~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
566 lines · 28.9 KB Raw History
//! Space repo and space meta archives, both STAR v1 (`star.zig`): a repo's
//! full state for `getRepo` and repo import, and a space host's policy, policy
//! state and writer set for space export and import. Mirrors `@atproto/space`
//! `sync/` and `space-meta-archive.ts`.

const std = @import("std");
const star = @import("../repo/star.zig");
const cbor = @import("../repo/cbor.zig");
const Did = @import("../syntax/did.zig").Did;
const Nsid = @import("../syntax/nsid.zig").Nsid;
const Rkey = @import("../syntax/rkey.zig").Rkey;
const Tid = @import("../syntax/tid.zig").Tid;
const SpaceUri = @import("ref.zig").SpaceUri;
const lthash = @import("lthash.zig");
const mac = @import("mac.zig");

const LtHash = lthash.LtHash;
const recordElement = lthash.recordElement;
const digest_bytes = lthash.digest_bytes;

pub const Commit = mac.Commit;
pub const commit_version = 1;

/// The Spaces alpha bounds a space record's DRISL encoding at 1 MiB.
pub const max_space_record_bytes = 1024 * 1024;

pub const RepoRecordBlock = struct {
    path: []const u8,
    cid: cbor.Cid,
    data: []const u8,
};

pub const VerifiedRepo = struct {
    arena: std.heap.ArenaAllocator,
    commit: Commit,
    records: []const RepoRecordBlock,

    pub fn deinit(self: *VerifiedRepo) void {
        self.arena.deinit();
    }
};

/// A commit over a repo's current LtHash state. It carries no signature: the
/// repo host authenticates it to each syncer with a per-request MAC.
pub fn commitForState(state: []const u8, ctx: struct { space: []const u8, repo: []const u8, rev: []const u8 }) !Commit {
    const hash = try LtHash.fromBytes(state);
    return .{ .repo = ctx.repo, .space = ctx.space, .rev = ctx.rev, .data = hash.digest() };
}

/// `com.atproto.space.defs#commit` as JSON, with `$bytes` unpadded as the
/// reference emits it.
pub fn commitJson(allocator: std.mem.Allocator, commit: Commit) ![]u8 {
    var data: [43]u8 = undefined;
    return std.fmt.allocPrint(
        allocator,
        "{{\"ver\":{d},\"repo\":{f},\"space\":{f},\"rev\":{f},\"data\":{{\"$bytes\":\"{s}\"}}}}",
        .{ commit.ver, std.json.fmt(commit.repo, .{}), std.json.fmt(commit.space, .{}), std.json.fmt(commit.rev, .{}), std.base64.standard_no_pad.Encoder.encode(&data, &commit.data) },
    );
}

pub const repo_star_type = "atproto-space-repo";

/// Serialize a full-state repo as a STAR v1 archive: magic, the commit as
/// DRISL metadata, then one record path / record DRISL pair per record in
/// strict bytewise path order.
pub fn writeRepoStar(
    allocator: std.mem.Allocator,
    commit: Commit,
    records: []RepoRecordBlock,
) ![]u8 {
    std.mem.sort(RepoRecordBlock, records, {}, recordPathLessThan);
    var out: std.Io.Writer.Allocating = .init(allocator);
    errdefer out.deinit();
    var writer = try star.Writer.init(allocator, &out.writer, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = repo_star_type } },
        .{ .key = "ver", .value = .{ .unsigned = commit.ver } },
        .{ .key = "repo", .value = .{ .text = commit.repo } },
        .{ .key = "space", .value = .{ .text = commit.space } },
        .{ .key = "rev", .value = .{ .text = commit.rev } },
        .{ .key = "data", .value = .{ .bytes = &commit.data } },
    } }, .{ .ordered_keys = true });
    defer writer.deinit();
    for (records, 0..) |record, idx| {
        if (idx > 0 and std.mem.eql(u8, records[idx - 1].path, record.path)) return error.DuplicateRecordPath;
        try writer.writePair(record.path, record.data);
    }
    try writer.finish();
    return out.toOwnedSlice();
}

fn recordPathLessThan(_: void, left: RepoRecordBlock, right: RepoRecordBlock) bool {
    return std.mem.order(u8, left.path, right.path) == .lt;
}

