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

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
817 lines · 41.7 KB Raw History
const std = @import("std");
const auth = @import("../auth/tokens.zig");
const clock = @import("../core/clock.zig");
const config = @import("../core/config.zig");
const http_api = @import("../http/api.zig");
const scopes = @import("../internal/scopes.zig");
const service_auth = @import("../internal/service_auth.zig");
const store = @import("../storage/store.zig");
const sync = @import("sync.zig");
const zat = @import("zat");

const http = std.http;
const max_repo_write_body_len = 5 * 1024 * 1024;
const max_apply_writes_body_len = 5 * 1024 * 1024;
// the reference PDS's messages (api/com/atproto/repo/applyWrites.ts and
// actor-store/repo/transactor.ts processWrites)
const too_many_writes_message = "Too many writes. Max: 200";
const commit_too_large_message = "Too many writes. Max event size: 2MB";

pub fn createRecord(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireAccount(request, allocator) catch return;
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown_and_deactivation);
    const body = http_api.readBodyAlloc(request, allocator, max_repo_write_body_len) catch |err| switch (err) {
        error.BodyTooLarge => return http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "record write body is too large"),
        else => return err,
    };
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    try requireRepoMatches(request, account, parsed.value);
    var options = parseWriteOptions(request, parsed.value) catch return;
    var missing_blob: ?[]const u8 = null;
    options.missing_blob = &missing_blob;
    const collection = zat.json.getString(parsed.value, "collection") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
    };
    try requireRepoScope(request, auth_ctx.oauth_scope, .create, collection);
    const rkey = zat.json.getString(parsed.value, "rkey");
    const record_value = recordBodyValue(parsed.value) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing record");
    };

    const result = store.applyWritesWithOptions(allocator, account, &.{.{ .create = .{
        .collection = collection,
        .rkey = rkey,
        .value = try withRecordType(allocator, collection, record_value),
    } }}, options) catch |err| switch (err) {
        error.InvalidCollection => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid collection"),
        error.InvalidRecordKey => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid rkey"),
        error.RecordTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record exceeds 1000000 encoded bytes"),
        error.TooManyWrites => return http_api.xrpcError(request, .bad_request, "InvalidRequest", too_many_writes_message),
        error.CommitTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", commit_too_large_message),
        error.BlobNotFound => return blobNotFound(request, allocator, missing_blob),
        error.InvalidRecordType => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid record type"),
        error.InvalidSwap => return http_api.xrpcError(request, .bad_request, "InvalidSwap", "swapCommit did not match current commit"),
        error.RecordAlreadyExists => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Record already exists"),
        error.ValidationRequired => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Record type is not known to this PDS"),
        error.InvalidDagCbor => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record is outside the atproto data model"),
        else => return err,
    };
    sync.notifyCrawlers(false);
    return writeRecordRef(request, allocator, result.records[0], result.commit);
}

pub fn putRecord(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireAccount(request, allocator) catch return;
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown_and_deactivation);
    const body = http_api.readBodyAlloc(request, allocator, max_repo_write_body_len) catch |err| switch (err) {
        error.BodyTooLarge => return http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "record write body is too large"),
        else => return err,
    };
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    try requireRepoMatches(request, account, parsed.value);
    var options = parseWriteOptions(request, parsed.value) catch return;
    var missing_blob: ?[]const u8 = null;
    options.missing_blob = &missing_blob;
    const swap = parseRecordSwap(request, parsed.value) catch return;
    const collection = zat.json.getString(parsed.value, "collection") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
    };
    try requireRepoScope(request, auth_ctx.oauth_scope, .update, collection);
    const rkey = zat.json.getString(parsed.value, "rkey") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey");
    };
    const record_value = recordBodyValue(parsed.value) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing record");
    };

    const result = store.applyWritesWithOptions(allocator, account, &.{.{ .update = .{
        .collection = collection,
        .rkey = rkey,
        .value = try withRecordType(allocator, collection, record_value),
        .swap = swap,
    } }}, options) catch |err| switch (err) {
        error.InvalidCollection => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid collection"),
        error.InvalidRecordKey => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid rkey"),
        error.RecordTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record exceeds 1000000 encoded bytes"),
        error.TooManyWrites => return http_api.xrpcError(request, .bad_request, "InvalidRequest", too_many_writes_message),
        error.CommitTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", commit_too_large_message),
        error.BlobNotFound => return blobNotFound(request, allocator, missing_blob),
        error.InvalidRecordType => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid record type"),
        error.InvalidSwap => return http_api.xrpcError(request, .bad_request, "InvalidSwap", "swapCommit or swapRecord did not match current repo state"),
        error.ValidationRequired => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Record type is not known to this PDS"),
        error.InvalidDagCbor => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record is outside the atproto data model"),
        else => return err,
    };
    sync.notifyCrawlers(false);
    return writeRecordRef(request, allocator, result.records[0], result.commit);
}

