//! HTTP message signatures (RFC 9421) as spaces use them: a credential holder //! signs each request it authorizes with a space credential, and a repo host //! MACs the commits and records it returns (see `mac.zig`). //! //! A signature is found by its `tag`, never its label: labels carry no meaning //! (RFC 9421 §7.2.5). Mirrors `@atproto/space` `http-signature.ts`. const std = @import("std"); const sf = @import("structured_fields.zig"); const jwt = @import("../crypto/jwt.zig"); const multicodec = @import("../crypto/multicodec.zig"); const Keypair = @import("../crypto/keypair.zig").Keypair; pub const Error = error{ BadSpaceSignature, OutOfMemory }; /// A covered component, e.g. `"authorization"` or `"atproto-space-commit";sf`. pub const Component = struct { name: []const u8, structured: bool = false, }; /// What a verifier requires of the signature it checks (RFC 9421 §3.2.1). pub const Requirements = struct { tag: []const u8, /// Exactly the components it must cover, in order. components: []const Component, /// Required when the signature names an `alg`. alg: []const u8, /// Required when the signature names a `keyid`. key_id: []const u8, }; pub const Found = struct { /// The signature's parameters, serialized canonically: what its base covers. signature_params: []const u8, signature: []const u8, }; pub const TaggedMember = struct { label: []const u8, params: sf.InnerList }; /// The inner-list members of a `Signature-Input` or `Accept-Signature` /// dictionary whose `tag` parameter is `tag`. pub fn membersWithTag(allocator: std.mem.Allocator, members: sf.Dictionary, tag: []const u8) ![]const TaggedMember { var out: std.ArrayList(TaggedMember) = .empty; for (members) |entry| switch (entry.member) { .inner_list => |list| { const value = sf.param(list.params, "tag") orelse continue; if (value == .string and std.mem.eql(u8, value.string, tag)) try out.append(allocator, .{ .label = entry.key, .params = list }); }, .item => {}, }; return out.items; } /// Whether `list` covers exactly `components`, in order, with no others. pub fn coversExactly(list: sf.InnerList, components: []const Component) bool { if (list.items.len != components.len) return false; for (list.items, components) |it, component| { if (it.bare != .string or !std.mem.eql(u8, it.bare.string, component.name)) return false; const expected_params: usize = if (component.structured) 1 else 0; if (it.params.len != expected_params) return false; if (component.structured) { const flag = sf.param(it.params, "sf") orelse return false; if (flag != .boolean or !flag.boolean) return false; } } return true; } /// The serialized inner list `(components...);params...`. pub fn formatSignatureParams(allocator: std.mem.Allocator, components: []const Component, params: []const sf.Parameter) error{OutOfMemory}![]u8 { var items: std.ArrayList(sf.Item) = .empty; defer items.deinit(allocator); for (components) |component| try items.append(allocator, componentItem(component)); var out: std.Io.Writer.Allocating = .init(allocator); errdefer out.deinit(); sf.writeInnerList(&out.writer, .{ .items = items.items, .params = params }) catch return error.OutOfMemory; return out.toOwnedSlice(); } fn componentItem(component: Component) sf.Item { const structured = &[_]sf.Parameter{.{ .key = "sf", .value = .{ .boolean = true } }}; return .{ .bare = .{ .string = component.name }, .params = if (component.structured) structured else &.{} }; } /// The signature base (RFC 9421 §2.5) over `components`, whose values are /// given in order, under the serialized `signature_params`. pub fn signatureBase(allocator: std.mem.Allocator, components: []const Component, values: []const []const u8, signature_params: []const u8) error{OutOfMemory}![]u8 { std.debug.assert(components.len == values.len); var out: std.Io.Writer.Allocating = .init(allocator); errdefer out.deinit(); writeBase(&out.writer, components, values, signature_params) catch return error.OutOfMemory; return out.toOwnedSlice(); } fn writeBase(writer: *std.Io.Writer, components: []const Component, values: []const []const u8, signature_params: []const u8) !void { for (components, values) |component, value| { try sf.writeItem(writer, componentItem(component)); try writer.print(": {s}\n", .{std.mem.trim(u8, value, " \t")}); } try writer.print("\"@signature-params\": {s}", .{signature_params}); } /// Find the one signature tagged `required.tag` in a message's `Signature-Input` /// and `Signature` fields, and check it meets `required`. Other parameters, like /// `created`, are covered by the signature but not interpreted. Allocations /// belong to `arena`. pub fn findSignature(arena: std.mem.Allocator, input_field: ?[]const u8, signature_field: ?[]const u8, required: Requirements) Error!Found { const inputs = sf.parseDictionary(arena, input_field orelse return error.BadSpaceSignature) catch return error.BadSpaceSignature; const signatures = sf.parseDictionary(arena, signature_field orelse return error.BadSpaceSignature) catch return error.BadSpaceSignature; const tagged = try membersWithTag(arena, inputs, required.tag); if (tagged.len != 1) return error.BadSpaceSignature; const signature = switch (sf.get(signatures, tagged[0].label) orelse return error.BadSpaceSignature) { .item => |it| if (it.bare == .bytes and it.params.len == 0) it.bare.bytes else return error.BadSpaceSignature, .inner_list => return error.BadSpaceSignature, }; const params = tagged[0].params; if (!coversExactly(params, required.components)) return error.BadSpaceSignature; if (sf.param(params.params, "alg")) |alg| { if (alg != .string or !std.mem.eql(u8, alg.string, required.alg)) return error.BadSpaceSignature; } if (sf.param(params.params, "keyid")) |key_id| { if (key_id != .string or !std.mem.eql(u8, key_id.string, required.key_id)) return error.BadSpaceSignature; } var out: std.Io.Writer.Allocating = .init(arena); sf.writeInnerList(&out.writer, params) catch return error.OutOfMemory; return .{ .signature_params = out.written(), .signature = signature }; } // ---- credential use ---- pub const credential_tag = "atproto-space-credential"; pub const credential_alg = "ecdsa-p256-sha256"; const credential_label = "sig"; /// A credential use covers the credential and its audience DID, in that order. pub const credential_components = [_]Component{ .{ .name = "authorization" }, .{ .name = "atproto-space-audience" } }; /// The request headers a holder sends with a space credential. pub const CredentialHeaders = struct { signature_input: []const u8, signature: []const u8, }; /// Sign a request authorized by `authorization` for `audience` with the /// holder's P-256 key. The caller also sends `authorization` and /// `atproto-space-audience` as given. pub fn signCredentialUse(allocator: std.mem.Allocator, keypair: *const Keypair, authorization: []const u8, audience: []const u8) !CredentialHeaders { if (keypair.algorithm() != .ES256) return error.BadSpaceSignature; const params = try formatSignatureParams(allocator, &credential_components, &.{.{ .key = "tag", .value = .{ .string = credential_tag } }}); defer allocator.free(params); const base = try signatureBase(allocator, &credential_components, &.{ authorization, audience }, params); defer allocator.free(base); const signature = try keypair.sign(base); const input = try std.fmt.allocPrint(allocator, credential_label ++ "={s}", .{params}); errdefer allocator.free(input); var encoded: [88]u8 = undefined; const sig = try std.fmt.allocPrint(allocator, credential_label ++ "=:{s}:", .{std.base64.standard.Encoder.encode(&encoded, &signature.bytes)}); return .{ .signature_input = input, .signature = sig }; } /// Verify the signature on a request authorized by a space credential against /// the P-256 did:key the credential is bound to (its `cnf.kid`). High-S /// signatures are accepted. pub fn verifyCredentialUse( allocator: std.mem.Allocator, authorization: []const u8, audience: []const u8, signature_input: ?[]const u8, signature: ?[]const u8, key_id: []const u8, ) Error!void { if (authorization.len == 0 or audience.len == 0) return error.BadSpaceSignature; var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const a = arena.allocator(); const found = try findSignature(a, signature_input, signature, .{ .tag = credential_tag, .components = &credential_components, .alg = credential_alg, .key_id = key_id, }); const key = multicodec.parseDidKey(a, key_id) catch return error.BadSpaceSignature; if (key.key_type != .p256 or found.signature.len != 64) return error.BadSpaceSignature; const base = try signatureBase(a, &credential_components, &.{ authorization, audience }, found.signature_params); jwt.verifyJose(.ES256, base, found.signature, key.raw) catch return error.BadSpaceSignature; } test "a credential use signs under any label and verifies by tag, accepting high-S" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); var key = try Keypair.fromSecretKey(.p256, @splat(0x42)); const kid = try key.did(a); const auth = "Atproto-Space-Credential credential"; const audience = "did:plc:alice"; const signed = try signCredentialUse(a, &key, auth, audience); try std.testing.expectEqualStrings("sig=(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\"", signed.signature_input); try verifyCredentialUse(a, auth, audience, signed.signature_input, signed.signature, kid); const params = "(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\";alg=\"ecdsa-p256-sha256\";created=123"; const base = try signatureBase(a, &credential_components, &.{ auth, audience }, params); const low = try key.sign(base); var high = low.bytes; high[32..64].* = try std.crypto.ecc.P256.scalar.neg(low.bytes[32..64].*, .big); for ([_][64]u8{ low.bytes, high }) |sig| { var encoded: [88]u8 = undefined; const b64 = std.base64.standard.Encoder.encode(&encoded, &sig); const input = try std.fmt.allocPrint(a, "other=(\"date\"), whatever={s}", .{params}); const signature = try std.fmt.allocPrint(a, "other=:YWJj:, whatever=:{s}:", .{b64}); for (0..2) |_| try verifyCredentialUse(a, auth, audience, input, signature, kid); try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, "Atproto-Space-Credential changed", audience, input, signature, kid)); try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, "did:plc:bob", input, signature, kid)); try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, input, "whatever=:YWJj:", kid)); // unpadded base64 const unpadded = try std.fmt.allocPrint(a, "whatever=:{s}:", .{std.mem.trimEnd(u8, b64, "=")}); try verifyCredentialUse(a, auth, audience, input, unpadded, kid); } } test "a credential use must carry the tag, both components in order, and the bound key" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); var key = try Keypair.fromSecretKey(.p256, @splat(0x42)); const kid = try key.did(a); var other = try Keypair.fromSecretKey(.p256, @splat(0x43)); const auth = "Atproto-Space-Credential credential"; const audience = "did:plc:alice"; const cases = [_][]const u8{ "(\"authorization\" \"atproto-space-audience\")", "(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space\"", "(\"authorization\");tag=\"atproto-space-credential\"", "(\"atproto-space-audience\" \"authorization\");tag=\"atproto-space-credential\"", "(\"authorization\" \"atproto-space-audience\";sf);tag=\"atproto-space-credential\"", "(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\";alg=\"hmac-sha256\"", try std.fmt.allocPrint(a, "(\"authorization\" \"atproto-space-audience\");tag=\"atproto-space-credential\";keyid=\"{s}\"", .{try other.did(a)}), }; for (cases) |params| { const base = try std.fmt.allocPrint(a, "\"authorization\": {s}\n\"atproto-space-audience\": {s}\n\"@signature-params\": {s}", .{ auth, audience, params }); const sig = try key.sign(base); var encoded: [88]u8 = undefined; const input = try std.fmt.allocPrint(a, "sig={s}", .{params}); const signature = try std.fmt.allocPrint(a, "sig=:{s}:", .{std.base64.standard.Encoder.encode(&encoded, &sig.bytes)}); try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, input, signature, kid)); } // two signatures with the credential tag const signed = try signCredentialUse(a, &key, auth, audience); const doubled_input = try std.fmt.allocPrint(a, "{s}, b={s}", .{ signed.signature_input, signed.signature_input["sig=".len..] }); const doubled_sig = try std.fmt.allocPrint(a, "{s}, b={s}", .{ signed.signature, signed.signature["sig=".len..] }); try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, doubled_input, doubled_sig, kid)); // a key other than the bound one try std.testing.expectError(error.BadSpaceSignature, verifyCredentialUse(a, auth, audience, signed.signature_input, signed.signature, try other.did(a))); }