/// Check a full-state permissioned repo STAR archive against the MAC its
/// `getRepo` response carried (see `mac.verifyCommitMac`). The MAC shows the repo host vouched for this
/// commit to whoever holds the shared secret; it proves nothing to a third
/// party, who could not tell it from one the holder forged. The returned value
/// owns its data and must be deinitialized by the caller.
pub fn verifyRepoStarFull(
    allocator: std.mem.Allocator,
    star_bytes: []const u8,
    ctx: struct { space: []const u8, repo: []const u8 },
    encapsulation: mac.Encapsulation,
    headers: mac.ResponseHeaders,
) !VerifiedRepo {
    var arena = std.heap.ArenaAllocator.init(allocator);
    errdefer arena.deinit();
    const a = arena.allocator();
    var input: std.Io.Reader = .fixed(star_bytes);
    var reader = try star.Reader.init(a, &input, .{ .max_value = max_space_record_bytes });
    defer reader.deinit();

    const commit = try repoStarCommit(a, reader.metadata);
    if (!std.mem.eql(u8, commit.repo, ctx.repo)) return error.InvalidRepoCommit;
    if (!std.mem.eql(u8, commit.space, ctx.space)) return error.InvalidRepoCommit;
    mac.verifyCommitMac(allocator, commit, encapsulation, headers) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        error.InvalidSpaceMac => return error.InvalidRepoCommit,
    };
    const records = try repoStarRecords(a, &reader, commit, false);
    return .{ .arena = arena, .commit = commit, .records = records };
}

/// Read a full-state repo STAR archive without authenticating its commit,
/// checking that its records fold to the commit's data and are canonical DRISL.
/// For a repo host importing the authenticated account's own repo; syncers
/// reading other accounts' repos use verifyRepoStarFull.
pub fn readRepoStar(allocator: std.mem.Allocator, star_bytes: []const u8) !VerifiedRepo {
    var arena = std.heap.ArenaAllocator.init(allocator);
    errdefer arena.deinit();
    const a = arena.allocator();
    var input: std.Io.Reader = .fixed(star_bytes);
    var reader = try star.Reader.init(a, &input, .{ .max_value = max_space_record_bytes });
    defer reader.deinit();

    const commit = try repoStarCommit(a, reader.metadata);
    if (Did.parse(commit.repo) == null) return error.InvalidRepoCommit;
    if (SpaceUri.parseRef(commit.space) == null) return error.InvalidRepoCommit;
    const records = try repoStarRecords(a, &reader, commit, true);
    return .{ .arena = arena, .commit = commit, .records = records };
}

fn repoStarCommit(a: std.mem.Allocator, meta: cbor.Value) !Commit {
    const star_type = meta.getString("$type") orelse return error.InvalidRepoStar;
    if (!std.mem.eql(u8, star_type, repo_star_type)) return error.InvalidRepoStar;
    if (meta.getUint("ver") != commit_version) return error.InvalidRepoCommit;
    const commit_data = meta.getBytes("data") orelse return error.InvalidRepoCommit;
    if (commit_data.len != digest_bytes) return error.InvalidRepoCommit;
    return .{
        .repo = try a.dupe(u8, meta.getString("repo") orelse return error.InvalidRepoCommit),
        .space = try a.dupe(u8, meta.getString("space") orelse return error.InvalidRepoCommit),
        .rev = try a.dupe(u8, meta.getString("rev") orelse return error.InvalidRepoCommit),
        .data = commit_data[0..digest_bytes].*,
    };
}

fn repoStarRecords(a: std.mem.Allocator, reader: *star.Reader, commit: Commit, require_canonical: bool) ![]const RepoRecordBlock {
    var records: std.ArrayList(RepoRecordBlock) = .empty;
    var set_hash: LtHash = .{};
    var previous: ?[]const u8 = null;
    while (try reader.next()) |entry| {
        const path = try a.dupe(u8, entry.key);
        if (previous) |prior| {
            if (std.mem.order(u8, prior, path) != .lt) return error.InvalidRepoPath;
        }
        previous = path;
        const slash = std.mem.indexOfScalar(u8, path, '/') orelse return error.InvalidRepoPath;
        const collection = path[0..slash];
        const rkey = path[slash + 1 ..];
        if (Nsid.parse(collection) == null or Rkey.parse(rkey) == null) return error.InvalidRepoPath;

        const data = try a.alloc(u8, @intCast(entry.value_len));
        if (try reader.readValue(data) != data.len) return error.InvalidRepoStar;
        const record = try cbor.decodeAll(a, data);
        if (record != .map) return error.InvalidRepoRecord;
        if (require_canonical and !std.mem.eql(u8, try cbor.encodeAlloc(a, record), data)) return error.InvalidRepoRecord;
        const cid = try cbor.Cid.forDagCbor(a, data);
        set_hash.add(try recordElement(a, collection, rkey, try cid.toString(a)));
        try records.append(a, .{ .path = path, .cid = cid, .data = data });
    }
    if (!std.mem.eql(u8, &set_hash.digest(), &commit.data)) return error.InvalidRepoIndex;
    return records.items;
}