pub fn describeRepo(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    const account = store.resolveRepo(allocator, repo) orelse {
        return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found");
    };
    try requirePublicRepoAvailable(request, account.did);
    const collections = try store.listCollectionsJson(allocator, account.did);
    const body = try std.fmt.allocPrint(
        allocator,
        "{{\"handle\":{f},\"did\":{f},\"didDoc\":{{\"id\":{f},\"alsoKnownAs\":[{f}],\"service\":[{{\"id\":\"#atproto_pds\",\"type\":\"AtprotoPersonalDataServer\",\"serviceEndpoint\":{f}}}]}},\"collections\":{s},\"handleIsCorrect\":true}}",
        .{
            std.json.fmt(account.handle, .{}),
            std.json.fmt(account.did, .{}),
            std.json.fmt(account.did, .{}),
            std.json.fmt(try std.fmt.allocPrint(allocator, "at://{s}", .{account.handle}), .{}),
            std.json.fmt(config.publicUrl(), .{}),
            collections,
        },
    );
    return http_api.json(request, .ok, body);
}

pub fn getRecord(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    const account = store.resolveRepo(allocator, repo) orelse return repoNotHosted(request, allocator, repo);
    const status = store.accountStatus(account.did) catch |err| switch (err) {
        error.RepoNotFound => return repoNotHosted(request, allocator, repo),
        else => return err,
    };
    if (status == .deleted) return repoNotHosted(request, allocator, repo);
    if (!status.isActive()) return accountStatusError(request, status);
    var collection_buf: [256]u8 = undefined;
    const collection = http_api.queryParam(request.url.raw, "collection", &collection_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
    };
    var rkey_buf: [512]u8 = undefined;
    const rkey = http_api.queryParam(request.url.raw, "rkey", &rkey_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey");
    };

    const record = store.get(allocator, account.did, collection, rkey) orelse {
        return recordNotFound(request, allocator, account.did, collection, rkey);
    };
    var cid_buf: [256]u8 = undefined;
    if (http_api.queryParam(request.url.raw, "cid", &cid_buf)) |expected_cid| {
        if (!std.mem.eql(u8, record.cid, expected_cid)) {
            return recordNotFound(request, allocator, account.did, collection, rkey);
        }
    }
    const body = try store.writeRecordJson(allocator, record);
    return http_api.json(request, .ok, body);
}

// The reference PDS answers a missing record with 400, not 404, and clients
// such as Germ's sign-in treat only that shape as "no record yet".
fn recordNotFound(request: *http_api.Request, allocator: std.mem.Allocator, did: []const u8, collection: []const u8, rkey: []const u8) !void {
    const message = try std.fmt.allocPrint(allocator, "Could not locate record: at://{s}/{s}/{s}", .{ did, collection, rkey });
    return http_api.xrpcError(request, .bad_request, "RecordNotFound", message);
}

// The reference PDS forwards getRecord for a repo it does not host to the
// AppView, which answers an unknown repo this way.
fn repoNotHosted(request: *http_api.Request, allocator: std.mem.Allocator, repo: []const u8) !void {
    const message = try std.fmt.allocPrint(allocator, "Could not find repo: {s}", .{repo});
    return http_api.xrpcError(request, .bad_request, "InvalidRequest", message);
}

