//! JSON Web Keys (RFC 7517) on the curves atproto signs with, and RFC 7638 //! thumbprints. Parses the public keys other parties publish: DPoP proof //! headers, OAuth client JWKS documents. const std = @import("std"); const crypto = std.crypto; const jwt = @import("jwt.zig"); const multicodec = @import("multicodec.zig"); pub const Error = error{InvalidJwk}; pub const SelectError = error{ InvalidJwk, InvalidJwks, KeyNotFound }; /// base64url of a SHA-256 digest pub const Thumbprint = [43]u8; pub const PublicKey = struct { key_type: multicodec.KeyType, /// compressed SEC1 point, as `jwt.verifyJose` and `jwt.verify*` take it raw: [33]u8, pub fn algorithm(self: PublicKey) jwt.Algorithm { return switch (self.key_type) { .secp256k1 => .ES256K, .p256 => .ES256, }; } /// verify a JOSE signature (high-S accepted) made with this key under `alg` pub fn verifyJose(self: PublicKey, alg: jwt.Algorithm, message: []const u8, signature: []const u8) !void { if (alg != self.algorithm()) return error.AlgorithmKeyMismatch; return jwt.verifyJose(alg, message, signature, &self.raw); } /// RFC 7638 thumbprint of the key's EC JWK pub fn thumbprint(self: PublicKey) error{InvalidPublicKey}!Thumbprint { const point = uncompressed(self) catch return error.InvalidPublicKey; var x: [43]u8 = undefined; var y: [43]u8 = undefined; _ = std.base64.url_safe_no_pad.Encoder.encode(&x, point[1..33]); _ = std.base64.url_safe_no_pad.Encoder.encode(&y, point[33..65]); var hash = crypto.hash.sha2.Sha256.init(.{}); for ([_][]const u8{ "{\"crv\":\"", curveName(self.key_type), "\",\"kty\":\"EC\",\"x\":\"", &x, "\",\"y\":\"", &y, "\"}" }) |part| hash.update(part); return encodeDigest(hash.finalResult()); } }; /// parse a public EC JWK: kty `EC`, crv `P-256` or `secp256k1`, and `x` and `y` /// naming a point on the curve. A JWK carrying the private scalar `d` is /// rejected, as jose's embedded-JWK check rejects a private key. pub fn parsePublicKey(value: std.json.Value) Error!PublicKey { if (value != .object) return error.InvalidJwk; if (!std.mem.eql(u8, member(value, "kty") orelse return error.InvalidJwk, "EC")) return error.InvalidJwk; if (value.object.get("d") != null) return error.InvalidJwk; const key_type = curveFromName(member(value, "crv") orelse return error.InvalidJwk) orelse return error.InvalidJwk; var point: [65]u8 = undefined; point[0] = 0x04; try decodeCoordinate(point[1..33], member(value, "x") orelse return error.InvalidJwk); try decodeCoordinate(point[33..65], member(value, "y") orelse return error.InvalidJwk); return .{ .key_type = key_type, .raw = switch (key_type) { .p256 => compress(crypto.sign.ecdsa.EcdsaP256Sha256, &point), .secp256k1 => compress(crypto.sign.ecdsa.EcdsaSecp256k1Sha256, &point), } catch return error.InvalidJwk }; } /// pick the key a JWT names from a JWKS document (`{"keys":[...]}`): with /// `kid`, only keys with that `kid`; then the first EC key on `alg`'s curve /// whose own `alg`, if any, is `alg`. A matching key that does not parse is /// an error rather than skipped. pub fn selectFromJwks(jwks: std.json.Value, kid: ?[]const u8, alg: jwt.Algorithm) SelectError!PublicKey { if (jwks != .object) return error.InvalidJwks; const keys = switch (jwks.object.get("keys") orelse return error.InvalidJwks) { .array => |array| array.items, else => return error.InvalidJwks, }; const crv = curveName(switch (alg) { .ES256 => .p256, .ES256K => .secp256k1, }); for (keys) |key| { if (key != .object) continue; if (kid) |wanted| { if (!std.mem.eql(u8, member(key, "kid") orelse continue, wanted)) continue; } if (!std.mem.eql(u8, member(key, "kty") orelse continue, "EC")) continue; if (!std.mem.eql(u8, member(key, "crv") orelse continue, crv)) continue; if (member(key, "alg")) |key_alg| { if (!std.mem.eql(u8, key_alg, @tagName(alg))) continue; } return try parsePublicKey(key); } return error.KeyNotFound; } /// RFC 7638 thumbprint of a JWK as given, over the required members of kty /// `EC`, `RSA`, `OKP` or `oct` serialized as jose's `calculateJwkThumbprint` /// does (`JSON.stringify`), so a DPoP `jkt` matches the reference for any /// encoding of the same key. It does not check that the key is usable. pub fn thumbprint(value: std.json.Value) Error!Thumbprint { if (value != .object) return error.InvalidJwk; const kty = member(value, "kty") orelse return error.InvalidJwk; const required: []const []const u8 = if (std.mem.eql(u8, kty, "EC")) &.{ "crv", "kty", "x", "y" } else if (std.mem.eql(u8, kty, "RSA")) &.{ "e", "kty", "n" } else if (std.mem.eql(u8, kty, "OKP")) &.{ "crv", "kty", "x" } else if (std.mem.eql(u8, kty, "oct")) &.{ "k", "kty" } else return error.InvalidJwk; var hash = crypto.hash.sha2.Sha256.init(.{}); hash.update("{"); for (required, 0..) |name, i| { const text = member(value, name) orelse return error.InvalidJwk; if (text.len == 0) return error.InvalidJwk; if (i > 0) hash.update(","); for ([_][]const u8{ "\"", name, "\":\"" }) |part| hash.update(part); hashJsonStringContent(&hash, text); hash.update("\""); } hash.update("}"); return encodeDigest(hash.finalResult()); } /// the inside of a string as `JSON.stringify` writes it fn hashJsonStringContent(hash: *crypto.hash.sha2.Sha256, text: []const u8) void { for (text) |c| { var escape: [6]u8 = undefined; hash.update(switch (c) { '"' => "\\\"", '\\' => "\\\\", 0x08 => "\\b", 0x0c => "\\f", '\n' => "\\n", '\r' => "\\r", '\t' => "\\t", 0...0x07, 0x0b, 0x0e...0x1f => std.fmt.bufPrint(&escape, "\\u{x:0>4}", .{c}) catch unreachable, else => @as(*const [1]u8, &c), }); } } fn member(object: std.json.Value, name: []const u8) ?[]const u8 { return switch (object.object.get(name) orelse return null) { .string => |s| s, else => null, }; } fn curveName(key_type: multicodec.KeyType) []const u8 { return switch (key_type) { .p256 => "P-256", .secp256k1 => "secp256k1", }; } fn curveFromName(name: []const u8) ?multicodec.KeyType { if (std.mem.eql(u8, name, "P-256")) return .p256; if (std.mem.eql(u8, name, "secp256k1")) return .secp256k1; return null; } /// a coordinate as Node's JWK import reads it: base64url decoded leniently /// (`jwt.base64UrlDecodeLenient`) into a big-endian integer, so leading zero /// bytes are allowed and it must fit in 32 bytes. fn decodeCoordinate(out: *[32]u8, text: []const u8) Error!void { out.* = @splat(0); var bytes = jwt.LenientBase64{ .text = text }; var len: usize = 0; while (bytes.next()) |b| { if (len == 0 and b == 0) continue; if (len == 32) return error.InvalidJwk; std.mem.copyForwards(u8, out[0..31], out[1..32]); out[31] = b; len += 1; } } fn compress(comptime Scheme: type, point: *const [65]u8) ![33]u8 { const key = try Scheme.PublicKey.fromSec1(point); return key.toCompressedSec1(); } fn uncompressed(key: PublicKey) ![65]u8 { return switch (key.key_type) { .p256 => (try crypto.sign.ecdsa.EcdsaP256Sha256.PublicKey.fromSec1(&key.raw)).toUncompressedSec1(), .secp256k1 => (try crypto.sign.ecdsa.EcdsaSecp256k1Sha256.PublicKey.fromSec1(&key.raw)).toUncompressedSec1(), }; } fn encodeDigest(digest: [32]u8) Thumbprint { var out: Thumbprint = undefined; _ = std.base64.url_safe_no_pad.Encoder.encode(&out, &digest); return out; } const testing = std.testing; const Keypair = @import("keypair.zig").Keypair; fn parseJson(arena: std.mem.Allocator, text: []const u8) !std.json.Value { return std.json.parseFromSliceLeaky(std.json.Value, arena, text, .{}); } // keys derived from the scalars 0x21.. and 0x22..; x, y and thumbprints from // python jwcrypto 1.6.1 const p256_jwk = \\{"kty":"EC","crv":"P-256","x":"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M","y":"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eE"} ; const p256_thumbprint = "Q6ityJw5hSExs1Tt1BtTHZV1VlRJ6a7CueD5W1hFLCM"; const k256_jwk = \\{"kty":"EC","crv":"secp256k1","x":"Rm1_yuVj5csJoNGHC7WANEgEYXh5oUlJzyIoXxuuPyc","y":"ZygXbDxkMfju2kU43DfIZeJ4Tzqed9BE8z5Ad5fhJ4o"} ; const k256_thumbprint = "tUjNtvo0m1_8chg1bBe-JX1QmeKl4sVBmFNmjJdbNQQ"; test "RFC 7638 example thumbprint" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const key = try parseJson(arena.allocator(), \\{"kty":"RSA","n":"0vx7agoebGcQSuuPiLJXZptN9nndrQmbXEps2aiAFbWhM78LhWx4cbbfAAtVT86zwu1RK7aPFFxuhDR1L6tSoc_BJECPebWKRXjBZCiFV4n3oknjhMstn64tZ_2W-5JsGY4Hc5n9yBXArwl93lqt7_RN5w6Cf0h4QyQ5v-65YGjQR0_FDW2QvzqY368QQMicAtaSqzs8KJZgnYb9c7d0zgdAZHzu6qMQvRL5hajrn1n91CbOpbISD08qNLyrdkt-bFTWhAI4vMQFh6WeZu0fM4lFd2NcRwr3XPksINHaQ-G_xBniIqbw0Ls1jF44-csFCur-kEgU8awapJzKnqDKgw","e":"AQAB","alg":"RS256","kid":"2011-04-29"} ); try testing.expectEqualStrings("NzbLsXh8uDCcd-6MNwXF4W_7noWXFZAfHkxZsRGC9Xs", &try thumbprint(key)); } test "EC thumbprints match an independent implementation and the keypair" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); for ([_][2][]const u8{ .{ p256_jwk, p256_thumbprint }, .{ k256_jwk, k256_thumbprint } }, [_]u8{ 0x21, 0x22 }, [_]multicodec.KeyType{ .p256, .secp256k1 }) |case, seed, key_type| { const value = try parseJson(a, case[0]); try testing.expectEqualStrings(case[1], &try thumbprint(value)); const key = try parsePublicKey(value); try testing.expectEqual(key_type, key.key_type); try testing.expectEqualStrings(case[1], &try key.thumbprint()); const keypair = try Keypair.fromSecretKey(key_type, @splat(seed)); try testing.expectEqualSlices(u8, &try keypair.publicKey(), &key.raw); const from_keypair = try keypair.jwkThumbprint(a); try testing.expectEqualStrings(case[1], from_keypair); } } test "a parsed JWK verifies the keypair's signatures" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); for ([_]multicodec.KeyType{ .p256, .secp256k1 }) |key_type| { const keypair = try Keypair.fromSecretKey(key_type, @splat(0x41)); const key = try parsePublicKey(try parseJson(a, try keypair.jwk(a))); const signature = try keypair.sign("message"); try key.verifyJose(keypair.algorithm(), "message", &signature.bytes); try testing.expectError(error.SignatureVerificationFailed, key.verifyJose(keypair.algorithm(), "other", &signature.bytes)); const other: jwt.Algorithm = if (key_type == .p256) .ES256K else .ES256; try testing.expectError(error.AlgorithmKeyMismatch, key.verifyJose(other, "message", &signature.bytes)); } } test "a point off the curve is rejected" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); // the P-256 key above with its y coordinate's last byte changed const off_curve = try parseJson(a, \\{"kty":"EC","crv":"P-256","x":"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M","y":"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eA"} ); try testing.expectError(error.InvalidJwk, parsePublicKey(off_curve)); // a valid P-256 point is not on secp256k1 const wrong_curve = try parseJson(a, \\{"kty":"EC","crv":"secp256k1","x":"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M","y":"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eE"} ); try testing.expectError(error.InvalidJwk, parsePublicKey(wrong_curve)); // x at or above the field prime const non_canonical = try parseJson(a, \\{"kty":"EC","crv":"P-256","x":"__________________________________________8","y":"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eE"} ); try testing.expectError(error.InvalidJwk, parsePublicKey(non_canonical)); } test "malformed EC JWKs are rejected" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const x = "\"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M\""; const y = "\"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eE\""; for ([_][]const u8{ "[]", "{\"kty\":\"RSA\",\"crv\":\"P-256\",\"x\":" ++ x ++ ",\"y\":" ++ y ++ "}", "{\"kty\":\"EC\",\"crv\":\"P-384\",\"x\":" ++ x ++ ",\"y\":" ++ y ++ "}", "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":" ++ x ++ "}", "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":" ++ x ++ ",\"y\":1}", // a truncated coordinate names another point; 33 significant bytes do not fit "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP0w\",\"y\":" ++ y ++ "}", "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"AUYtuhrk_BqWi02s8gzdbb4frjSqlxUUpj00BcPRz9OD\",\"y\":" ++ y ++ "}", // a private key "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":" ++ x ++ ",\"y\":" ++ y ++ ",\"d\":\"ISEhISEhISEhISEhISEhISEhISEhISEhISEhISEhISE\"}", }) |text| { try testing.expectError(error.InvalidJwk, parsePublicKey(try parseJson(a, text))); } } test "select a JWKS key by kid and alg" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const k256 = k256_jwk[0 .. k256_jwk.len - 1]; const p256 = p256_jwk[0 .. p256_jwk.len - 1]; const jwks = try parseJson(a, "{\"keys\":[" ++ "{\"kty\":\"RSA\",\"kid\":\"rsa\",\"n\":\"AQAB\",\"e\":\"AQAB\"}," ++ k256 ++ ",\"kid\":\"k256\"}," ++ p256 ++ ",\"kid\":\"p256-pinned\",\"alg\":\"ES256K\"}," ++ p256 ++ ",\"kid\":\"p256\",\"alg\":\"ES256\"}]}"); try testing.expectEqual(multicodec.KeyType.secp256k1, (try selectFromJwks(jwks, null, .ES256K)).key_type); const by_alg = try selectFromJwks(jwks, null, .ES256); try testing.expectEqualStrings(p256_thumbprint, &try by_alg.thumbprint()); try testing.expectEqualStrings(k256_thumbprint, &try (try selectFromJwks(jwks, "k256", .ES256K)).thumbprint()); try testing.expectError(error.KeyNotFound, selectFromJwks(jwks, "k256", .ES256)); try testing.expectError(error.KeyNotFound, selectFromJwks(jwks, "p256-pinned", .ES256)); try testing.expectError(error.KeyNotFound, selectFromJwks(jwks, "missing", .ES256)); try testing.expectError(error.KeyNotFound, selectFromJwks(jwks, "rsa", .ES256)); const broken = try parseJson(a, "{\"keys\":[{\"kty\":\"EC\",\"crv\":\"P-256\",\"kid\":\"bad\",\"x\":\"AA\",\"y\":\"AA\"}]}"); try testing.expectError(error.InvalidJwk, selectFromJwks(broken, "bad", .ES256)); try testing.expectError(error.InvalidJwks, selectFromJwks(try parseJson(a, "{\"keys\":{}}"), null, .ES256)); try testing.expectError(error.InvalidJwks, selectFromJwks(try parseJson(a, "[]"), null, .ES256)); } test "coordinates decode as leniently as Node's JWK import" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const canonical = try parsePublicKey(try parseJson(a, p256_jwk)); const y = "\"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eE\""; // Node 22's crypto.createPublicKey accepts each of these as the same key inline for ([_][]const u8{ "\"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M=\"", "\"Ri26GuT8GpaLTazyDN1tvh+uNKqXFRSmPTQFw9HP04M\"", "\"AEYtuhrk_BqWi02s8gzdbb4frjSqlxUUpj00BcPRz9OD\"", }) |x| { const key = try parsePublicKey(try parseJson(a, "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":" ++ x ++ ",\"y\":" ++ y ++ "}")); try testing.expectEqualSlices(u8, &canonical.raw, &key.raw); } } test "thumbprints serialize members as JSON.stringify does" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); // expected digests from Node 22: sha256(JSON.stringify(members)), base64url const padded = try parseJson(a, \\{"kty":"EC","crv":"P-256","x":"Ri26GuT8GpaLTazyDN1tvh-uNKqXFRSmPTQFw9HP04M=","y":"tYu7CMEzg0KMWFPHHEyFHhNLBWgh5Gj-Cpd6v0MT3eE"} ); try testing.expectEqualStrings("PtOaRXPjIqyzEzKLfVN9E6SUMLNz9POreIT4cCTLdCs", &try thumbprint(padded)); const escaped = try parseJson(a, "{\"kty\":\"oct\",\"k\":\"a\\\"b\\\\c\\n\\t\\u0001\u{e9}/\"}"); try testing.expectEqualStrings("bSgcF-pA0zNw5nbAAdtwjiqbr6yukxuOID9Qt0gOC4E", &try thumbprint(escaped)); try testing.expectError(error.InvalidJwk, thumbprint(try parseJson(a, "{\"kty\":\"oct\",\"k\":\"\"}"))); try testing.expectError(error.InvalidJwk, thumbprint(try parseJson(a, "{\"kty\":\"EC\",\"crv\":\"P-256\",\"x\":\"AA\"}"))); try testing.expectError(error.InvalidJwk, thumbprint(try parseJson(a, "{\"kty\":\"XYZ\"}"))); }