pub const space_meta_star_type = "atproto-space-meta";
pub const space_meta_version = 1;
const space_meta_policy_key = "policy";
const space_meta_writer_prefix = "writer/";

/// An entry of a policy's own state in a space meta archive, keyed like a
/// record path.
pub const SpaceMetaEntry = struct { key: []const u8, value: cbor.Value };

/// A writer-set entry, as listWriters reports it.
pub const SpaceMetaWriter = struct {
    did: []const u8,
    repo_rev: []const u8,
    data: [digest_bytes]u8,
    space_rev: []const u8,
};

pub const SpaceMetaArchive = struct {
    arena: std.heap.ArenaAllocator,
    space: []const u8,
    policy: cbor.Value,
    policy_state: []const SpaceMetaEntry,
    writers: []const SpaceMetaWriter,

    pub fn deinit(self: *SpaceMetaArchive) void {
        self.arena.deinit();
    }
};

/// Serialize a space's host-side state as an `atproto-space-meta` STAR
/// archive: the policy, then its state, then the writer set, each section in
/// strict bytewise key order.
pub fn writeSpaceMetaStar(
    allocator: std.mem.Allocator,
    space: []const u8,
    policy: cbor.Value,
    policy_state: []const SpaceMetaEntry,
    writers: []const SpaceMetaWriter,
) ![]u8 {
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const a = arena.allocator();
    var out: std.Io.Writer.Allocating = .init(allocator);
    errdefer out.deinit();
    var writer = try star.Writer.init(a, &out.writer, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = space_meta_star_type } },
        .{ .key = "ver", .value = .{ .unsigned = space_meta_version } },
        .{ .key = "space", .value = .{ .text = space } },
    } }, .{});
    defer writer.deinit();
    try writer.writePair(space_meta_policy_key, try cbor.encodeAlloc(a, policy));

    const state = try a.dupe(SpaceMetaEntry, policy_state);
    std.mem.sort(SpaceMetaEntry, state, {}, entryKeyLessThan);
    for (state, 0..) |entry, idx| {
        if (idx > 0 and std.mem.eql(u8, state[idx - 1].key, entry.key)) return error.DuplicateKey;
        try writer.writePair(entry.key, try cbor.encodeAlloc(a, entry.value));
    }

    const keyed = try a.alloc(SpaceMetaEntry, writers.len);
    for (writers, 0..) |w, idx| {
        keyed[idx] = .{
            .key = try std.fmt.allocPrint(a, space_meta_writer_prefix ++ "{s}", .{w.did}),
            .value = .{ .map = try a.dupe(cbor.Value.MapEntry, &.{
                .{ .key = "data", .value = .{ .bytes = try a.dupe(u8, &w.data) } },
                .{ .key = "repoRev", .value = .{ .text = w.repo_rev } },
                .{ .key = "spaceRev", .value = .{ .text = w.space_rev } },
            }) },
        };
    }
    std.mem.sort(SpaceMetaEntry, keyed, {}, entryKeyLessThan);
    for (keyed, 0..) |entry, idx| {
        if (idx > 0 and std.mem.eql(u8, keyed[idx - 1].key, entry.key)) return error.DuplicateKey;
        try writer.writePair(entry.key, try cbor.encodeAlloc(a, entry.value));
    }
    try writer.finish();
    return out.toOwnedSlice();
}

fn entryKeyLessThan(_: void, left: SpaceMetaEntry, right: SpaceMetaEntry) bool {
    return std.mem.order(u8, left.key, right.key) == .lt;
}

const SpaceMetaSection = enum(u2) { policy, policy_state, writers };

fn spaceMetaSection(key: []const u8) SpaceMetaSection {
    if (std.mem.eql(u8, key, space_meta_policy_key)) return .policy;
    if (std.mem.startsWith(u8, key, space_meta_writer_prefix)) return .writers;
    return .policy_state;
}