pub fn listRecords(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    const account = store.resolveRepo(allocator, repo) orelse {
        return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found");
    };
    try requirePublicRepoAvailable(request, account.did);
    var collection_buf: [256]u8 = undefined;
    const collection = http_api.queryParam(request.url.raw, "collection", &collection_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
    };
    var cursor_buf: [512]u8 = undefined;
    const cursor = http_api.queryParam(request.url.raw, "cursor", &cursor_buf);
    const reverse = queryBool(request.url.raw, "reverse", false);
    const body = try store.writeListJson(allocator, account.did, collection, cursor, reverse, @min(http_api.queryLimit(request.url.raw, 50), 100));
    return http_api.json(request, .ok, body);
}

pub fn deleteRecord(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireAccount(request, allocator) catch return;
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown_and_deactivation);
    const body = http_api.readBodyAlloc(request, allocator, max_repo_write_body_len) catch |err| switch (err) {
        error.BodyTooLarge => return http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "record write body is too large"),
        else => return err,
    };
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    try requireRepoMatches(request, account, parsed.value);
    const options = parseWriteOptions(request, parsed.value) catch return;
    const swap = parseRecordSwap(request, parsed.value) catch return;
    const collection = zat.json.getString(parsed.value, "collection") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
    };
    try requireRepoScope(request, auth_ctx.oauth_scope, .delete, collection);
    const rkey = zat.json.getString(parsed.value, "rkey") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey");
    };
    _ = store.applyWritesWithOptions(allocator, account, &.{.{ .delete = .{
        .collection = collection,
        .rkey = rkey,
        .swap = swap,
    } }}, options) catch |err| switch (err) {
        error.InvalidCollection => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid collection"),
        error.InvalidRecordKey => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid rkey"),
        error.InvalidSwap => return http_api.xrpcError(request, .bad_request, "InvalidSwap", "swapCommit or swapRecord did not match current repo state"),
        // deleting a record that is not there changes nothing; like the
        // reference PDS, answer success and write no commit
        error.RecordNotFound => return http_api.json(request, .ok, "{}"),
        else => return err,
    };
    sync.notifyCrawlers(false);
    return http_api.json(request, .ok, "{}");
}

