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
//! Space tokens: a requester's PDS signs a delegation token naming the space
//! host as audience; the space authority exchanges it for a space credential
//! bound to the holder's P-256 key (`cnf.kid`). Mirrors `@atproto/space`
//! `credential.ts`. Client attestations are signed with a client's JWKS key,
//! so only their structure is checked here.
const std = @import("std");
const jwt = @import("../crypto/jwt.zig");
const multicodec = @import("../crypto/multicodec.zig");
const Keypair = @import("../crypto/keypair.zig").Keypair;
const Did = @import("../syntax/did.zig").Did;
const json = @import("../xrpc/json.zig");
pub const Error = error{ InvalidSpaceToken, ExpiredSpaceToken, OutOfMemory };
pub const clock_skew_s = 5;
pub const credential_max_age_s = 3600;
pub const Type = enum {
delegation,
credential,
client_attestation,
pub fn typ(self: Type) []const u8 {
return switch (self) {
.delegation => "atproto-space-delegation+jwt",
.credential => "atproto-space-credential+jwt",
.client_attestation => "atproto-client-attestation+jwt",
};
}
fn kid(self: Type) ?[]const u8 {
return switch (self) {
.delegation, .credential => "#atproto",
.client_attestation => null,
};
}
pub fn lifetime(self: Type) i64 {
return switch (self) {
.delegation, .client_attestation => 60,
.credential => 600,
};
}
};
/// The audience a delegation token and a client attestation name: the space
/// authority's PDS service entry, since the space host is its PDS.
pub fn spaceHostAud(allocator: std.mem.Allocator, space_did: []const u8) ![]u8 {
return std.fmt.allocPrint(allocator, "{s}#atproto_pds", .{space_did});
}
/// The space DID a `spaceHostAud` audience names.
pub fn spaceDidFromAud(aud: []const u8) ?[]const u8 {
const did = if (std.mem.endsWith(u8, aud, "#atproto_pds")) aud[0 .. aud.len - "#atproto_pds".len] else return null;
return if (Did.parse(did) != null) did else null;
}
pub const Claims = struct {
iss: []const u8,
sub: []const u8,
aud: ?[]const u8 = null,
/// The holder key a credential is bound to.
cnf_kid: ?[]const u8 = null,
iat: i64,
exp: i64,
jti: []const u8,
};
pub const Token = struct {
alg: jwt.Algorithm,
kid: ?[]const u8,
claims: Claims,
signing_input: []const u8,
signature: []const u8,
};
/// Sign a token of `token_type` with the issuer's key. `iat` is now, in unix
/// seconds; `exp` follows from the type's lifetime unless given.
pub fn create(allocator: std.mem.Allocator, io: std.Io, token_type: Type, keypair: *const Keypair, claims: struct {
iss: []const u8,
sub: []const u8,
aud: ?[]const u8 = null,
cnf_kid: ?[]const u8 = null,
iat: i64,
expires_in: ?i64 = null,
}) ![]u8 {
const expires_in = claims.expires_in orelse token_type.lifetime();
if (token_type == .credential and (claims.cnf_kid == null or expires_in <= 0 or expires_in > credential_max_age_s)) return error.InvalidSpaceToken;
var jti_bytes: [16]u8 = undefined;
io.random(&jti_bytes);
const jti = std.fmt.bytesToHex(jti_bytes, .lower);
var header: std.Io.Writer.Allocating = .init(allocator);
defer header.deinit();
try header.writer.print("{{\"alg\":\"{s}\",\"typ\":\"{s}\"", .{ @tagName(keypair.algorithm()), token_type.typ() });
if (token_type.kid()) |kid| try header.writer.print(",\"kid\":\"{s}\"", .{kid});
try header.writer.writeByte('}');
var payload: std.Io.Writer.Allocating = .init(allocator);
defer payload.deinit();
const w = &payload.writer;
try w.print("{{\"iss\":{f},\"sub\":{f}", .{ std.json.fmt(claims.iss, .{}), std.json.fmt(claims.sub, .{}) });
if (claims.aud) |aud| try w.print(",\"aud\":{f}", .{std.json.fmt(aud, .{})});
if (claims.cnf_kid) |kid| try w.print(",\"cnf\":{{\"kid\":{f}}}", .{std.json.fmt(kid, .{})});
try w.print(",\"iat\":{d},\"exp\":{d},\"jti\":\"{s}\"}}", .{ claims.iat, claims.iat + expires_in, jti });
const header_b64 = try jwt.base64UrlEncode(allocator, header.written());
defer allocator.free(header_b64);
const payload_b64 = try jwt.base64UrlEncode(allocator, payload.written());
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 signature = try keypair.sign(signing_input);
const signature_b64 = try jwt.base64UrlEncode(allocator, &signature.bytes);
defer allocator.free(signature_b64);
return std.fmt.allocPrint(allocator, "{s}.{s}", .{ signing_input, signature_b64 });
}
/// Structural checks only, no signature check: as far as a client attestation
/// goes, since its key comes from the client's JWKS. Allocations belong to
/// `arena`.
pub fn parse(arena: std.mem.Allocator, token_type: Type, token: []const u8) Error!Token {
var parts = std.mem.splitScalar(u8, token, '.');
const header_b64 = parts.next() orelse return error.InvalidSpaceToken;
const payload_b64 = parts.next() orelse return error.InvalidSpaceToken;
const signature_b64 = parts.next() orelse return error.InvalidSpaceToken;
if (parts.next() != null) return error.InvalidSpaceToken;
const header = try jsonPart(arena, header_b64);
const payload = try jsonPart(arena, payload_b64);
if (!std.mem.eql(u8, json.getString(header, "typ") orelse return error.InvalidSpaceToken, token_type.typ())) return error.InvalidSpaceToken;
const alg = jwt.Algorithm.fromString(json.getString(header, "alg") orelse return error.InvalidSpaceToken) orelse return error.InvalidSpaceToken;
const kid = json.getString(header, "kid");
if (token_type.kid()) |required| {
if (!std.mem.eql(u8, kid orelse return error.InvalidSpaceToken, required)) return error.InvalidSpaceToken;
}
const claims: Claims = .{
.iss = nonEmpty(json.getString(payload, "iss")) orelse return error.InvalidSpaceToken,
.sub = nonEmpty(json.getString(payload, "sub")) orelse return error.InvalidSpaceToken,
.aud = nonEmpty(json.getString(payload, "aud")),
.cnf_kid = json.getString(payload, "cnf.kid"),
.iat = numericDate(payload, "iat") orelse 0,
.exp = numericDate(payload, "exp") orelse return error.InvalidSpaceToken,
.jti = nonEmpty(json.getString(payload, "jti")) orelse return error.InvalidSpaceToken,
};
switch (token_type) {
.delegation => if (claims.aud == null) return error.InvalidSpaceToken,
.client_attestation => if (claims.aud == null or !std.mem.eql(u8, claims.iss, claims.sub)) return error.InvalidSpaceToken,
.credential => {
if (Did.parse(claims.cnf_kid orelse return error.InvalidSpaceToken) == null) return error.InvalidSpaceToken;
if (numericDate(payload, "iat") == null or claims.exp <= claims.iat or claims.exp - claims.iat > credential_max_age_s) return error.InvalidSpaceToken;
},
}
return .{
.alg = alg,
.kid = kid,
.claims = claims,
.signing_input = token[0 .. header_b64.len + 1 + payload_b64.len],
.signature = jwt.base64UrlDecode(arena, signature_b64) catch return error.InvalidSpaceToken,
};
}
pub const VerifyOptions = struct {
/// The issuer's `#atproto` signing key, as a did:key.
signing_key: []const u8,
/// Unix seconds.
now: i64,
aud: ?[]const u8 = null,
sub: ?[]const u8 = null,
};
/// Parse, check timing and claims, and verify the issuer's low-S signature.
/// A caller that finds the signature invalid may retry once with a freshly
/// resolved key, in case the issuer rotated it.
pub fn verify(arena: std.mem.Allocator, token_type: Type, token: []const u8, options: VerifyOptions) Error!Token {
const parsed = try parse(arena, token_type, token);
const claims = parsed.claims;
if (token_type == .credential and claims.iat > options.now + clock_skew_s) return error.InvalidSpaceToken;
if (options.now - clock_skew_s >= claims.exp) return error.ExpiredSpaceToken;
if (options.aud) |aud| {
if (!std.mem.eql(u8, claims.aud orelse return error.InvalidSpaceToken, aud)) return error.InvalidSpaceToken;
}
if (options.sub) |sub| {
if (!std.mem.eql(u8, claims.sub, sub)) return error.InvalidSpaceToken;
}
if (token_type == .credential) {
const holder = multicodec.parseDidKey(arena, claims.cnf_kid.?) catch return error.InvalidSpaceToken;
if (holder.key_type != .p256) return error.InvalidSpaceToken;
}
const key = multicodec.parseDidKey(arena, options.signing_key) catch return error.InvalidSpaceToken;
switch (parsed.alg) {
.ES256 => {
if (key.key_type != .p256) return error.InvalidSpaceToken;
jwt.verifyP256(parsed.signing_input, parsed.signature, key.raw) catch return error.InvalidSpaceToken;
},
.ES256K => {
if (key.key_type != .secp256k1) return error.InvalidSpaceToken;
jwt.verifySecp256k1(parsed.signing_input, parsed.signature, key.raw) catch return error.InvalidSpaceToken;
},
}
return parsed;
}
fn jsonPart(arena: std.mem.Allocator, b64: []const u8) Error!std.json.Value {
const bytes = jwt.base64UrlDecode(arena, b64) catch return error.InvalidSpaceToken;
const value = std.json.parseFromSliceLeaky(std.json.Value, arena, bytes, .{}) catch return error.InvalidSpaceToken;
return if (value == .object) value else error.InvalidSpaceToken;
}
fn nonEmpty(value: ?[]const u8) ?[]const u8 {
const v = value orelse return null;
return if (v.len == 0) null else v;
}
fn numericDate(payload: std.json.Value, name: []const u8) ?i64 {
return switch (json.getPath(payload, name) orelse return null) {
.integer => |n| n,
.float => |n| if (std.math.isFinite(n) and @abs(n) < 1e15) @intFromFloat(@floor(n)) else null,
else => null,
};
}
const testing = std.testing;
test "delegation tokens and credentials round trip and bind their claims" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const io = testing.io;
var authority = try Keypair.fromSecretKey(.secp256k1, @splat(0x21));
var requester = try Keypair.fromSecretKey(.p256, @splat(0x22));
var holder = try Keypair.fromSecretKey(.p256, @splat(0x23));
const space = "at:space/did:plc:alice/fm.example.private/self";
const aud = try spaceHostAud(a, "did:plc:alice");
const now: i64 = 1_800_000_000;
const delegation = try create(a, io, .delegation, &requester, .{ .iss = "did:plc:bob", .sub = space, .aud = aud, .iat = now });
const verified = try verify(a, .delegation, delegation, .{ .signing_key = try requester.did(a), .now = now, .aud = aud, .sub = space });
try testing.expectEqualStrings("did:plc:bob", verified.claims.iss);
try testing.expectEqualStrings("did:plc:alice", spaceDidFromAud(verified.claims.aud.?).?);
try testing.expectEqual(now + 60, verified.claims.exp);
try testing.expectError(error.InvalidSpaceToken, verify(a, .delegation, delegation, .{ .signing_key = try requester.did(a), .now = now, .aud = "did:plc:carol#atproto_pds" }));
try testing.expectError(error.ExpiredSpaceToken, verify(a, .delegation, delegation, .{ .signing_key = try requester.did(a), .now = now + 65 }));
try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, delegation, .{ .signing_key = try requester.did(a), .now = now }));
const credential = try create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .cnf_kid = try holder.did(a), .iat = now });
const cred = try verify(a, .credential, credential, .{ .signing_key = try authority.did(a), .now = now + 599, .sub = space });
try testing.expectEqualStrings(try holder.did(a), cred.claims.cnf_kid.?);
try testing.expectEqualStrings("#atproto", cred.kid.?);
try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, credential, .{ .signing_key = try requester.did(a), .now = now }));
try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, credential, .{ .signing_key = try authority.did(a), .now = now - 6 }));
try testing.expectError(error.ExpiredSpaceToken, verify(a, .credential, credential, .{ .signing_key = try authority.did(a), .now = now + 605 }));
}
test "credentials need a P-256 holder key and a bounded lifetime" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const a = arena.allocator();
const io = testing.io;
var authority = try Keypair.fromSecretKey(.p256, @splat(0x21));
var k256 = try Keypair.fromSecretKey(.secp256k1, @splat(0x23));
const space = "at:space/did:plc:alice/fm.example.private/self";
try testing.expectError(error.InvalidSpaceToken, create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .iat = 0 }));
try testing.expectError(error.InvalidSpaceToken, create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .cnf_kid = try k256.did(a), .iat = 0, .expires_in = 3601 }));
const bound_to_k256 = try create(a, io, .credential, &authority, .{ .iss = "did:plc:alice", .sub = space, .cnf_kid = try k256.did(a), .iat = 0 });
try testing.expectError(error.InvalidSpaceToken, verify(a, .credential, bound_to_k256, .{ .signing_key = try authority.did(a), .now = 0 }));
}
test "client attestations name the client as issuer and subject" {
var arena = std.heap.ArenaAllocator.init(testing.allocator);
defer arena.deinit();
const a = arena.allocator();
var client = try Keypair.fromSecretKey(.p256, @splat(0x31));
const id = "https://client.example/client-metadata.json";
const token = try create(a, testing.io, .client_attestation, &client, .{ .iss = id, .sub = id, .aud = "did:plc:alice#atproto_pds", .iat = 0 });
const parsed = try parse(a, .client_attestation, token);
try testing.expectEqualStrings(id, parsed.claims.sub);
try testing.expect(parsed.kid == null);
const mismatched = try create(a, testing.io, .client_attestation, &client, .{ .iss = id, .sub = "https://other.example", .aud = "did:plc:alice#atproto_pds", .iat = 0 });
try testing.expectError(error.InvalidSpaceToken, parse(a, .client_attestation, mismatched));
}