/// Read an `atproto-space-meta` archive, rejecting it when a section is out of
/// place, a key is duplicated or out of order, a value is not a map, or the
/// policy is missing. Interpreting the policy and its state is the caller's.
pub fn readSpaceMetaStar(allocator: std.mem.Allocator, star_bytes: []const u8) !SpaceMetaArchive {
    var arena = std.heap.ArenaAllocator.init(allocator);
    errdefer arena.deinit();
    const a = arena.allocator();
    var input: std.Io.Reader = .fixed(star_bytes);
    var reader = try star.Reader.init(a, &input, .{ .max_value = max_space_record_bytes });
    defer reader.deinit();

    const meta = reader.metadata;
    if (!std.mem.eql(u8, meta.getString("$type") orelse return error.InvalidSpaceMeta, space_meta_star_type)) return error.InvalidSpaceMeta;
    if (meta.getUint("ver") != space_meta_version) return error.InvalidSpaceMeta;
    const space = try a.dupe(u8, meta.getString("space") orelse return error.InvalidSpaceMeta);
    if (SpaceUri.parseRef(space) == null) return error.InvalidSpaceMeta;

    var policy: ?cbor.Value = null;
    var state: std.ArrayList(SpaceMetaEntry) = .empty;
    var writers: std.ArrayList(SpaceMetaWriter) = .empty;
    var section: ?SpaceMetaSection = null;
    var previous: ?[]const u8 = null;
    while (try reader.next()) |entry| {
        const key = try a.dupe(u8, entry.key);
        const key_section = spaceMetaSection(key);
        if (section == null or key_section != section.?) {
            if (section) |current| if (@backingInt(key_section) < @backingInt(current)) return error.SectionOutOfOrder;
            section = key_section;
            previous = null;
        }
        if (previous) |prior| if (std.mem.order(u8, prior, key) != .lt) return error.KeyOutOfOrder;
        previous = key;

        const data = try a.alloc(u8, @intCast(entry.value_len));
        if (try reader.readValue(data) != data.len) return error.InvalidSpaceMeta;
        const value = cbor.decodeAll(a, data) catch return error.InvalidSpaceMeta;
        if (value != .map) return error.InvalidSpaceMeta;
        switch (key_section) {
            .policy => policy = value,
            .policy_state => try state.append(a, .{ .key = key, .value = value }),
            .writers => {
                const did = key[space_meta_writer_prefix.len..];
                if (Did.parse(did) == null) return error.InvalidSpaceMeta;
                const rev = value.getString("repoRev") orelse return error.InvalidSpaceMeta;
                const space_rev = value.getString("spaceRev") orelse return error.InvalidSpaceMeta;
                const hash = value.getBytes("data") orelse return error.InvalidSpaceMeta;
                if (Tid.parse(rev) == null or Tid.parse(space_rev) == null or hash.len != digest_bytes) return error.InvalidSpaceMeta;
                try writers.append(a, .{ .did = did, .repo_rev = rev, .data = hash[0..digest_bytes].*, .space_rev = space_rev });
            },
        }
    }
    return .{
        .arena = arena,
        .space = space,
        .policy = policy orelse return error.MissingPolicy,
        .policy_state = state.items,
        .writers = writers.items,
    };
}