pub fn applyWrites(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireAccount(request, allocator) catch return;
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown_and_deactivation);
    const body = http_api.readBodyAlloc(request, allocator, max_apply_writes_body_len) catch |err| switch (err) {
        error.BodyTooLarge => return http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "applyWrites body is too large"),
        else => return err,
    };
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    try requireRepoMatches(request, account, parsed.value);
    var options = parseWriteOptions(request, parsed.value) catch return;
    var missing_blob: ?[]const u8 = null;
    options.missing_blob = &missing_blob;
    const writes = switch (parsed.value) {
        .object => |object| object.get("writes") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing writes"),
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected object"),
    };
    if (writes != .array) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "writes must be an array");
    if (writes.array.items.len > store.max_commit_ops) return http_api.xrpcError(request, .bad_request, "InvalidRequest", too_many_writes_message);

    var staged: std.ArrayList(store.WriteOp) = .empty;
    for (writes.array.items, 0..) |write, idx| {
        if (write != .object) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid write");
        const type_name = http_api.valueString(write, "$type") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing write $type");
        };
        const collection = http_api.valueString(write, "collection") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
        };
        _ = idx;

        if (std.mem.eql(u8, type_name, "com.atproto.repo.applyWrites#create")) {
            try requireRepoScope(request, auth_ctx.oauth_scope, .create, collection);
            const record_value = write.object.get("value") orelse {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing value");
            };
            try staged.append(allocator, .{ .create = .{
                .collection = collection,
                .rkey = http_api.valueString(write, "rkey"),
                .value = try withRecordType(allocator, collection, record_value),
            } });
        } else if (std.mem.eql(u8, type_name, "com.atproto.repo.applyWrites#update")) {
            try requireRepoScope(request, auth_ctx.oauth_scope, .update, collection);
            const rkey = http_api.valueString(write, "rkey") orelse {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey");
            };
            const record_value = write.object.get("value") orelse {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing value");
            };
            try staged.append(allocator, .{ .update = .{
                .collection = collection,
                .rkey = rkey,
                .value = try withRecordType(allocator, collection, record_value),
                .swap = parseRecordSwap(request, write) catch return,
            } });
        } else if (std.mem.eql(u8, type_name, "com.atproto.repo.applyWrites#delete")) {
            try requireRepoScope(request, auth_ctx.oauth_scope, .delete, collection);
            const rkey = http_api.valueString(write, "rkey") orelse {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey");
            };
            try staged.append(allocator, .{ .delete = .{
                .collection = collection,
                .rkey = rkey,
                .swap = parseRecordSwap(request, write) catch return,
            } });
        } else {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Unknown write operation type");
        }
    }
    const result = store.applyWritesWithOptions(allocator, account, staged.items, options) catch |err| switch (err) {
        error.InvalidCollection => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid collection"),
        error.InvalidRecordKey => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid rkey"),
        error.RecordTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record exceeds 1000000 encoded bytes"),
        error.TooManyWrites => return http_api.xrpcError(request, .bad_request, "InvalidRequest", too_many_writes_message),
        error.CommitTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", commit_too_large_message),
        error.BlobNotFound => return blobNotFound(request, allocator, missing_blob),
        error.InvalidRecordType => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid record type"),
        error.InvalidSwap => return http_api.xrpcError(request, .bad_request, "InvalidSwap", "swapCommit or swapRecord did not match current repo state"),
        error.RecordAlreadyExists => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Record already exists"),
        error.ValidationRequired => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Record type is not known to this PDS"),
        error.InvalidDagCbor => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record is outside the atproto data model"),
        error.RecordNotFound => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Could not find a record to delete"),
        else => return err,
    };

    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeByte('[');
    var record_idx: usize = 0;
    for (staged.items, 0..) |op, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        switch (op) {
            .create => {
                const record = result.records[record_idx];
                record_idx += 1;
                const uri = try record.uri(allocator);
                try out.writer.print(
                    "{{\"$type\":\"com.atproto.repo.applyWrites#createResult\",\"uri\":{f},\"cid\":{f},\"validationStatus\":{f}}}",
                    .{ std.json.fmt(uri, .{}), std.json.fmt(record.cid, .{}), std.json.fmt(record.validation_status, .{}) },
                );
            },
            .update => {
                const record = result.records[record_idx];
                record_idx += 1;
                const uri = try record.uri(allocator);
                try out.writer.print(
                    "{{\"$type\":\"com.atproto.repo.applyWrites#updateResult\",\"uri\":{f},\"cid\":{f},\"validationStatus\":{f}}}",
                    .{ std.json.fmt(uri, .{}), std.json.fmt(record.cid, .{}), std.json.fmt(record.validation_status, .{}) },
                );
            },
            .delete => try out.writer.writeAll("{\"$type\":\"com.atproto.repo.applyWrites#deleteResult\"}"),
        }
    }
    try out.writer.writeByte(']');
    const body_out = try std.fmt.allocPrint(
        allocator,
        "{{\"commit\":{{\"cid\":{f},\"rev\":{f}}},\"results\":{s}}}",
        .{ std.json.fmt(result.commit.cid, .{}), std.json.fmt(result.commit.rev, .{}), out.written() },
    );
    sync.notifyCrawlers(false);
    return http_api.json(request, .ok, body_out);
}

