//! Inter-service auth JWTs (https://atproto.com/specs/xrpc#inter-service-authentication-jwt): //! a service signs a short-lived token with an account's `#atproto` key, naming //! the receiving service as `aud` and the called method as `lxm`. const std = @import("std"); const Allocator = std.mem.Allocator; const jwt = @import("../crypto/jwt.zig"); const Keypair = @import("../crypto/keypair.zig").Keypair; const oauth_primitives = @import("../oauth/primitives.zig"); const multibase = @import("../crypto/multibase.zig"); const multicodec = @import("../crypto/multicodec.zig"); const Did = @import("../syntax/did.zig").Did; pub const default_lifetime_s = 60; pub const Claims = struct { /// the account's DID, or `did#service` for a service identity iss: []const u8, aud: []const u8, lxm: ?[]const u8 = null, sub: ?[]const u8 = null, /// unix seconds; now when null iat: ?i64 = null, /// unix seconds; `default_lifetime_s` after `iat` when null exp: ?i64 = null, /// 16 random bytes as hex when null jti: ?[]const u8 = null, }; /// sign a service auth JWT with `keypair`, JSON-encoding every claim. The /// caller owns the returned token. pub fn create(allocator: Allocator, io: std.Io, keypair: *const Keypair, claims: Claims) ![]u8 { const iat = claims.iat orelse @as(i64, @intCast(@divFloor(std.Io.Timestamp.now(io, .real).nanoseconds, std.time.ns_per_s))); const exp = claims.exp orelse iat + default_lifetime_s; var random_jti: [32]u8 = undefined; const jti = claims.jti orelse blk: { var bytes: [16]u8 = undefined; io.random(&bytes); random_jti = std.fmt.bytesToHex(bytes, .lower); break :blk &random_jti; }; var header_buf: [32]u8 = undefined; const header = std.fmt.bufPrint(&header_buf, "{{\"typ\":\"JWT\",\"alg\":\"{s}\"}}", .{@tagName(keypair.algorithm())}) catch unreachable; var payload: std.Io.Writer.Allocating = .init(allocator); defer payload.deinit(); const w = &payload.writer; try w.print("{{\"iat\":{d},\"iss\":{f}", .{ iat, std.json.fmt(claims.iss, .{}) }); if (claims.sub) |sub| try w.print(",\"sub\":{f}", .{std.json.fmt(sub, .{})}); try w.print(",\"aud\":{f},\"exp\":{d}", .{ std.json.fmt(claims.aud, .{}), exp }); if (claims.lxm) |lxm| try w.print(",\"lxm\":{f}", .{std.json.fmt(lxm, .{})}); try w.print(",\"jti\":{f}}}", .{std.json.fmt(jti, .{})}); return oauth_primitives.createJwt(allocator, header, payload.written(), keypair); } /// failures named after the reference implementation's error codes pub const Error = error{ BadJwt, /// an OAuth access or refresh token or a DPoP proof presented as service auth BadJwtType, JwtExpired, BadJwtAudience, BadJwtLexiconMethod, BadJwtIss, BadJwtSignature, OutOfMemory, }; pub const VerifyOptions = struct { /// unix seconds now: i64, /// the audiences this service answers to, such as its DID and /// `did#atproto_pds`; null leaves `aud` to the caller audiences: ?[]const []const u8, /// the method being called, which `lxm` must name exactly; null skips the /// check lxm: ?[]const u8, /// the DID the issuer must be, checked before its key is resolved issuer: ?[]const u8 = null, }; pub const Verified = struct { /// `iss` as given, possibly `did#service` iss: []const u8, /// `iss` without its fragment issuer_did: []const u8, aud: []const u8, lxm: ?[]const u8, jti: ?[]const u8, exp: i64, alg: jwt.Algorithm, }; /// what `verify` asks the caller's resolver for pub const KeyRequest = struct { did: []const u8, /// `#atproto`, or `#atproto_label` when `iss` is `did#atproto_labeler` key_id: []const u8, /// set on the second request, made after the first key failed to verify /// the signature, so a cached DID document is bypassed force_refresh: bool, }; /// verify a service auth JWT as the reference `verifyJwt` does: three parts /// with an `alg`, a `typ` other than `at+jwt`, `refresh+jwt` or `dpop+jwt`, /// string `iss` and `aud`, a numeric `exp` not before `now`, an accepted /// `aud`, `lxm` equal to the called method (no wildcards), and `iss` a DID /// with at most one non-empty fragment. The signature is JOSE (high-S /// accepted) under the issuer's key, which `resolver.resolveSigningKey(arena, /// KeyRequest)` returns as a multibase multikey or a did:key; when it does not /// verify, the key is requested once more with `force_refresh` in case the /// issuer rotated it. Resolver errors are returned as they are. Allocations /// belong to `arena`. pub fn verify(arena: Allocator, token: []const u8, options: VerifyOptions, resolver: anytype) !Verified { const parts = jwt.decodeLeaky(arena, token) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.InvalidJwt => return error.BadJwt, }; const alg_name = parts.headerString("alg") orelse return error.BadJwt; if (parts.headerString("typ")) |typ| { for ([_][]const u8{ "at+jwt", "refresh+jwt", "dpop+jwt" }) |forbidden| { if (std.mem.eql(u8, typ, forbidden)) return error.BadJwtType; } } const iss = parts.claimString("iss") orelse return error.BadJwt; const aud = parts.claimString("aud") orelse return error.BadJwt; const exp = parts.claimNumericDate("exp") orelse return error.BadJwt; const lxm: ?[]const u8 = switch (parts.payload.object.get("lxm") orelse .null) { .string => |s| s, else => |value| if (truthy(value)) return error.BadJwt else null, }; if (parts.payload.object.get("nonce")) |nonce| { if (nonce != .string and truthy(nonce)) return error.BadJwt; } if (options.now > exp) return error.JwtExpired; if (options.audiences) |audiences| { for (audiences) |accepted| { if (std.mem.eql(u8, aud, accepted)) break; } else return error.BadJwtAudience; } if (options.lxm) |method| { if (!std.mem.eql(u8, lxm orelse return error.BadJwtLexiconMethod, method)) return error.BadJwtLexiconMethod; } const issuer_did = issuerDid(iss) orelse return error.BadJwtIss; if (options.issuer) |expected| { if (!std.mem.eql(u8, issuer_did, expected)) return error.BadJwtIss; } const alg = jwt.Algorithm.fromString(alg_name) orelse return error.BadJwtSignature; var request: KeyRequest = .{ .did = issuer_did, .key_id = if (std.mem.eql(u8, iss[issuer_did.len..], "#atproto_labeler")) "#atproto_label" else "#atproto", .force_refresh = false, }; const key = try resolver.resolveSigningKey(arena, request); if (!signatureVerifies(arena, alg, parts, key)) { request.force_refresh = true; const fresh = try resolver.resolveSigningKey(arena, request); if (std.mem.eql(u8, fresh, key) or !signatureVerifies(arena, alg, parts, fresh)) return error.BadJwtSignature; } return .{ .iss = iss, .issuer_did = issuer_did, .aud = aud, .lxm = lxm, .jti = parts.claimString("jti"), .exp = exp, .alg = alg, }; } /// the DID an `iss` names: the whole value, or the part before a single /// non-empty `#fragment` pub fn issuerDid(iss: []const u8) ?[]const u8 { const hash = std.mem.indexOfScalar(u8, iss, '#') orelse return if (Did.parse(iss) != null) iss else null; const fragment = iss[hash + 1 ..]; if (fragment.len == 0 or std.mem.indexOfScalar(u8, fragment, '#') != null) return null; return if (Did.parse(iss[0..hash]) != null) iss[0..hash] else null; } fn signatureVerifies(arena: Allocator, alg: jwt.Algorithm, parts: jwt.Decoded, key_text: []const u8) bool { const encoded = if (std.mem.startsWith(u8, key_text, "did:key:")) key_text["did:key:".len..] else key_text; const bytes = multibase.decode(arena, encoded) catch return false; const key = multicodec.parsePublicKey(bytes) catch return false; const expected: multicodec.KeyType = switch (alg) { .ES256 => .p256, .ES256K => .secp256k1, }; if (key.key_type != expected) return false; jwt.verifyJose(alg, parts.signing_input, parts.signature, key.raw) catch return false; return true; } /// JavaScript truthiness of a JSON value, for the reference's /// `payload.lxm && typeof payload.lxm !== "string"` checks fn truthy(value: std.json.Value) bool { return switch (value) { .null => false, .bool => |b| b, .integer => |n| n != 0, .float => |n| n != 0 and !std.math.isNan(n), .number_string => |s| (std.fmt.parseFloat(f64, s) catch 1) != 0, .string => |s| s.len > 0, .array, .object => true, }; } const testing = std.testing; test "create signs JSON-encoded claims that Jwt.parse reads back" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.secp256k1, @splat(0x61)); const token = try create(a, testing.io, &keypair, .{ .iss = "did:plc:alice", .aud = "did:web:svc.example#with\"quote", .lxm = "com.atproto.repo.uploadBlob", .iat = 1_800_000_000, }); var parsed = try jwt.Jwt.parse(a, token); defer parsed.deinit(); try testing.expectEqualStrings("did:plc:alice", parsed.payload.iss); try testing.expectEqualStrings("did:web:svc.example#with\"quote", parsed.payload.aud); try testing.expectEqualStrings("com.atproto.repo.uploadBlob", parsed.payload.lxm.?); try testing.expectEqual(@as(i64, 1_800_000_060), parsed.payload.exp); try testing.expectEqual(@as(?i64, 1_800_000_000), parsed.payload.iat); try testing.expectEqual(@as(usize, 32), parsed.payload.jti.?.len); const pk = try keypair.publicKey(); const key = try multibase.encode(a, .base58btc, try multicodec.encodePublicKey(a, .secp256k1, &pk)); try parsed.verify(key); const parts = try jwt.decodeLeaky(a, token); try testing.expectEqualStrings("JWT", parts.headerString("typ").?); try testing.expectEqualStrings("ES256K", parts.headerString("alg").?); try testing.expect(parts.claimString("sub") == null); } test "create takes an explicit sub, exp and jti" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.p256, @splat(0x62)); const token = try create(a, testing.io, &keypair, .{ .iss = "did:plc:alice", .sub = "did:plc:alice", .aud = "did:web:svc.example", .iat = 100, .exp = 400, .jti = "zds-1", }); const parts = try jwt.decodeLeaky(a, token); try testing.expectEqualStrings("ES256", parts.headerString("alg").?); try testing.expectEqualStrings("did:plc:alice", parts.claimString("sub").?); try testing.expectEqual(@as(?i64, 400), parts.claimNumericDate("exp")); try testing.expectEqualStrings("zds-1", parts.claimString("jti").?); try testing.expect(parts.claimString("lxm") == null); } const TestResolver = struct { /// served without and with `force_refresh` keys: [2][]const u8, requests: [2]KeyRequest = undefined, calls: usize = 0, fail: bool = false, pub fn resolveSigningKey(self: *TestResolver, arena: Allocator, request: KeyRequest) error{DidNotFound}![]const u8 { _ = arena; if (self.fail) return error.DidNotFound; self.requests[self.calls] = request; self.calls += 1; return self.keys[@intFromBool(request.force_refresh)]; } }; fn multikey(a: Allocator, keypair: *const Keypair) ![]const u8 { const pk = try keypair.publicKey(); return multibase.encode(a, .base58btc, try multicodec.encodePublicKey(a, keypair.key_type, &pk)); } const t0: i64 = 1_800_000_000; const upload_blob = "com.atproto.repo.uploadBlob"; const pds_audiences: []const []const u8 = &.{ "did:web:pds.example", "did:web:pds.example#atproto_pds" }; test "verify a service auth token and report its claims" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); for ([_]multicodec.KeyType{ .secp256k1, .p256 }) |key_type| { const keypair = try Keypair.fromSecretKey(key_type, @splat(0x61)); const token = try create(a, testing.io, &keypair, .{ .iss = "did:plc:alice", .aud = "did:web:pds.example#atproto_pds", .lxm = upload_blob, .iat = t0, .jti = "j1" }); for ([_][]const u8{ try multikey(a, &keypair), try keypair.did(a) }) |key| { var resolver: TestResolver = .{ .keys = .{ key, key } }; const verified = try verify(a, token, .{ .now = t0 + 60, .audiences = pds_audiences, .lxm = upload_blob, .issuer = "did:plc:alice" }, &resolver); try testing.expectEqualStrings("did:plc:alice", verified.iss); try testing.expectEqualStrings("did:plc:alice", verified.issuer_did); try testing.expectEqualStrings("did:web:pds.example#atproto_pds", verified.aud); try testing.expectEqualStrings(upload_blob, verified.lxm.?); try testing.expectEqualStrings("j1", verified.jti.?); try testing.expectEqual(t0 + 60, verified.exp); try testing.expectEqual(keypair.algorithm(), verified.alg); try testing.expectEqual(@as(usize, 1), resolver.calls); try testing.expectEqualStrings("did:plc:alice", resolver.requests[0].did); try testing.expectEqualStrings("#atproto", resolver.requests[0].key_id); try testing.expect(!resolver.requests[0].force_refresh); } } } test "a signature that fails under a cached key is retried once with a refreshed key" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const rotated = try Keypair.fromSecretKey(.p256, @splat(0x71)); const previous = try Keypair.fromSecretKey(.secp256k1, @splat(0x72)); const token = try create(a, testing.io, &rotated, .{ .iss = "did:plc:alice", .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 }); const options: VerifyOptions = .{ .now = t0, .audiences = pds_audiences, .lxm = upload_blob }; var refreshed: TestResolver = .{ .keys = .{ try multikey(a, &previous), try multikey(a, &rotated) } }; _ = try verify(a, token, options, &refreshed); try testing.expectEqual(@as(usize, 2), refreshed.calls); try testing.expect(refreshed.requests[1].force_refresh); var stale: TestResolver = .{ .keys = .{ try multikey(a, &previous), try multikey(a, &previous) } }; try testing.expectError(error.BadJwtSignature, verify(a, token, options, &stale)); try testing.expectEqual(@as(usize, 2), stale.calls); var unreachable_did: TestResolver = .{ .keys = .{ "", "" }, .fail = true }; try testing.expectError(error.DidNotFound, verify(a, token, options, &unreachable_did)); } test "a high-S service auth signature verifies" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.p256, @splat(0x61)); const token = try create(a, testing.io, &keypair, .{ .iss = "did:plc:alice", .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 }); 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); const high_s = try std.mem.concat(a, u8, &.{ token[0..sig_start], try jwt.base64UrlEncode(a, signature) }); const key = try multikey(a, &keypair); var resolver: TestResolver = .{ .keys = .{ key, key } }; _ = try verify(a, high_s, .{ .now = t0, .audiences = pds_audiences, .lxm = upload_blob }, &resolver); } test "service auth claims are checked before the issuer's key is resolved" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.secp256k1, @splat(0x61)); const key = try multikey(a, &keypair); const options: VerifyOptions = .{ .now = t0, .audiences = pds_audiences, .lxm = upload_blob }; const Case = struct { claims: Claims, options: VerifyOptions = options, expected: anyerror }; const cases = [_]Case{ .{ .claims = .{ .iss = "did:plc:alice", .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 - 61 }, .expected = error.JwtExpired }, .{ .claims = .{ .iss = "did:plc:alice", .aud = "did:web:other.example", .lxm = upload_blob, .iat = t0 }, .expected = error.BadJwtAudience }, .{ .claims = .{ .iss = "did:plc:alice", .aud = "did:web:pds.example#atproto_labeler", .lxm = upload_blob, .iat = t0 }, .expected = error.BadJwtAudience }, .{ .claims = .{ .iss = "did:plc:alice", .aud = "did:web:pds.example", .lxm = "com.atproto.repo.createRecord", .iat = t0 }, .expected = error.BadJwtLexiconMethod }, .{ .claims = .{ .iss = "did:plc:alice", .aud = "did:web:pds.example", .lxm = "*", .iat = t0 }, .expected = error.BadJwtLexiconMethod }, .{ .claims = .{ .iss = "did:plc:alice", .aud = "did:web:pds.example", .iat = t0 }, .expected = error.BadJwtLexiconMethod }, .{ .claims = .{ .iss = "alice", .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 }, .expected = error.BadJwtIss }, .{ .claims = .{ .iss = "did:plc:alice#", .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 }, .expected = error.BadJwtIss }, .{ .claims = .{ .iss = "did:plc:alice#a#b", .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 }, .expected = error.BadJwtIss }, .{ .claims = .{ .iss = "did:plc:mallory", .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 }, .options = .{ .now = t0, .audiences = pds_audiences, .lxm = upload_blob, .issuer = "did:plc:alice" }, .expected = error.BadJwtIss }, }; for (cases) |case| { var resolver: TestResolver = .{ .keys = .{ key, key } }; const token = try create(a, testing.io, &keypair, case.claims); try testing.expectError(case.expected, verify(a, token, case.options, &resolver)); try testing.expectEqual(@as(usize, 0), resolver.calls); } // exp is inclusive; null audiences and lxm leave those checks to the caller var resolver: TestResolver = .{ .keys = .{ key, key } }; const token = try create(a, testing.io, &keypair, .{ .iss = "did:plc:alice", .aud = "did:web:anyone.example", .iat = t0 - 60 }); _ = try verify(a, token, .{ .now = t0, .audiences = null, .lxm = null }, &resolver); } test "a labeler fragment selects the label key and is stripped from the issuer DID" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.secp256k1, @splat(0x61)); const key = try multikey(a, &keypair); for ([_][2][]const u8{ .{ "did:web:labeler.example#atproto_labeler", "#atproto_label" }, .{ "did:web:feed.example#bsky_fg", "#atproto" } }) |case| { var resolver: TestResolver = .{ .keys = .{ key, key } }; const token = try create(a, testing.io, &keypair, .{ .iss = case[0], .aud = "did:web:pds.example", .lxm = upload_blob, .iat = t0 }); const verified = try verify(a, token, .{ .now = t0, .audiences = pds_audiences, .lxm = upload_blob }, &resolver); try testing.expectEqualStrings(case[0], verified.iss); try testing.expectEqualStrings(case[0][0..std.mem.indexOfScalar(u8, case[0], '#').?], verified.issuer_did); try testing.expectEqualStrings(verified.issuer_did, resolver.requests[0].did); try testing.expectEqualStrings(case[1], resolver.requests[0].key_id); } } test "service auth token shapes the reference rejects" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.secp256k1, @splat(0x61)); const key = try multikey(a, &keypair); const options: VerifyOptions = .{ .now = t0, .audiences = null, .lxm = null }; const valid_payload = "{\"iss\":\"did:plc:alice\",\"aud\":\"did:web:pds.example\",\"exp\":1800000000}"; const Case = struct { header: []const u8, payload: []const u8 = valid_payload, expected: anyerror }; for ([_]Case{ .{ .header = "{\"typ\":\"dpop+jwt\",\"alg\":\"ES256K\"}", .expected = error.BadJwtType }, .{ .header = "{\"typ\":\"at+jwt\",\"alg\":\"ES256K\"}", .expected = error.BadJwtType }, .{ .header = "{\"typ\":\"refresh+jwt\",\"alg\":\"ES256K\"}", .expected = error.BadJwtType }, .{ .header = "{\"typ\":\"JWT\"}", .expected = error.BadJwt }, .{ .header = "{\"alg\":\"ES256K\"}", .payload = "{\"iss\":\"did:plc:alice\",\"exp\":1800000000}", .expected = error.BadJwt }, .{ .header = "{\"alg\":\"ES256K\"}", .payload = "{\"iss\":\"did:plc:alice\",\"aud\":\"did:web:pds.example\",\"exp\":\"1800000000\"}", .expected = error.BadJwt }, .{ .header = "{\"alg\":\"ES256K\"}", .payload = "{\"iss\":\"did:plc:alice\",\"aud\":\"did:web:pds.example\",\"exp\":1800000000,\"lxm\":1}", .expected = error.BadJwt }, }) |case| { var resolver: TestResolver = .{ .keys = .{ key, key } }; const token = try oauth_primitives.createJwt(a, case.header, case.payload, &keypair); try testing.expectError(case.expected, verify(a, token, options, &resolver)); } var resolver: TestResolver = .{ .keys = .{ key, key } }; _ = try verify(a, try oauth_primitives.createJwt(a, "{\"alg\":\"ES256K\"}", "{\"iss\":\"did:plc:alice\",\"aud\":\"did:web:pds.example\",\"exp\":1800000000.5}", &keypair), options, &resolver); try testing.expectError(error.BadJwt, verify(a, "not.a.jwt", options, &resolver)); } test "service auth payload types follow the reference's checks" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const keypair = try Keypair.fromSecretKey(.secp256k1, @splat(0x61)); const key = try multikey(a, &keypair); const options: VerifyOptions = .{ .now = t0, .audiences = null, .lxm = null }; const claims = "\"iss\":\"did:plc:alice\",\"aud\":\"did:web:pds.example\",\"exp\":1800000000"; // falsy non-string lxm and nonce pass the reference's `x && typeof x !== "string"` for ([_][]const u8{ ",\"lxm\":false", ",\"lxm\":0", ",\"lxm\":null", ",\"nonce\":0", ",\"nonce\":\"n\"" }) |extra| { var resolver: TestResolver = .{ .keys = .{ key, key } }; const token = try oauth_primitives.createJwt(a, "{\"alg\":\"ES256K\"}", try std.fmt.allocPrint(a, "{{{s}{s}}}", .{ claims, extra }), &keypair); const verified = try verify(a, token, options, &resolver); try testing.expect(verified.lxm == null); } for ([_][]const u8{ ",\"lxm\":true", ",\"lxm\":[]", ",\"nonce\":1" }) |extra| { var resolver: TestResolver = .{ .keys = .{ key, key } }; const token = try oauth_primitives.createJwt(a, "{\"alg\":\"ES256K\"}", try std.fmt.allocPrint(a, "{{{s}{s}}}", .{ claims, extra }), &keypair); try testing.expectError(error.BadJwt, verify(a, token, options, &resolver)); } // a padded, duplicated payload decodes as Node and JSON.parse would var resolver: TestResolver = .{ .keys = .{ key, key } }; const payload = try jwt.base64UrlEncode(a, "{\"iss\":\"did:plc:mallory\"," ++ claims ++ "}"); const signing_input = try std.fmt.allocPrint(a, "eyJhbGciOiJFUzI1NksifQ.{s}=", .{payload}); const signature = try keypair.sign(signing_input); const token = try std.fmt.allocPrint(a, "{s}.{s}", .{ signing_input, try jwt.base64UrlEncode(a, &signature.bytes) }); try testing.expectEqualStrings("did:plc:alice", (try verify(a, token, options, &resolver)).iss); }