1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
//! OAuth client primitives for AT Protocol.
//!
//! PKCE, DPoP proofs, client assertions, form encoding, and related helpers
//! for implementing AT Protocol OAuth flows.
const std = @import("std");
const crypto = std.crypto;
const Io = std.Io;
const Allocator = std.mem.Allocator;
const Keypair = @import("../crypto/keypair.zig").Keypair;
const jwt = @import("../crypto/jwt.zig");
fn timestamp(io: Io) i64 {
return @intCast(@divFloor(Io.Timestamp.now(io, .real).nanoseconds, std.time.ns_per_s));
}
/// create a signed JWT from header and payload JSON strings.
/// caller owns returned slice.
pub fn createJwt(allocator: Allocator, header_json: []const u8, payload_json: []const u8, keypair: *const Keypair) ![]u8 {
const header_b64 = try jwt.base64UrlEncode(allocator, header_json);
defer allocator.free(header_b64);
const payload_b64 = try jwt.base64UrlEncode(allocator, payload_json);
defer allocator.free(payload_b64);
const signing_input = try std.fmt.allocPrint(allocator, "{s}.{s}", .{ header_b64, payload_b64 });
defer allocator.free(signing_input);
const sig = try keypair.sign(signing_input);
const sig_b64 = try jwt.base64UrlEncode(allocator, &sig.bytes);
defer allocator.free(sig_b64);
return std.fmt.allocPrint(allocator, "{s}.{s}", .{ signing_input, sig_b64 });
}
/// create a DPoP proof JWT per RFC 9449.
/// htm: HTTP method, htu: target URI, nonce: server-provided DPoP-Nonce,
/// ath: optional access token hash (base64url-encoded SHA-256).
pub fn createDpopProof(
allocator: Allocator,
io: std.Io,
keypair: *const Keypair,
htm: []const u8,
htu: []const u8,
nonce: ?[]const u8,
ath: ?[]const u8,
) ![]u8 {
const jwk_json = try keypair.jwk(allocator);
defer allocator.free(jwk_json);
const jti = try generateJti(allocator, io);
defer allocator.free(jti);
const alg = @tagName(keypair.algorithm());
const now = timestamp(io);
const header = try std.fmt.allocPrint(allocator,
\\{{"typ":"dpop+jwt","alg":"{s}","jwk":{s}}}
, .{ alg, jwk_json });
defer allocator.free(header);
var aw: std.Io.Writer.Allocating = .init(allocator);
defer aw.deinit();
try aw.writer.print(
\\{{"jti":"{s}","htm":{f},"htu":{f},"iat":{d}
, .{ jti, std.json.fmt(htm, .{}), std.json.fmt(htu, .{}), now });
if (nonce) |n| {
try aw.writer.print(",\"nonce\":{f}", .{std.json.fmt(n, .{})});
}
if (ath) |a| {
try aw.writer.print(",\"ath\":{f}", .{std.json.fmt(a, .{})});
}
try aw.writer.writeAll("}");
return createJwt(allocator, header, aw.written(), keypair);
}
/// create a private_key_jwt client assertion for token endpoint auth.
/// client_id: the OAuth client ID, aud: the token endpoint URL.
pub fn createClientAssertion(
allocator: Allocator,
io: std.Io,
keypair: *const Keypair,
client_id: []const u8,
aud: []const u8,
) ![]u8 {
const jti = try generateJti(allocator, io);
defer allocator.free(jti);
const kid = try keypair.jwkThumbprint(allocator);
defer allocator.free(kid);
const alg = @tagName(keypair.algorithm());
const now = timestamp(io);
const header = try std.fmt.allocPrint(allocator,
\\{{"typ":"JWT","alg":"{s}","kid":"{s}"}}
, .{ alg, kid });
defer allocator.free(header);
const payload = try std.fmt.allocPrint(allocator,
\\{{"iss":{f},"sub":{f},"aud":{f},"jti":"{s}","iat":{d},"exp":{d}}}
, .{ std.json.fmt(client_id, .{}), std.json.fmt(client_id, .{}), std.json.fmt(aud, .{}), jti, now, now + 120 });
defer allocator.free(payload);
return createJwt(allocator, header, payload, keypair);
}
/// generate a random PKCE code verifier (43 chars, base64url-encoded 32 random bytes).
/// caller owns returned slice.
pub fn generatePkceVerifier(allocator: Allocator, io: std.Io) ![]u8 {
var random_bytes: [32]u8 = undefined;
io.random(&random_bytes);
return jwt.base64UrlEncode(allocator, &random_bytes);
}
/// generate a PKCE S256 challenge from a verifier.
/// caller owns returned slice.
pub fn generatePkceChallenge(allocator: Allocator, verifier: []const u8) ![]u8 {
var hash: [32]u8 = undefined;
crypto.hash.sha2.Sha256.hash(verifier, &hash, .{});
return jwt.base64UrlEncode(allocator, &hash);
}
/// generate a random state parameter (CSRF token).
/// caller owns returned slice.
pub fn generateState(allocator: Allocator, io: std.Io) ![]u8 {
var random_bytes: [16]u8 = undefined;
io.random(&random_bytes);
return jwt.base64UrlEncode(allocator, &random_bytes);
}
/// compute access token hash for DPoP ath claim: base64url(SHA-256(access_token)).
/// caller owns returned slice.
pub fn accessTokenHash(allocator: Allocator, access_token: []const u8) ![]u8 {
var hash: [32]u8 = undefined;
crypto.hash.sha2.Sha256.hash(access_token, &hash, .{});
return jwt.base64UrlEncode(allocator, &hash);
}
/// encode key-value pairs as application/x-www-form-urlencoded.
/// caller owns returned slice.
pub fn formEncode(allocator: Allocator, params: []const [2][]const u8) ![]u8 {
var aw: std.Io.Writer.Allocating = .init(allocator);
errdefer aw.deinit();
for (params, 0..) |kv, i| {
if (i > 0) try aw.writer.writeAll("&");
try percentEncode(&aw.writer, kv[0]);
try aw.writer.writeAll("=");
try percentEncode(&aw.writer, kv[1]);
}
return try aw.toOwnedSlice();
}
/// format a JWKS JSON containing a single public key.
/// caller owns returned slice.
pub fn jwksJson(allocator: Allocator, keypair: *const Keypair) ![]u8 {
const jwk_json = try keypair.jwk(allocator);
defer allocator.free(jwk_json);
return std.fmt.allocPrint(allocator,
\\{{"keys":[{s}]}}
, .{jwk_json});
}
/// percent-encode `input` per RFC 3986: unreserved characters (ALPHA, DIGIT,
/// "-", ".", "_", "~") pass through, every other byte becomes `%XX` with
/// uppercase hex. safe for query values, form fields and single path segments.
pub fn percentEncode(writer: anytype, input: []const u8) !void {
for (input) |c| {
if (isUnreserved(c)) {
try writer.writeByte(c);
} else {
try writer.print("%{X:0>2}", .{c});
}
}
}
/// `percentEncode` into a new slice. caller owns the returned slice.
pub fn percentEncodeAlloc(allocator: Allocator, input: []const u8) ![]u8 {
var out: std.Io.Writer.Allocating = .init(allocator);
errdefer out.deinit();
try percentEncode(&out.writer, input);
return out.toOwnedSlice();
}
fn generateJti(allocator: Allocator, io: std.Io) ![]u8 {
var random_bytes: [16]u8 = undefined;
io.random(&random_bytes);
return jwt.base64UrlEncode(allocator, &random_bytes);
}
fn isUnreserved(c: u8) bool {
return switch (c) {
'A'...'Z', 'a'...'z', '0'...'9', '-', '_', '.', '~' => true,
else => false,
};
}
test "PKCE S256 challenge - RFC 7636 test vector" {
const allocator = std.testing.allocator;
const verifier = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk";
const challenge = try generatePkceChallenge(allocator, verifier);
defer allocator.free(challenge);
try std.testing.expectEqualStrings("E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM", challenge);
}
test "PKCE verifier is 43 chars" {
const allocator = std.testing.allocator;
const io = std.Options.debug_io;
const verifier = try generatePkceVerifier(allocator, io);
defer allocator.free(verifier);
try std.testing.expectEqual(@as(usize, 43), verifier.len);
}
test "form URL encoding" {
const allocator = std.testing.allocator;
const params = [_][2][]const u8{
.{ "grant_type", "authorization_code" },
.{ "code", "abc123" },
.{ "redirect_uri", "https://example.com/callback" },
};
const encoded = try formEncode(allocator, ¶ms);
defer allocator.free(encoded);
try std.testing.expectEqualStrings(
"grant_type=authorization_code&code=abc123&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback",
encoded,
);
}
test "percent encoding keeps RFC 3986 unreserved bytes and escapes the rest" {
const allocator = std.testing.allocator;
const unreserved = "AZaz09-._~";
const kept = try percentEncodeAlloc(allocator, unreserved);
defer allocator.free(kept);
try std.testing.expectEqualStrings(unreserved, kept);
const escaped = try percentEncodeAlloc(allocator, "did:plc:x/y z+%\xff");
defer allocator.free(escaped);
try std.testing.expectEqualStrings("did%3Aplc%3Ax%2Fy%20z%2B%25%FF", escaped);
const empty = try percentEncodeAlloc(allocator, "");
defer allocator.free(empty);
try std.testing.expectEqualStrings("", empty);
}
test "access token hash" {
const allocator = std.testing.allocator;
const ath = try accessTokenHash(allocator, "test-access-token");
defer allocator.free(ath);
try std.testing.expectEqual(@as(usize, 43), ath.len);
}
test "createJwt sign and verify round-trip" {
const allocator = std.testing.allocator;
const multibase = @import("../crypto/multibase.zig");
const multicodec = @import("../crypto/multicodec.zig");
const keypair = try Keypair.fromSecretKey(.p256, .{
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
});
const header =
\\{"alg":"ES256","typ":"JWT"}
;
const payload =
\\{"iss":"did:example:test","aud":"did:example:aud","exp":9999999999}
;
const token = try createJwt(allocator, header, payload, &keypair);
defer allocator.free(token);
var parsed_jwt = try jwt.Jwt.parse(allocator, token);
defer parsed_jwt.deinit();
try std.testing.expectEqual(jwt.Algorithm.ES256, parsed_jwt.header.alg);
try std.testing.expectEqualStrings("did:example:test", parsed_jwt.payload.iss);
const pk = try keypair.publicKey();
const mc_bytes = try multicodec.encodePublicKey(allocator, .p256, &pk);
defer allocator.free(mc_bytes);
const multibase_key = try multibase.encode(allocator, .base58btc, mc_bytes);
defer allocator.free(multibase_key);
try parsed_jwt.verify(multibase_key);
}
test "DPoP proof structure" {
const allocator = std.testing.allocator;
const io = std.Options.debug_io;
const keypair = try Keypair.fromSecretKey(.p256, .{
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
});
const proof = try createDpopProof(allocator, io, &keypair, "POST", "https://auth.example.com/token", "server-nonce", null);
defer allocator.free(proof);
var iter = std.mem.splitScalar(u8, proof, '.');
const header_b64 = iter.next().?;
const payload_b64 = iter.next().?;
const header_json = try jwt.base64UrlDecode(allocator, header_b64);
defer allocator.free(header_json);
const header_parsed = try std.json.parseFromSlice(std.json.Value, allocator, header_json, .{});
defer header_parsed.deinit();
try std.testing.expectEqualStrings("dpop+jwt", header_parsed.value.object.get("typ").?.string);
try std.testing.expectEqualStrings("ES256", header_parsed.value.object.get("alg").?.string);
try std.testing.expect(header_parsed.value.object.get("jwk") != null);
const payload_json = try jwt.base64UrlDecode(allocator, payload_b64);
defer allocator.free(payload_json);
const payload_parsed = try std.json.parseFromSlice(std.json.Value, allocator, payload_json, .{});
defer payload_parsed.deinit();
const obj = payload_parsed.value.object;
try std.testing.expect(obj.get("jti") != null);
try std.testing.expectEqualStrings("POST", obj.get("htm").?.string);
try std.testing.expectEqualStrings("https://auth.example.com/token", obj.get("htu").?.string);
try std.testing.expect(obj.get("iat") != null);
try std.testing.expectEqualStrings("server-nonce", obj.get("nonce").?.string);
}
test "client assertion structure" {
const allocator = std.testing.allocator;
const io = std.Options.debug_io;
const keypair = try Keypair.fromSecretKey(.p256, .{
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
});
const assertion = try createClientAssertion(allocator, io, &keypair, "https://app.example.com/client-metadata", "https://bsky.social/oauth/token");
defer allocator.free(assertion);
var iter = std.mem.splitScalar(u8, assertion, '.');
const header_b64 = iter.next().?;
const payload_b64 = iter.next().?;
const header_json = try jwt.base64UrlDecode(allocator, header_b64);
defer allocator.free(header_json);
const header_parsed = try std.json.parseFromSlice(std.json.Value, allocator, header_json, .{});
defer header_parsed.deinit();
try std.testing.expectEqualStrings("JWT", header_parsed.value.object.get("typ").?.string);
try std.testing.expectEqualStrings("ES256", header_parsed.value.object.get("alg").?.string);
try std.testing.expect(header_parsed.value.object.get("kid") != null);
const payload_json = try jwt.base64UrlDecode(allocator, payload_b64);
defer allocator.free(payload_json);
const payload_parsed = try std.json.parseFromSlice(std.json.Value, allocator, payload_json, .{});
defer payload_parsed.deinit();
const obj = payload_parsed.value.object;
try std.testing.expectEqualStrings("https://app.example.com/client-metadata", obj.get("iss").?.string);
try std.testing.expectEqualStrings("https://app.example.com/client-metadata", obj.get("sub").?.string);
try std.testing.expectEqualStrings("https://bsky.social/oauth/token", obj.get("aud").?.string);
try std.testing.expect(obj.get("jti") != null);
try std.testing.expect(obj.get("iat") != null);
try std.testing.expect(obj.get("exp") != null);
}
test "JWKS JSON wraps JWK" {
const allocator = std.testing.allocator;
const keypair = try Keypair.fromSecretKey(.p256, .{
0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28,
0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f, 0x30,
0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38,
0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f, 0x40,
});
const jwks = try jwksJson(allocator, &keypair);
defer allocator.free(jwks);
const parsed = try std.json.parseFromSlice(std.json.Value, allocator, jwks, .{});
defer parsed.deinit();
const keys = parsed.value.object.get("keys").?.array;
try std.testing.expectEqual(@as(usize, 1), keys.items.len);
try std.testing.expectEqualStrings("EC", keys.items[0].object.get("kty").?.string);
}
test "DPoP proofs and client assertions JSON-encode caller strings" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const io = std.testing.io;
const keypair = try Keypair.fromSecretKey(.p256, @splat(0x21));
const htu = "https://pds.example/x\"y\\z";
const proof = try createDpopProof(a, io, &keypair, "POST", htu, "n\"1", null);
const proof_parts = try jwt.decodeLeaky(a, proof);
try std.testing.expectEqualStrings(htu, proof_parts.claimString("htu").?);
try std.testing.expectEqualStrings("n\"1", proof_parts.claimString("nonce").?);
const client_id = "https://client.example/\"meta\".json";
const assertion = try createClientAssertion(a, io, &keypair, client_id, "https://pds.example/\\");
const assertion_parts = try jwt.decodeLeaky(a, assertion);
try std.testing.expectEqualStrings(client_id, assertion_parts.claimString("iss").?);
try std.testing.expectEqualStrings(client_id, assertion_parts.claimString("sub").?);
try std.testing.expectEqualStrings("https://pds.example/\\", assertion_parts.claimString("aud").?);
}