pub fn importRepo(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireAccount(request, allocator) catch return;
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown);
    const body = http_api.readBodyAlloc(request, allocator, 128 * 1024 * 1024) catch |err| switch (err) {
        error.BodyTooLarge => return http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "repo CAR is too large"),
        else => return err,
    };

    const loaded = zat.loadCommitFromCARWithOptions(allocator, body, .{ .max_size = body.len, .max_blocks = body.len }) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "invalid repo CAR");
    };
    if (!std.mem.eql(u8, loaded.commit.did, account.did)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "repo DID does not match session");
    }
    try verifyImportedRepoCar(request, allocator, account.did, body);

    var tree = zat.mst.Mst.loadFromBlocks(allocator, loaded.repo_car, loaded.commit.data_cid) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "repo CAR is missing MST blocks");
    };

    var imported_records: std.ArrayList(store.ImportedRecord) = .empty;
    collectImportedRecords(allocator, loaded.repo_car, &tree, &imported_records) catch |err| switch (err) {
        error.RecordTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record exceeds 1000000 encoded bytes"),
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "repo CAR contains records outside the atproto data model"),
    };

    var imported_blocks: std.ArrayList(store.ImportedBlock) = .empty;
    for (loaded.repo_car.blocks) |block| {
        try imported_blocks.append(allocator, .{
            .cid = try zat.cbor.Cid.toString(.{ .raw = block.cid_raw }, allocator),
            .data = block.data,
        });
    }

    try store.importRepo(
        allocator,
        account,
        try zat.cbor.Cid.toString(.{ .raw = loaded.commit_cid }, allocator),
        loaded.commit.rev,
        imported_records.items,
        imported_blocks.items,
    );
    if (store.isAccountActive(account.did)) sync.notifyCrawlers(true);
    return http_api.json(request, .ok, "{}");
}

fn verifyImportedRepoCar(request: *http_api.Request, allocator: std.mem.Allocator, did: []const u8, body: []const u8) !void {
    var resolver = service_auth.didResolver(allocator);
    defer resolver.deinit();
    var doc = resolver.resolve(zat.Did.parse(did).?) catch {
        return http_api.xrpcError(request, .bad_gateway, "DidResolutionFailed", "could not resolve repo did");
    };
    defer doc.deinit();
    const signing_key = doc.signingKey() orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "DID document is missing atproto signing key");
    };
    const key_bytes = zat.multibase.decode(allocator, signing_key.public_key_multibase) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "DID document has invalid signing key");
    };
    const public_key = zat.multicodec.parsePublicKey(key_bytes) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "DID document has invalid signing key");
    };
    _ = zat.verifyCommitCar(allocator, body, public_key, .{
        .expected_did = did,
        .max_car_size = body.len,
        .max_blocks = body.len,
        .require_complete_repo = true,
    }) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "repo CAR verification failed");
    };
}

pub fn uploadBlob(io: std.Io, request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireBlobUploadAuth(request, allocator) catch return;
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown);
    const max_size = config.blobUploadLimit();
    if (request.body_len > max_size) {
        return http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "blob is too large");
    }
    var body_reader = try request.reader(30_000);
    const blob_mime = @import("../internal/blob_mime.zig");
    var prefix: [blob_mime.sniff_bytes]u8 = undefined;
    body_reader.interface.buffer = &prefix;
    const bytes = try body_reader.interface.peek(@min(request.body_len, prefix.len));
    const mime_type = blob_mime.detect(bytes, http_api.headerValue(request, "content-type") orelse "application/octet-stream");
    if (auth_ctx.oauth_scope) |scope| {
        try requireBlobScope(request, scope, mime_type);
    }
    const blob = store.putBlobReader(allocator, io, account, &body_reader.interface, request.body_len, max_size, mime_type) catch |err| switch (err) {
        error.BlobTooLarge => return http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "blob is too large"),
        error.BlobTakendown => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Blob has been takendown, cannot re-upload"),
        else => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", @errorName(err)),
    };
    const body_out = try uploadBlobResponseJson(allocator, blob.cid, mime_type, blob.size);
    return http_api.json(request, .ok, body_out);
}

const BlobUploadAuth = struct {
    account: auth.Account,
    oauth_scope: ?[]const u8,
};

fn requireBlobUploadAuth(request: *http_api.Request, allocator: std.mem.Allocator) !BlobUploadAuth {
    if (http_api.requireBearerAccess(request, allocator)) |ctx| {
        return .{ .account = ctx.account, .oauth_scope = ctx.oauth_scope };
    } else |err| switch (err) {
        error.AuthRequired, error.ExpiredToken, error.BadTokenScope, error.UseDpopNonce => {
            try http_api.bearerErrorResponse(request, err);
            return error.HandledResponse;
        },
        error.InvalidToken => return requireBlobUploadServiceAuth(request, allocator),
    }
}