test "permissioned repo STAR carries the commit in metadata and records in path order" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const first_data = try cbor.encodeAlloc(allocator, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = "fm.example.note" } },
        .{ .key = "text", .value = .{ .text = "first" } },
    } });
    const second_data = try cbor.encodeAlloc(allocator, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = "fm.example.note" } },
        .{ .key = "text", .value = .{ .text = "second" } },
    } });
    const first_cid = try cbor.Cid.forDagCbor(allocator, first_data);
    const second_cid = try cbor.Cid.forDagCbor(allocator, second_data);
    const first_cid_text = try first_cid.toString(allocator);
    const second_cid_text = try second_cid.toString(allocator);

    var state: LtHash = .{};
    state.add(try recordElement(allocator, "fm.example.note", "one", first_cid_text));
    state.add(try recordElement(allocator, "fm.example.note", "two", second_cid_text));
    const space = "at:space/did:plc:alice/fm.example.private/self";
    const commit = try commitForState(&state.bytes, .{ .space = space, .repo = "did:plc:alice", .rev = "3mrepoexporttest" });
    var records = [_]RepoRecordBlock{
        .{ .path = "fm.example.note/two", .cid = second_cid, .data = second_data },
        .{ .path = "fm.example.note/one", .cid = first_cid, .data = first_data },
    };
    const bytes = try writeRepoStar(allocator, commit, &records);
    try std.testing.expectEqualSlices(u8, star.magic, bytes[0..4]);
    const secret: [32]u8 = @splat(9);
    const response = try testMacResponse(allocator, commit, &secret);
    var verified = try verifyRepoStarFull(allocator, bytes, .{ .space = space, .repo = "did:plc:alice" }, .{ .key_share = test_key_share, .shared_secret = &secret }, response);
    defer verified.deinit();
    try std.testing.expectEqualStrings("3mrepoexporttest", verified.commit.rev);
    try std.testing.expectEqual(@as(usize, 2), verified.records.len);
    try std.testing.expectEqualStrings("fm.example.note/one", verified.records[0].path);
    try std.testing.expectEqualSlices(u8, first_cid.raw, verified.records[0].cid.raw);
    try std.testing.expectEqualStrings("fm.example.note/two", verified.records[1].path);
    try std.testing.expectError(error.InvalidRepoCommit, verifyRepoStarFull(allocator, bytes, .{ .space = space, .repo = "did:plc:bob" }, .{ .key_share = test_key_share, .shared_secret = &secret }, response));
    const other: [32]u8 = @splat(8);
    try std.testing.expectError(error.InvalidRepoCommit, verifyRepoStarFull(allocator, bytes, .{ .space = space, .repo = "did:plc:alice" }, .{ .key_share = test_key_share, .shared_secret = &other }, response));
}

test "commit JSON matches com.atproto.space.defs#commit" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const commit: Commit = .{ .repo = "did:plc:alice", .space = "at:space/did:plc:alice/fm.example.private/self", .rev = "3mrev", .data = @splat(1) };
    try std.testing.expectEqualStrings(
        "{\"ver\":1,\"repo\":\"did:plc:alice\",\"space\":\"at:space/did:plc:alice/fm.example.private/self\",\"rev\":\"3mrev\",\"data\":{\"$bytes\":\"AQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQE\"}}",
        try commitJson(arena.allocator(), commit),
    );
}

const reference_space = "at:space/did:plc:refauthority/com.example.forum/general";
const reference_repo = "did:plc:refuser";

fn referenceStar(allocator: std.mem.Allocator) ![]u8 {
    const encoded = std.mem.trim(u8, @embedFile("testdata/space-reference-repo.star-v1.base64"), "\r\n");
    const star_bytes = try allocator.alloc(u8, try std.base64.standard.Decoder.calcSizeForSlice(encoded));
    try std.base64.standard.Decoder.decode(star_bytes, encoded);
    return star_bytes;
}

test "permissioned repo STAR rejects out-of-order and duplicate paths" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const data = try cbor.encodeAlloc(allocator, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = "fm.example.note" } },
    } });
    const cid = try cbor.Cid.forDagCbor(allocator, data);
    const commit: Commit = .{ .repo = "a", .space = "s", .rev = "3mstarorder", .data = @splat(0) };
    var duplicate = [_]RepoRecordBlock{
        .{ .path = "z.x/a", .cid = cid, .data = data },
        .{ .path = "z.x/a", .cid = cid, .data = data },
    };
    try std.testing.expectError(error.DuplicateRecordPath, writeRepoStar(allocator, commit, &duplicate));
    var records = [_]RepoRecordBlock{
        .{ .path = "z.x/a", .cid = cid, .data = data },
        .{ .path = "longer.path/b", .cid = cid, .data = data },
    };
    const bytes = try writeRepoStar(allocator, commit, &records);
    // Bytewise, not DAG-CBOR length-first, ordering.
    try std.testing.expect(std.mem.indexOf(u8, bytes, "longer.path/b").? < std.mem.indexOf(u8, bytes, "z.x/a").?);
}

fn testSpaceMetaStar(allocator: std.mem.Allocator, keys: []const []const u8) ![]u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    var writer = try star.Writer.init(allocator, &out.writer, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = space_meta_star_type } },
        .{ .key = "ver", .value = .{ .unsigned = space_meta_version } },
        .{ .key = "space", .value = .{ .text = "at:space/did:plc:alice/fm.example.notes/self" } },
    } }, .{});
    const data: [digest_bytes]u8 = @splat(1);
    const map = try cbor.encodeAlloc(allocator, .{ .map = &.{
        .{ .key = "data", .value = .{ .bytes = &data } },
        .{ .key = "repoRev", .value = .{ .text = "3mrevaaaaaa22" } },
        .{ .key = "spaceRev", .value = .{ .text = "3mspaceaaaa22" } },
    } });
    for (keys) |key| try writer.writePair(key, map);
    try writer.finish();
    return out.toOwnedSlice();
}

