//! Space repos authenticate commits and records with a MAC rather than a //! signature, so a leaked response proves nothing to a third party. A MAC is an //! HTTP message signature (RFC 9421) using `hmac-sha256`, keyed by a //! per-request shared secret (see `kem.zig`). //! //! The syncer asks for one with an `Accept-Signature` header whose `tag` names a //! profile. The host answers with a header describing the commit or record it //! returned, and a MAC covering that header. Mirrors `@atproto/space` `mac.ts`. const std = @import("std"); const sf = @import("structured_fields.zig"); const hs = @import("http_signature.zig"); const Did = @import("../syntax/did.zig").Did; const HmacSha256 = std.crypto.auth.hmac.sha2.HmacSha256; pub const Error = error{ InvalidSpaceMac, OutOfMemory }; pub const alg = "hmac-sha256"; pub const request_header = "accept-signature"; /// The label this syncer asks for its MAC under. A host answers under the /// label it was asked for; a syncer finds the MAC by its tag. const request_label = "mac"; pub const Profile = enum { commit, record, pub fn tag(self: Profile) []const u8 { return switch (self) { .commit => "atproto-space-commit", .record => "atproto-space-record", }; } /// The response header the profile's MAC covers. pub fn coveredHeader(self: Profile) []const u8 { return switch (self) { .commit => "atproto-space-commit", .record => "atproto-space-record", }; } fn components(self: Profile) [1]hs.Component { return .{.{ .name = self.coveredHeader(), .structured = true }}; } }; /// `com.atproto.space.defs#commit`. pub const Commit = struct { ver: u8 = 1, repo: []const u8, space: []const u8, rev: []const u8, data: [32]u8, }; // ---- requests ---- /// The syncer's `Accept-Signature` value asking for a MAC keyed by the secret /// for `key_share`, e.g. /// `mac=("atproto-space-commit";sf);keyid="did:key:zDna...";tag="atproto-space-commit"`. pub fn formatMacRequest(allocator: std.mem.Allocator, profile: Profile, key_share: []const u8) ![]u8 { const components = profile.components(); const params = try hs.formatSignatureParams(allocator, &components, &.{ .{ .key = "keyid", .value = .{ .string = key_share } }, .{ .key = "tag", .value = .{ .string = profile.tag() } }, }); defer allocator.free(params); return std.fmt.allocPrint(allocator, request_label ++ "={s}", .{params}); } /// A MAC request as the host reads it from `Accept-Signature`. pub const MacRequest = struct { label: []const u8, key_share: []const u8, /// The requested parameters, serialized: the host's MAC uses them as given. signature_params: []const u8, }; /// The parameters a host fulfills. A syncer uses a new key share for each /// request, so `created`, `expires` and `nonce` would add nothing. const request_params = [_][]const u8{ "keyid", "tag", "alg" }; /// Find the MAC requested for `profile` in an `Accept-Signature` value and /// check the host can fulfill it. Requests with other tags are ignored, so this /// is null when none is for `profile`. Allocations belong to `arena`. pub fn parseMacRequest(arena: std.mem.Allocator, value: ?[]const u8, profile: Profile) Error!?MacRequest { const requests = sf.parseDictionary(arena, value orelse return null) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.InvalidSpaceMac, }; const tagged = try hs.membersWithTag(arena, requests, profile.tag()); if (tagged.len == 0) return null; if (tagged.len > 1) return error.InvalidSpaceMac; const params = tagged[0].params; if (!hs.coversExactly(params, &profile.components())) return error.InvalidSpaceMac; for (params.params) |p| { for (request_params) |known| { if (std.mem.eql(u8, p.key, known)) break; } else return error.InvalidSpaceMac; } if (sf.param(params.params, "alg")) |requested| { if (requested != .string or !std.mem.eql(u8, requested.string, alg)) return error.InvalidSpaceMac; } const key_share = sf.param(params.params, "keyid") orelse return error.InvalidSpaceMac; if (key_share != .string or Did.parse(key_share.string) == null) return error.InvalidSpaceMac; var out: std.Io.Writer.Allocating = .init(arena); sf.writeInnerList(&out.writer, params) catch return error.OutOfMemory; return .{ .label = tagged[0].label, .key_share = key_share.string, .signature_params = out.written() }; } // ---- responses ---- /// The headers a host answers a MAC request with: the covered header (named /// by `covered_name`), and the `Signature-Input` and `Signature` of a MAC over it. pub const MacHeaders = struct { covered_name: []const u8, covered: []const u8, signature_input: []const u8, signature: []const u8, pub fn deinit(self: MacHeaders, allocator: std.mem.Allocator) void { allocator.free(self.covered); allocator.free(self.signature_input); allocator.free(self.signature); } }; /// An `Atproto-Space-Commit` header describing `commit`, e.g. /// `ver=1, repo="did:example:alice", space="at://...", rev="3mwcj3b6uak2f", data=:q3J0...=:`, /// and a MAC over it. pub fn createCommitMacHeaders(allocator: std.mem.Allocator, commit: Commit, request: MacRequest, shared_secret: *const [32]u8) !MacHeaders { const covered = try allocDictionary(allocator, &.{ .{ .key = "ver", .member = .{ .item = .{ .bare = .{ .integer = commit.ver } } } }, .{ .key = "repo", .member = .{ .item = .{ .bare = .{ .string = commit.repo } } } }, .{ .key = "space", .member = .{ .item = .{ .bare = .{ .string = commit.space } } } }, .{ .key = "rev", .member = .{ .item = .{ .bare = .{ .string = commit.rev } } } }, .{ .key = "data", .member = .{ .item = .{ .bare = .{ .bytes = &commit.data } } } }, }); errdefer allocator.free(covered); return createMacHeaders(allocator, .commit, covered, request, shared_secret); } /// An `Atproto-Space-Record` header naming a record by uri and cid, e.g. /// `uri="at://...", cid="bafyrei..."`, and a MAC over it. pub fn createRecordMacHeaders(allocator: std.mem.Allocator, uri: []const u8, cid: []const u8, request: MacRequest, shared_secret: *const [32]u8) !MacHeaders { const covered = try allocDictionary(allocator, &.{ .{ .key = "uri", .member = .{ .item = .{ .bare = .{ .string = uri } } } }, .{ .key = "cid", .member = .{ .item = .{ .bare = .{ .string = cid } } } }, }); errdefer allocator.free(covered); return createMacHeaders(allocator, .record, covered, request, shared_secret); } fn allocDictionary(allocator: std.mem.Allocator, dictionary: sf.Dictionary) error{OutOfMemory}![]u8 { var out: std.Io.Writer.Allocating = .init(allocator); errdefer out.deinit(); sf.writeDictionary(&out.writer, dictionary) catch return error.OutOfMemory; return out.toOwnedSlice(); } fn createMacHeaders(allocator: std.mem.Allocator, profile: Profile, covered: []u8, request: MacRequest, shared_secret: *const [32]u8) !MacHeaders { const mac = try macOver(allocator, profile, covered, request.signature_params, shared_secret); const signature_input = try std.fmt.allocPrint(allocator, "{s}={s}", .{ request.label, request.signature_params }); errdefer allocator.free(signature_input); var encoded: [44]u8 = undefined; const signature = try std.fmt.allocPrint(allocator, "{s}=:{s}:", .{ request.label, std.base64.standard.Encoder.encode(&encoded, &mac) }); return .{ .covered_name = profile.coveredHeader(), .covered = covered, .signature_input = signature_input, .signature = signature }; } fn macOver(allocator: std.mem.Allocator, profile: Profile, covered: []const u8, signature_params: []const u8, shared_secret: *const [32]u8) error{OutOfMemory}![32]u8 { const components = profile.components(); const base = try hs.signatureBase(allocator, &components, &.{covered}, signature_params); defer allocator.free(base); var mac: [32]u8 = undefined; HmacSha256.create(&mac, base, shared_secret); return mac; } // ---- verification ---- /// The headers of a response a syncer checks. pub const ResponseHeaders = struct { covered: ?[]const u8, signature_input: ?[]const u8, signature: ?[]const u8, }; /// What the syncer requested the MAC with (see `kem.encapsulate`). pub const Encapsulation = struct { key_share: []const u8, shared_secret: *const [32]u8, }; /// Verify a response's MAC, and that its `Atproto-Space-Commit` header /// describes `commit`. pub fn verifyCommitMac(allocator: std.mem.Allocator, commit: Commit, encapsulation: Encapsulation, headers: ResponseHeaders) Error!void { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const fields = try verifyMac(arena.allocator(), .commit, encapsulation, headers); const ver = bareItem(fields, "ver") orelse return error.InvalidSpaceMac; const data = bareItem(fields, "data") orelse return error.InvalidSpaceMac; const matches = ver == .integer and ver.integer == commit.ver and stringItem(fields, "repo", commit.repo) and stringItem(fields, "space", commit.space) and stringItem(fields, "rev", commit.rev) and data == .bytes and std.mem.eql(u8, data.bytes, &commit.data); if (!matches) return error.InvalidSpaceMac; } /// Verify a response's MAC, and that its `Atproto-Space-Record` header names /// `uri` and `cid`. pub fn verifyRecordMac(allocator: std.mem.Allocator, uri: []const u8, cid: []const u8, encapsulation: Encapsulation, headers: ResponseHeaders) Error!void { var arena = std.heap.ArenaAllocator.init(allocator); defer arena.deinit(); const fields = try verifyMac(arena.allocator(), .record, encapsulation, headers); if (!stringItem(fields, "uri", uri) or !stringItem(fields, "cid", cid)) return error.InvalidSpaceMac; } fn verifyMac(arena: std.mem.Allocator, profile: Profile, encapsulation: Encapsulation, headers: ResponseHeaders) Error!sf.Dictionary { const components = profile.components(); const found = hs.findSignature(arena, headers.signature_input, headers.signature, .{ .tag = profile.tag(), .components = &components, .alg = alg, .key_id = encapsulation.key_share, }) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, error.BadSpaceSignature => return error.InvalidSpaceMac, }; const fields = sf.parseDictionary(arena, headers.covered orelse return error.InvalidSpaceMac) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, else => return error.InvalidSpaceMac, }; // The `sf` flag covers the header as re-serialized from its parsed form. const canonical = try allocDictionary(arena, fields); const expected = try macOver(arena, profile, canonical, found.signature_params, encapsulation.shared_secret); if (found.signature.len != expected.len or !std.crypto.timing_safe.eql([32]u8, expected, found.signature[0..32].*)) return error.InvalidSpaceMac; return fields; } /// A dictionary member's bare item, ignoring any parameters. fn bareItem(fields: sf.Dictionary, key: []const u8) ?sf.BareItem { return switch (sf.get(fields, key) orelse return null) { .item => |it| it.bare, .inner_list => null, }; } fn stringItem(fields: sf.Dictionary, key: []const u8, expected: []const u8) bool { const value = bareItem(fields, key) orelse return false; return value == .string and std.mem.eql(u8, value.string, expected); } const testing = std.testing; const key_share_fixture = "did:key:zDnaExample"; const space_fixture = "at:space/did:example:space/app.bsky.group/test"; const uri_fixture = space_fixture ++ "/did:example:alice/app.bsky.feed.post/1"; const commit_fixture: Commit = .{ .space = space_fixture, .repo = "did:example:alice", .rev = "3kbcq3p7ad400", .data = @splat(1) }; const secret_fixture: [32]u8 = @splat(7); const encapsulation_fixture: Encapsulation = .{ .key_share = key_share_fixture, .shared_secret = &secret_fixture }; fn responseFor(headers: MacHeaders) ResponseHeaders { return .{ .covered = headers.covered, .signature_input = headers.signature_input, .signature = headers.signature }; } fn commitResponse(a: std.mem.Allocator, commit: Commit) !ResponseHeaders { const request = (try parseMacRequest(a, try formatMacRequest(a, .commit, key_share_fixture), .commit)).?; return responseFor(try createCommitMacHeaders(a, commit, request, &secret_fixture)); } /// A MAC over the commit header under hand-written parameters, standing in for /// a host that answers differently than this module does. fn commitResponseWithParams(a: std.mem.Allocator, params: []const u8) !ResponseHeaders { const covered = (try commitResponse(a, commit_fixture)).covered.?; const base = try std.fmt.allocPrint(a, "\"atproto-space-commit\";sf: {s}\n\"@signature-params\": {s}", .{ covered, params }); var mac: [32]u8 = undefined; HmacSha256.create(&mac, base, &secret_fixture); var encoded: [44]u8 = undefined; return .{ .covered = covered, .signature_input = try std.fmt.allocPrint(a, "mac={s}", .{params}), .signature = try std.fmt.allocPrint(a, "mac=:{s}:", .{std.base64.standard.Encoder.encode(&encoded, &mac)}), }; } test "formats and reads MAC requests" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const commit_request = try formatMacRequest(a, .commit, key_share_fixture); try testing.expectEqualStrings("mac=(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\"", commit_request); try testing.expectEqualStrings("mac=(\"atproto-space-record\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-record\"", try formatMacRequest(a, .record, key_share_fixture)); const parsed = (try parseMacRequest(a, commit_request, .commit)).?; try testing.expectEqualStrings("mac", parsed.label); try testing.expectEqualStrings(key_share_fixture, parsed.key_share); try testing.expectEqualStrings(commit_request["mac=".len..], parsed.signature_params); const other_label = "other=(\"content-digest\");tag=\"other\", m=(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\""; try testing.expectEqualStrings("m", (try parseMacRequest(a, other_label, .commit)).?.label); _ = (try parseMacRequest(a, try std.fmt.allocPrint(a, "{s};alg=\"hmac-sha256\"", .{commit_request}), .commit)).?; try testing.expect(try parseMacRequest(a, null, .commit) == null); const other_profile = try std.fmt.allocPrint(a, "other=(\"content-digest\");tag=\"other\", {s}", .{try formatMacRequest(a, .record, key_share_fixture)}); try testing.expect(try parseMacRequest(a, other_profile, .commit) == null); const draft_tag = "mac=(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-repo\""; try testing.expect(try parseMacRequest(a, draft_tag, .commit) == null); } test "refuses MAC requests the host cannot fulfill" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const commit_request = try formatMacRequest(a, .commit, key_share_fixture); const one = "(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\""; const bad = [_][]const u8{ "???", try std.fmt.allocPrint(a, "a={s}, b={s}", .{ one, one }), try std.fmt.allocPrint(a, "{s};alg=\"ecdsa-p256-sha256\"", .{commit_request}), try std.fmt.allocPrint(a, "{s};created=1", .{commit_request}), try std.fmt.allocPrint(a, "{s};expires=1", .{commit_request}), try std.fmt.allocPrint(a, "{s};nonce=\"abc\"", .{commit_request}), "mac=(\"atproto-space-record\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\"", "mac=(\"atproto-space-commit\");keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\"", "mac=(\"atproto-space-commit\";sf \"authorization\");keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\"", "mac=(\"atproto-space-commit\";sf);tag=\"atproto-space-commit\"", "mac=(\"atproto-space-commit\";sf);keyid=\"not-a-did\";tag=\"atproto-space-commit\"", }; for (bad) |value| try testing.expectError(error.InvalidSpaceMac, parseMacRequest(a, value, .commit)); } test "a commit MAC covers its header under the requested parameters" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const params = "(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\""; const request = (try parseMacRequest(a, "sig1=" ++ params, .commit)).?; const headers = try createCommitMacHeaders(a, commit_fixture, request, &secret_fixture); const covered = "ver=1, repo=\"did:example:alice\", space=\"" ++ space_fixture ++ "\", rev=\"3kbcq3p7ad400\", data=:AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE=:"; try testing.expectEqualStrings("atproto-space-commit", headers.covered_name); try testing.expectEqualStrings(covered, headers.covered); try testing.expectEqualStrings("sig1=" ++ params, headers.signature_input); var mac: [32]u8 = undefined; HmacSha256.create(&mac, "\"atproto-space-commit\";sf: " ++ covered ++ "\n\"@signature-params\": " ++ params, &secret_fixture); var encoded: [44]u8 = undefined; try testing.expectEqualStrings(try std.fmt.allocPrint(a, "sig1=:{s}:", .{std.base64.standard.Encoder.encode(&encoded, &mac)}), headers.signature); } test "a commit MAC verifies only for its commit and secret" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const response = try commitResponse(a, commit_fixture); try verifyCommitMac(a, commit_fixture, encapsulation_fixture, response); const other_secret: [32]u8 = @splat(8); try testing.expectError(error.InvalidSpaceMac, verifyCommitMac(a, commit_fixture, .{ .key_share = key_share_fixture, .shared_secret = &other_secret }, response)); var changed = [_]Commit{ commit_fixture, commit_fixture, commit_fixture, commit_fixture, commit_fixture }; changed[0].ver = 2; changed[1].repo = "did:example:bob"; changed[2].space = space_fixture ++ "2"; changed[3].rev = "3kbcq3p7ad401"; changed[4].data = @splat(2); for (changed) |commit| try testing.expectError(error.InvalidSpaceMac, verifyCommitMac(a, commit, encapsulation_fixture, response)); // a tampered header var tampered = response; tampered.covered = try std.mem.replaceOwned(u8, a, response.covered.?, "3kbcq3p7ad400", "3kbcq3p7ad401"); var tampered_commit = commit_fixture; tampered_commit.rev = "3kbcq3p7ad401"; try testing.expectError(error.InvalidSpaceMac, verifyCommitMac(a, tampered_commit, encapsulation_fixture, tampered)); // whitespace is not significant: the header is re-serialized var spaced = response; spaced.covered = try std.mem.replaceOwned(u8, a, response.covered.?, ", ", ", "); try verifyCommitMac(a, commit_fixture, encapsulation_fixture, spaced); // found by tag under any label var relabeled = response; relabeled.signature_input = try std.mem.replaceOwned(u8, a, response.signature_input.?, "mac=", "other="); relabeled.signature = try std.mem.replaceOwned(u8, a, response.signature.?, "mac=", "other="); try verifyCommitMac(a, commit_fixture, encapsulation_fixture, relabeled); // more than one MAC with the profile tag var doubled = response; doubled.signature_input = try std.fmt.allocPrint(a, "{s}, {s}", .{ response.signature_input.?, relabeled.signature_input.? }); doubled.signature = try std.fmt.allocPrint(a, "{s}, {s}", .{ response.signature.?, relabeled.signature.? }); try testing.expectError(error.InvalidSpaceMac, verifyCommitMac(a, commit_fixture, encapsulation_fixture, doubled)); // each header is required for (0..3) |missing| { var partial = response; switch (missing) { 0 => partial.covered = null, 1 => partial.signature_input = null, else => partial.signature = null, } try testing.expectError(error.InvalidSpaceMac, verifyCommitMac(a, commit_fixture, encapsulation_fixture, partial)); } } test "a commit MAC's parameters may vary within what the syncer asked for" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const accepted = [_][]const u8{ "(\"atproto-space-commit\";sf);tag=\"atproto-space-commit\";created=1700000000;keyid=\"did:key:zDnaExample\"", "(\"atproto-space-commit\";sf);tag=\"atproto-space-commit\"", "(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\";alg=\"hmac-sha256\"", }; for (accepted) |params| try verifyCommitMac(a, commit_fixture, encapsulation_fixture, try commitResponseWithParams(a, params)); const refused = [_][]const u8{ "(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaOther\";tag=\"atproto-space-commit\"", "(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\";alg=\"hmac-sha512\"", "(\"atproto-space-commit\";sf);keyid=\"did:key:zDnaExample\";tag=\"other\"", "(\"atproto-space-commit\");keyid=\"did:key:zDnaExample\";tag=\"atproto-space-commit\"", }; for (refused) |params| try testing.expectError(error.InvalidSpaceMac, verifyCommitMac(a, commit_fixture, encapsulation_fixture, try commitResponseWithParams(a, params))); } test "a record MAC covers the uri and cid, and is not a commit MAC" { var arena = std.heap.ArenaAllocator.init(testing.allocator); defer arena.deinit(); const a = arena.allocator(); const cid_a = "bafyreidefdycgbfy3oglcb6ism3eqhyp5llsrpzxjsuac2gsy4mtrtx244"; const cid_b = "bafyreidpw4cbv6gr4ukh33z23pvvrpr3wi4gnpmi4doamlsl3sa4rgri2a"; const request = (try parseMacRequest(a, try formatMacRequest(a, .record, key_share_fixture), .record)).?; const headers = try createRecordMacHeaders(a, uri_fixture, cid_a, request, &secret_fixture); try testing.expectEqualStrings("uri=\"" ++ uri_fixture ++ "\", cid=\"" ++ cid_a ++ "\"", headers.covered); const response = responseFor(headers); try verifyRecordMac(a, uri_fixture, cid_a, encapsulation_fixture, response); try testing.expectError(error.InvalidSpaceMac, verifyRecordMac(a, uri_fixture ++ "2", cid_a, encapsulation_fixture, response)); try testing.expectError(error.InvalidSpaceMac, verifyRecordMac(a, uri_fixture, cid_b, encapsulation_fixture, response)); try testing.expectError(error.InvalidSpaceMac, verifyCommitMac(a, commit_fixture, encapsulation_fixture, response)); }