fn requireBlobUploadServiceAuth(request: *http_api.Request, allocator: std.mem.Allocator) !BlobUploadAuth {
    const raw_header = http_api.headerValue(request, "authorization") orelse {
        try http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Authentication required");
        return error.HandledResponse;
    };
    if (!std.ascii.startsWithIgnoreCase(raw_header, "bearer ")) {
        try http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Authentication required");
        return error.HandledResponse;
    }
    const token = std.mem.trim(u8, raw_header["bearer ".len..], " \t");
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const pds_service = try std.fmt.allocPrint(arena.allocator(), "{s}#atproto_pds", .{config.serverDid()});
    const verified = zat.service_auth.verify(arena.allocator(), token, .{
        .now = clock.nowSeconds(),
        .audiences = &.{ config.serverDid(), pds_service },
        .lxm = "com.atproto.repo.uploadBlob",
    }, service_auth.KeyResolver{ .local_only = true }) catch |err| {
        switch (err) {
            error.OutOfMemory => return err,
            error.BadJwt, error.BadJwtType, error.JwtExpired, error.BadJwtAudience, error.BadJwtLexiconMethod, error.BadJwtIss, error.BadJwtSignature, error.UnknownIssuer => try http_api.xrpcError(request, .unauthorized, "InvalidToken", "Invalid token"),
            else => try http_api.xrpcError(request, .bad_gateway, "DidResolutionFailed", "could not resolve jwt issuer did"),
        }
        return error.HandledResponse;
    };
    const account = (store.findAccount(allocator, verified.issuer_did) catch null) orelse {
        try http_api.xrpcError(request, .unauthorized, "InvalidToken", "Invalid token");
        return error.HandledResponse;
    };
    return .{ .account = account, .oauth_scope = null };
}

fn uploadBlobResponseJson(
    allocator: std.mem.Allocator,
    cid: []const u8,
    mime_type: []const u8,
    size: usize,
) ![]const u8 {
    const Link = struct {
        @"$link": []const u8,
    };
    const Blob = struct {
        @"$type": []const u8,
        ref: Link,
        mimeType: []const u8,
        size: usize,
    };
    const Response = struct {
        blob: Blob,
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try std.json.Stringify.value(Response{
        .blob = .{
            .@"$type" = "blob",
            .ref = .{ .@"$link" = cid },
            .mimeType = mime_type,
            .size = size,
        },
    }, .{}, &out.writer);
    return out.toOwnedSlice();
}

pub fn listMissingBlobs(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireAccount(request, allocator) catch return;
    const account = auth_ctx.account;
    var cursor_buf: [256]u8 = undefined;
    const body = try store.writeMissingBlobsJson(
        allocator,
        account.did,
        http_api.queryParam(request.url.raw, "cursor", &cursor_buf),
        @min(http_api.queryLimit(request.url.raw, 500), 1000),
    );
    return http_api.json(request, .ok, body);
}

fn requireAccount(request: *http_api.Request, allocator: std.mem.Allocator) !http_api.BearerAccount {
    return http_api.requireBearerAccess(request, allocator) catch |err| {
        try http_api.bearerErrorResponse(request, err);
        return error.HandledResponse;
    };
}

fn requirePublicRepoAvailable(request: *http_api.Request, did: []const u8) !void {
    const status = store.accountStatus(did) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
        else => return err,
    };
    if (status.isActive()) return;
    return accountStatusError(request, status);
}

fn accountStatusError(request: *http_api.Request, status: store.AccountStatus) !void {
    return switch (status) {
        .active => {},
        .takendown => http_api.xrpcError(request, .bad_request, "RepoTakendown", "Repo has been taken down"),
        .suspended => http_api.xrpcError(request, .bad_request, "RepoSuspended", "Repo is suspended"),
        .deactivated => http_api.xrpcError(request, .bad_request, "RepoDeactivated", "Repo is deactivated"),
        .deleted => http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
    };
}

fn requireRepoScope(request: *http_api.Request, maybe_scope: ?[]const u8, action: scopes.RepoAction, collection: []const u8) !void {
    if (scopes.repoAllows(maybe_scope, action, collection)) return;
    return http_api.xrpcError(request, .forbidden, "InsufficientScope", "Insufficient scope");
}