test "space meta archives round-trip in section and key order" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const space = "at:space/did:plc:alice/fm.example.notes/self";
    const policy: cbor.Value = .{ .map = &.{.{ .key = "$type", .value = .{ .text = "com.atproto.memberspace.policy" } }} };
    const member = cbor.Value{ .map = &.{ .{ .key = "read", .value = .{ .boolean = true } }, .{ .key = "write", .value = .{ .boolean = false } } } };
    const bytes = try writeSpaceMetaStar(a, space, policy, &.{
        .{ .key = "com.atproto.memberspace.member/did:plc:zed", .value = member },
        .{ .key = "com.atproto.memberspace.member/did:plc:bob", .value = member },
    }, &.{
        .{ .did = "did:plc:zed", .repo_rev = "3mrevzzzzzz22", .data = @splat(2), .space_rev = "3mspacezzzz22" },
        .{ .did = "did:plc:bob", .repo_rev = "3mrevbbbbbb22", .data = @splat(1), .space_rev = "3mspacebbbb22" },
    });
    var archive = try readSpaceMetaStar(std.testing.allocator, bytes);
    defer archive.deinit();
    try std.testing.expectEqualStrings(space, archive.space);
    try std.testing.expectEqualStrings("com.atproto.memberspace.policy", archive.policy.getString("$type").?);
    try std.testing.expectEqual(@as(usize, 2), archive.policy_state.len);
    try std.testing.expectEqualStrings("com.atproto.memberspace.member/did:plc:bob", archive.policy_state[0].key);
    try std.testing.expectEqualStrings("did:plc:bob", archive.writers[0].did);
    try std.testing.expectEqualStrings("3mspacezzzz22", archive.writers[1].space_rev);
    try std.testing.expectEqual(@as(u8, 2), archive.writers[1].data[0]);
}

test "space meta archives reject misplaced, duplicate, or missing keys" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const cases = [_]struct { keys: []const []const u8, err: anyerror }{
        .{ .keys = &.{"com.atproto.memberspace.member/did:plc:bob"}, .err = error.MissingPolicy },
        .{ .keys = &.{ "writer/did:plc:bob", "policy" }, .err = error.SectionOutOfOrder },
        .{ .keys = &.{ "policy", "writer/did:plc:bob", "com.atproto.memberspace.member/did:plc:bob" }, .err = error.SectionOutOfOrder },
        .{ .keys = &.{ "policy", "com.atproto.memberspace.member/did:plc:zed", "com.atproto.memberspace.member/did:plc:bob" }, .err = error.KeyOutOfOrder },
        .{ .keys = &.{ "policy", "policy" }, .err = error.KeyOutOfOrder },
        .{ .keys = &.{ "policy", "writer/not-a-did" }, .err = error.InvalidSpaceMeta },
    };
    for (cases) |case| {
        try std.testing.expectError(case.err, readSpaceMetaStar(std.testing.allocator, try testSpaceMetaStar(a, case.keys)));
    }
}

test "imported repo archives must fold to the commit and be canonical" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const record = try cbor.encodeAlloc(a, .{ .map = &.{.{ .key = "$type", .value = .{ .text = "fm.example.note" } }} });
    const cid = try cbor.Cid.forDagCbor(a, record);
    var hash: LtHash = .{};
    hash.add(try recordElement(a, "fm.example.note", "one", try cid.toString(a)));
    const commit: Commit = .{ .repo = "did:plc:alice", .space = "at:space/did:plc:alice/fm.example.notes/self", .rev = "3mrevaaaaaa22", .data = hash.digest() };
    var blocks = [_]RepoRecordBlock{.{ .path = "fm.example.note/one", .cid = cid, .data = record }};
    var repo = try readRepoStar(std.testing.allocator, try writeRepoStar(a, commit, &blocks));
    defer repo.deinit();
    try std.testing.expectEqualStrings("did:plc:alice", repo.commit.repo);
    try std.testing.expectEqual(@as(usize, 1), repo.records.len);

    var wrong = commit;
    wrong.data = @splat(0);
    try std.testing.expectError(error.InvalidRepoIndex, readRepoStar(std.testing.allocator, try writeRepoStar(a, wrong, &blocks)));
}

