//! Server-side verification of JWTs a client signs with a key from its JWKS: //! `private_key_jwt` client assertions (RFC 7523) and, through `typ` and //! `max_lifetime`, client attestations for permissioned spaces. Fetching the //! client's metadata and JWKS, and remembering `jti` against replay, stay with //! the server. const std = @import("std"); const Allocator = std.mem.Allocator; const jwt = @import("../crypto/jwt.zig"); const jwk = @import("../crypto/jwk.zig"); pub const Error = error{ InvalidClientAssertion, ClientAssertionAudienceMismatch, /// expired, too old, issued in the future, or living too long StaleClientAssertion, /// the JWKS has no key for the assertion's `kid` and `alg` ClientKeyNotFound, InvalidClientJwks, OutOfMemory, }; pub const Options = struct { /// the client the assertion must name as `iss` and `sub`; null accepts any /// client whose `iss` equals its `sub`, for a server that looks the client /// up by it before verifying the signature client_id: ?[]const u8 = null, /// the audience the assertion must name, alone or in an `aud` array audience: []const u8, /// unix seconds now: i64, /// a header `typ` the assertion must carry typ: ?[]const u8 = null, require_kid: bool = false, /// how old `iat` may be when the assertion has no `exp` max_age: i64 = 300, /// how far `iat` may be ahead of `now` max_future_skew: i64 = 60, /// when set, `iat` and `exp` are both required and `exp - iat` may not /// exceed it max_lifetime: ?i64 = null, }; pub const ClientAssertion = struct { parts: jwt.Decoded, alg: jwt.Algorithm, kid: ?[]const u8, client_id: []const u8, /// for the caller's replay store, until `exp` jti: []const u8, iat: ?i64, exp: ?i64, /// verify the JOSE signature (high-S accepted) with the key the /// assertion's `kid` and `alg` select from the client's JWKS document pub fn verifySignature(self: ClientAssertion, jwks: std.json.Value) Error!void { const key = jwk.selectFromJwks(jwks, self.kid, self.alg) catch |err| return switch (err) { error.KeyNotFound => error.ClientKeyNotFound, error.InvalidJwk, error.InvalidJwks => error.InvalidClientJwks, }; key.verifyJose(self.alg, self.parts.signing_input, self.parts.signature) catch return error.InvalidClientAssertion; } }; /// check an assertion's structure, claims and timing without its signature. /// `exp`, when present, must not have passed; without it, `iat` must be within /// `max_age`. Allocations belong to `arena`. pub fn parse(arena: Allocator, token: []const u8, options: Options) Error!ClientAssertion { const parts = jwt.decodeLeaky(arena, token) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidJwt => return error.InvalidClientAssertion, }; if (options.typ) |typ| { if (!std.mem.eql(u8, parts.headerString("typ") orelse return error.InvalidClientAssertion, typ)) return error.InvalidClientAssertion; } const alg = parts.algorithm() orelse return error.InvalidClientAssertion; const kid = parts.headerString("kid"); if (options.require_kid and kid == null) return error.InvalidClientAssertion; const iss = parts.claimString("iss") orelse return error.InvalidClientAssertion; const sub = parts.claimString("sub") orelse return error.InvalidClientAssertion; if (iss.len == 0 or !std.mem.eql(u8, iss, sub)) return error.InvalidClientAssertion; if (options.client_id) |client_id| { if (!std.mem.eql(u8, iss, client_id)) return error.InvalidClientAssertion; } const jti = parts.claimString("jti") orelse return error.InvalidClientAssertion; if (jti.len == 0) return error.InvalidClientAssertion; if (!namesAudience(parts.payload.object.get("aud") orelse return error.InvalidClientAssertion, options.audience)) return error.ClientAssertionAudienceMismatch; const iat = try optionalNumericDate(parts, "iat"); const exp = try optionalNumericDate(parts, "exp"); if (options.max_lifetime) |max_lifetime| { const issued = iat orelse return error.InvalidClientAssertion; const expires = exp orelse return error.InvalidClientAssertion; if (expires < issued or expires -| issued > max_lifetime) return error.StaleClientAssertion; } if (iat) |issued| { if (issued > options.now +| options.max_future_skew) return error.StaleClientAssertion; } if (exp) |expires| { if (expires < options.now) return error.StaleClientAssertion; } else { const issued = iat orelse return error.InvalidClientAssertion; if (options.now -| issued > options.max_age) return error.StaleClientAssertion; } return .{ .parts = parts, .alg = alg, .kid = kid, .client_id = iss, .jti = jti, .iat = iat, .exp = exp }; } /// `parse`, then `verifySignature` against the client's JWKS document. pub fn verify(arena: Allocator, token: []const u8, jwks: std.json.Value, options: Options) Error!ClientAssertion { const assertion = try parse(arena, token, options); try assertion.verifySignature(jwks); return assertion; } fn namesAudience(aud: std.json.Value, audience: []const u8) bool { return switch (aud) { .string => |s| std.mem.eql(u8, s, audience), .array => |array| for (array.items) |item| { if (item == .string and std.mem.eql(u8, item.string, audience)) break true; } else false, else => false, }; } fn optionalNumericDate(parts: jwt.Decoded, name: []const u8) Error!?i64 { if (parts.payload.object.get(name) == null) return null; return parts.claimNumericDate(name) orelse error.InvalidClientAssertion; } const testing = std.testing; const Keypair = @import("../crypto/keypair.zig").Keypair; const primitives = @import("primitives.zig"); const test_client = "https://client.example/oauth-client-metadata.json"; const issuer = "https://pds.example"; const now: i64 = 1_800_000_000; fn jwksFor(a: Allocator, keypair: *const Keypair) !std.json.Value { return std.json.parseFromSliceLeaky(std.json.Value, a, try primitives.jwksJson(a, keypair), .{}); } fn sign(a: Allocator, keypair: *const Keypair, header_json: []const u8, payload: []const u8) ![]u8 { return primitives.createJwt(a, header_json, payload, keypair); } fn header(a: Allocator, keypair: *const Keypair, typ: []const u8) ![]u8 { return std.fmt.allocPrint(a, "{{\"typ\":\"{s}\",\"alg\":\"{s}\",\"kid\":\"{s}\"}}", .{ typ, @tagName(keypair.algorithm()), try keypair.jwkThumbprint(a) }); } fn claims(a: Allocator, iss: []const u8, aud: []const u8, timing: []const u8) ![]u8 { return std.fmt.allocPrint(a, "{{\"iss\":\"{s}\",\"sub\":\"{s}\",\"aud\":{s},\"jti\":\"j1\"{s}}}", .{ iss, iss, aud, timing }); } test "a private_key_jwt assertion from createClientAssertion verifies" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const io = testing.io; for ([_]@import("../crypto/multicodec.zig").KeyType{ .p256, .secp256k1 }) |key_type| { const keypair = try Keypair.fromSecretKey(key_type, @splat(0x51)); const token = try primitives.createClientAssertion(a, io, &keypair, test_client, issuer); const clock: i64 = @intCast(@divFloor(std.Io.Timestamp.now(io, .real).nanoseconds, std.time.ns_per_s)); const assertion = try verify(a, token, try jwksFor(a, &keypair), .{ .client_id = test_client, .audience = issuer, .now = clock }); try testing.expectEqualStrings(test_client, assertion.client_id); try testing.expect(assertion.jti.len > 0); try testing.expectEqualStrings(try keypair.jwkThumbprint(a), assertion.kid.?); const other = try Keypair.fromSecretKey(key_type, @splat(0x52)); try testing.expectError(error.ClientKeyNotFound, verify(a, token, try jwksFor(a, &other), .{ .client_id = test_client, .audience = issuer, .now = clock })); try testing.expectError(error.InvalidClientAssertion, verify(a, token, try jwksFor(a, &keypair), .{ .client_id = "https://other.example", .audience = issuer, .now = clock })); try testing.expectError(error.ClientAssertionAudienceMismatch, verify(a, token, try jwksFor(a, &keypair), .{ .client_id = test_client, .audience = "https://other.example", .now = clock })); } } test "client assertion claims and timing" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.p256, @splat(0x51)); const h = try header(a, &keypair, "JWT"); const jwks = try jwksFor(a, &keypair); const options: Options = .{ .client_id = test_client, .audience = issuer, .now = now }; const aud = "\"" ++ issuer ++ "\""; _ = try verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"exp\":1800000060")), jwks, options); _ = try verify(a, try sign(a, &keypair, h, try claims(a, test_client, "[\"https://x.example\",\"" ++ issuer ++ "\"]", ",\"exp\":1800000060")), jwks, options); // without exp, iat decides _ = try verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":1799999700")), jwks, options); try testing.expectError(error.StaleClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":1799999699")), jwks, options)); try testing.expectError(error.InvalidClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, "")), jwks, options)); // expired, and issued in the future try testing.expectError(error.StaleClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"exp\":1799999999")), jwks, options)); try testing.expectError(error.StaleClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":1800000061,\"exp\":1800000120")), jwks, options)); try testing.expectError(error.InvalidClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"exp\":\"1800000060\"")), jwks, options)); // audience try testing.expectError(error.ClientAssertionAudienceMismatch, verify(a, try sign(a, &keypair, h, try claims(a, test_client, "[\"https://x.example\"]", ",\"exp\":1800000060")), jwks, options)); try testing.expectError(error.ClientAssertionAudienceMismatch, verify(a, try sign(a, &keypair, h, try claims(a, test_client, "1", ",\"exp\":1800000060")), jwks, options)); // iss and sub must both be the client const split = try std.fmt.allocPrint(a, "{{\"iss\":\"{s}\",\"sub\":\"https://other.example\",\"aud\":{s},\"jti\":\"j1\",\"exp\":1800000060}}", .{ test_client, aud }); try testing.expectError(error.InvalidClientAssertion, verify(a, try sign(a, &keypair, h, split), jwks, options)); var any_client = options; any_client.client_id = null; try testing.expectError(error.InvalidClientAssertion, verify(a, try sign(a, &keypair, h, split), jwks, any_client)); try testing.expectEqualStrings("https://any.example", (try verify(a, try sign(a, &keypair, h, try claims(a, "https://any.example", aud, ",\"exp\":1800000060")), jwks, any_client)).client_id); // jti const no_jti = try std.fmt.allocPrint(a, "{{\"iss\":\"{s}\",\"sub\":\"{s}\",\"aud\":{s},\"exp\":1800000060}}", .{ test_client, test_client, aud }); try testing.expectError(error.InvalidClientAssertion, verify(a, try sign(a, &keypair, h, no_jti), jwks, options)); } test "client assertion keys and signatures" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.p256, @splat(0x51)); const options: Options = .{ .client_id = test_client, .audience = issuer, .now = now }; const payload = try claims(a, test_client, "\"" ++ issuer ++ "\"", ",\"exp\":1800000060"); const token = try sign(a, &keypair, try header(a, &keypair, "JWT"), payload); // no kid: the first key on the curve is used, unless a kid is required const no_kid = try sign(a, &keypair, "{\"alg\":\"ES256\"}", payload); _ = try verify(a, no_kid, try jwksFor(a, &keypair), options); var kid_required = options; kid_required.require_kid = true; try testing.expectError(error.InvalidClientAssertion, parse(a, no_kid, kid_required)); // the JWKS key named by kid is off the curve const off_curve = try std.json.parseFromSliceLeaky(std.json.Value, a, try std.fmt.allocPrint(a, \\{{"keys":[{{"kty":"EC","crv":"P-256","kid":"{s}","x":"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M","y":"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eA"}}]}} , .{try keypair.jwkThumbprint(a)}), .{}); try testing.expectError(error.InvalidClientJwks, verify(a, token, off_curve, options)); // a signature by another key under this kid const other = try Keypair.fromSecretKey(.p256, @splat(0x52)); const forged = try sign(a, &other, try header(a, &keypair, "JWT"), payload); try testing.expectError(error.InvalidClientAssertion, verify(a, forged, try jwksFor(a, &keypair), options)); // high-S is a valid JOSE signature const sig_start = std.mem.lastIndexOfScalar(u8, token, '.').? + 1; var signature = try jwt.base64UrlDecode(a, token[sig_start..]); signature[32..64].* = try std.crypto.ecc.P256.scalar.neg(signature[32..64].*, .big); _ = try verify(a, try std.mem.concat(a, u8, &.{ token[0..sig_start], try jwt.base64UrlEncode(a, signature) }), try jwksFor(a, &keypair), options); } test "client attestations: typ, kid and a bounded lifetime" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.p256, @splat(0x51)); const jwks = try jwksFor(a, &keypair); const space_host = "did:plc:alice#atproto_pds"; const options: Options = .{ .audience = space_host, .now = now, .typ = "atproto-client-attestation+jwt", .require_kid = true, .max_lifetime = 300, }; const aud = "\"" ++ space_host ++ "\""; const h = try header(a, &keypair, "atproto-client-attestation+jwt"); const attestation = try verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":1799999990,\"exp\":1800000050")), jwks, options); try testing.expectEqualStrings(test_client, attestation.client_id); try testing.expectEqual(@as(?i64, 1800000050), attestation.exp); try testing.expectError(error.InvalidClientAssertion, verify(a, try sign(a, &keypair, try header(a, &keypair, "JWT"), try claims(a, test_client, aud, ",\"iat\":1799999990,\"exp\":1800000050")), jwks, options)); try testing.expectError(error.InvalidClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"exp\":1800000050")), jwks, options)); try testing.expectError(error.StaleClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":1799999990,\"exp\":1800000291")), jwks, options)); try testing.expectError(error.StaleClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":1800000050,\"exp\":1800000040")), jwks, options)); } test "client assertion dates are JSON numbers, floored" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.p256, @splat(0x51)); const jwks = try jwksFor(a, &keypair); const h = try header(a, &keypair, "JWT"); const aud = "\"" ++ issuer ++ "\""; const options: Options = .{ .client_id = test_client, .audience = issuer, .now = now }; const assertion = try verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":1799999999.5,\"exp\":1800000060.9")), jwks, options); try testing.expectEqual(@as(?i64, 1799999999), assertion.iat); try testing.expectEqual(@as(?i64, 1800000060), assertion.exp); // a far-past iat cannot overflow the age check try testing.expectError(error.StaleClientAssertion, verify(a, try sign(a, &keypair, h, try claims(a, test_client, aud, ",\"iat\":-1e300")), jwks, options)); }