fn requireBlobScope(request: *http_api.Request, maybe_scope: ?[]const u8, mime_type: []const u8) !void {
    if (scopes.blobAllows(maybe_scope, mime_type)) return;
    return http_api.xrpcError(request, .forbidden, "InsufficientScope", "Insufficient scope");
}

fn requireRepoMatches(request: *http_api.Request, account: auth.Account, value: std.json.Value) !void {
    const repo = zat.json.getString(value, "repo") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    if (std.mem.eql(u8, repo, account.did) or std.ascii.eqlIgnoreCase(repo, account.handle)) return;
    return http_api.xrpcError(request, .bad_request, "InvalidRepo", "Repo does not match authenticated user");
}

/// A record without `$type` is stored as the collection it is written to, as the
/// reference PDS does; a `$type` naming another collection is still refused.
fn withRecordType(allocator: std.mem.Allocator, collection: []const u8, value: std.json.Value) !std.json.Value {
    const object = switch (value) {
        .object => |object| object,
        else => return value,
    };
    if (object.contains("$type")) return value;
    var typed = try object.clone(allocator);
    try typed.put(allocator, "$type", .{ .string = collection });
    return .{ .object = typed };
}

test "a record without $type takes its collection" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const untyped = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"subject\":\"at://x\"}", .{});
    const typed = try withRecordType(a, "social.grain.favorite", untyped);
    try std.testing.expectEqualStrings("social.grain.favorite", typed.object.get("$type").?.string);
    try std.testing.expect(!untyped.object.contains("$type"));
    const other = try std.json.parseFromSliceLeaky(std.json.Value, a, "{\"$type\":\"app.bsky.feed.like\"}", .{});
    try std.testing.expectEqualStrings("app.bsky.feed.like", (try withRecordType(a, "social.grain.favorite", other)).object.get("$type").?.string);
}

fn recordBodyValue(value: std.json.Value) ?std.json.Value {
    return switch (value) {
        .object => |object| object.get("record"),
        else => null,
    };
}

/// the reference PDS's answer for a record naming a blob the account does not
/// have (actor-store/blob/transactor.ts)
fn blobNotFound(request: *http_api.Request, allocator: std.mem.Allocator, cid: ?[]const u8) !void {
    const message = try std.fmt.allocPrint(allocator, "Could not find blob: {s}", .{cid orelse ""});
    return http_api.xrpcError(request, .bad_request, "BlobNotFound", message);
}

fn parseWriteOptions(request: *http_api.Request, value: std.json.Value) !store.WriteOptions {
    const object = switch (value) {
        .object => |object| object,
        else => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected object");
            return error.HandledResponse;
        },
    };

    var options: store.WriteOptions = .{};
    if (object.get("validate")) |validate| {
        options.validate = switch (validate) {
            .bool => |enabled| if (enabled) .require else .skip,
            else => {
                try http_api.xrpcError(request, .bad_request, "InvalidRequest", "validate must be a boolean");
                return error.HandledResponse;
            },
        };
    }
    if (object.get("swapCommit")) |swap_commit| {
        options.swap_commit = switch (swap_commit) {
            .string => |cid| cid,
            else => {
                try http_api.xrpcError(request, .bad_request, "InvalidRequest", "swapCommit must be a CID string");
                return error.HandledResponse;
            },
        };
    }
    return options;
}

fn parseRecordSwap(request: *http_api.Request, value: std.json.Value) !store.RecordSwap {
    const object = switch (value) {
        .object => |object| object,
        else => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected object");
            return error.HandledResponse;
        },
    };
    const swap_record = object.get("swapRecord") orelse return .none;
    return switch (swap_record) {
        .null => .missing,
        .string => |cid| .{ .cid = cid },
        else => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "swapRecord must be a CID string or null");
            return error.HandledResponse;
        },
    };
}

fn queryBool(target: []const u8, name: []const u8, default: bool) bool {
    var buf: [16]u8 = undefined;
    const raw = http_api.queryParam(target, name, &buf) orelse return default;
    if (std.ascii.eqlIgnoreCase(raw, "true") or std.mem.eql(u8, raw, "1")) return true;
    if (std.ascii.eqlIgnoreCase(raw, "false") or std.mem.eql(u8, raw, "0")) return false;
    return default;
}