const test_key_share = "did:key:zDnaExample";

fn testMacResponse(a: std.mem.Allocator, commit: Commit, secret: *const [32]u8) !mac.ResponseHeaders {
    const request = (try mac.parseMacRequest(a, try mac.formatMacRequest(a, .commit, test_key_share), .commit)).?;
    const headers = try mac.createCommitMacHeaders(a, commit, request, secret);
    return .{ .covered = headers.covered, .signature_input = headers.signature_input, .signature = headers.signature };
}

test "reads the reference repo archive and writes it back byte for byte" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const star_bytes = try referenceStar(allocator);
    const read = try readRepoStar(allocator, star_bytes);
    const secret: [32]u8 = @splat(0x42);
    const encapsulation: mac.Encapsulation = .{ .key_share = test_key_share, .shared_secret = &secret };
    const response = try testMacResponse(allocator, read.commit, &secret);

    var verified = try verifyRepoStarFull(allocator, star_bytes, .{ .space = reference_space, .repo = reference_repo }, encapsulation, response);
    defer verified.deinit();
    try std.testing.expectEqualStrings("3mstarrefrevaa", verified.commit.rev);
    try std.testing.expectEqual(@as(usize, 5), verified.records.len);
    try std.testing.expectEqualStrings("com.e.p/x", verified.records[0].path);
    try std.testing.expectEqualStrings("com.example.post.reply/q", verified.records[1].path);
    try std.testing.expectEqualStrings("com.example.post/aaa", verified.records[2].path);
    try std.testing.expectEqualStrings("com.example.post/bbb", verified.records[3].path);
    try std.testing.expectEqualStrings("com.example.reply/zz", verified.records[4].path);
    const records = try allocator.dupe(RepoRecordBlock, verified.records);
    try std.testing.expectEqualSlices(u8, star_bytes, try writeRepoStar(allocator, verified.commit, records));
    var legacy = verified.commit;
    legacy.space = "at://did:plc:refauthority/space/com.example.forum/general";
    try std.testing.expectError(error.InvalidRepoCommit, readRepoStar(allocator, try writeRepoStar(allocator, legacy, records)));
    try std.testing.expectError(error.InvalidRepoCommit, verifyRepoStarFull(allocator, star_bytes, .{ .space = "at:space/did:plc:refauthority/com.example.forum/other", .repo = reference_repo }, encapsulation, response));
}

test "a shared-secret holder can MAC its own substitute repo" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const star_bytes = try referenceStar(allocator);
    const secret: [32]u8 = @splat(0x42);
    const encapsulation: mac.Encapsulation = .{ .key_share = test_key_share, .shared_secret = &secret };
    const original = try readRepoStar(allocator, star_bytes);
    const response = try testMacResponse(allocator, original.commit, &secret);

    const replacement = try cbor.encodeAlloc(allocator, .{ .map = &.{
        .{ .key = "$type", .value = .{ .text = "com.example.post" } },
        .{ .key = "text", .value = .{ .text = "replacement by a reader" } },
    } });
    const cid = try cbor.Cid.forDagCbor(allocator, replacement);
    var records = [_]RepoRecordBlock{.{ .path = "com.example.post/aaa", .cid = cid, .data = replacement }};
    var state: LtHash = .{};
    state.add(try recordElement(allocator, "com.example.post", "aaa", try cid.toString(allocator)));
    var substituted = original.commit;
    substituted.data = state.digest();
    const substituted_star = try writeRepoStar(allocator, substituted, &records);
    // The host's MAC no longer matches...
    try std.testing.expectError(error.InvalidRepoCommit, verifyRepoStarFull(allocator, substituted_star, .{ .space = reference_space, .repo = reference_repo }, encapsulation, response));
    // ...but the syncer holds the secret too, so it can MAC its own forgery. That
    // deniability is the point: a leaked response proves nothing to anyone else.
    var accepted = try verifyRepoStarFull(allocator, substituted_star, .{ .space = reference_space, .repo = reference_repo }, encapsulation, try testMacResponse(allocator, substituted, &secret));
    defer accepted.deinit();
    try std.testing.expectEqualSlices(u8, replacement, accepted.records[0].data);
}