fn writeRecordRef(request: *http_api.Request, allocator: std.mem.Allocator, record: store.Record, commit: store.CommitInfo) !void {
    const uri = try record.uri(allocator);
    const body_out = try std.fmt.allocPrint(
        allocator,
        "{{\"uri\":{f},\"cid\":{f},\"commit\":{{\"cid\":{f},\"rev\":{f}}},\"validationStatus\":{f}}}",
        .{ std.json.fmt(uri, .{}), std.json.fmt(record.cid, .{}), std.json.fmt(commit.cid, .{}), std.json.fmt(commit.rev, .{}), std.json.fmt(record.validation_status, .{}) },
    );
    return http_api.json(request, .ok, body_out);
}

fn collectImportedRecords(
    allocator: std.mem.Allocator,
    repo_car: zat.car.Car,
    tree: *zat.mst.Mst,
    out: *std.ArrayList(store.ImportedRecord),
) anyerror!void {
    var ctx = ImportRecordWalkContext{
        .allocator = allocator,
        .repo_car = repo_car,
        .out = out,
    };
    try tree.walk(ctx.walker());
}

const ImportRecordWalkContext = struct {
    allocator: std.mem.Allocator,
    repo_car: zat.car.Car,
    out: *std.ArrayList(store.ImportedRecord),

    fn walker(self: *ImportRecordWalkContext) zat.mst.Walker {
        return .{
            .ctx = self,
            .entryFn = onEntry,
        };
    }

    fn onEntry(ctx: *anyopaque, entry: zat.mst.WalkEntry) anyerror!void {
        const self: *ImportRecordWalkContext = @ptrCast(@alignCast(ctx));
        const block = zat.car.findBlock(self.repo_car, entry.value.raw) orelse return error.MissingRecordBlock;
        if (block.len > store.max_record_bytes) return error.RecordTooLarge;
        const record_value = try zat.cbor.decodeAll(self.allocator, block);
        const slash = std.mem.indexOfScalar(u8, entry.key, '/') orelse return error.InvalidRepoPath;
        try self.out.append(self.allocator, .{
            .collection = try self.allocator.dupe(u8, entry.key[0..slash]),
            .rkey = try self.allocator.dupe(u8, entry.key[slash + 1 ..]),
            .cid = try zat.cbor.Cid.toString(.{ .raw = entry.value.raw }, self.allocator),
            .blob_cids = try store.blobCidTexts(self.allocator, record_value),
        });
    }
};

test "repo import checks referenced record sizes without limiting unrelated blocks" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    for ([_]usize{ 999_999, 1_000_000, 1_000_001 }) |size| {
        const text = try allocator.alloc(u8, size - 11);
        @memset(text, 'x');
        const entries = [_]zat.cbor.Value.MapEntry{.{ .key = "text", .value = .{ .text = text } }};
        const bytes = try zat.cbor.encodeAlloc(allocator, .{ .map = &entries });
        try std.testing.expectEqual(size, bytes.len);
        const cid = try zat.cbor.Cid.forDagCbor(allocator, bytes);
        var tree = zat.mst.Mst.init(allocator);
        _ = try tree.putReturn("dev.zat.sizeprobe/record", cid);
        const extra = try allocator.alloc(u8, 1_000_001);
        @memset(extra, 0);
        const extra_cid = try zat.cbor.Cid.forDagCbor(allocator, extra);
        const blocks = [_]zat.car.Block{
            .{ .cid_raw = cid.raw, .data = bytes },
            .{ .cid_raw = extra_cid.raw, .data = extra },
        };
        var records: std.ArrayList(store.ImportedRecord) = .empty;
        const result = collectImportedRecords(allocator, .{ .roots = &.{}, .blocks = &blocks }, &tree, &records);
        if (size > 1_000_000) {
            try std.testing.expectError(error.RecordTooLarge, result);
            try std.testing.expectEqual(@as(usize, 0), records.items.len);
        } else {
            try result;
            try std.testing.expectEqual(@as(usize, 1), records.items.len);
        }
    }
}