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

zat.dev/zds

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

0
0
572 lines · 27.4 KB Raw History
const std = @import("std");
const auth = @import("../auth/tokens.zig");
const config = @import("../core/config.zig");
const log = @import("../core/log.zig");
const mail = @import("../core/mail.zig");
const http_api = @import("../http/api.zig");
const email_tokens = @import("../internal/email_tokens.zig");
const handles = @import("../internal/handles.zig");
const scopes = @import("../internal/scopes.zig");
const plc = @import("plc.zig");
const service_auth = @import("../internal/service_auth.zig");
const store = @import("../storage/store.zig");
const zat = @import("zat");

const http = std.http;

pub fn getRecommendedDidCredentials(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 keypair = try store.signingKeypair(account.did);
    const keys: plc.VerificationKeys = .{
        .atproto = try keypair.did(allocator),
        .atproto_kem = try store.kemDidKey(allocator, account.did),
    };
    const rotation_keys_json = if (std.mem.startsWith(u8, account.did, "did:web:"))
        "[]"
    else keys: {
        var rotation_keypair = plc.configuredRotationKeypair() catch |err| switch (err) {
            error.MissingPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is not configured"),
            error.InvalidPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is invalid"),
        };
        const rotation_keys = try plc.rotationDidKeys(allocator, &rotation_keypair);
        break :keys try jsonStringArray(allocator, rotation_keys);
    };
    const body = try std.fmt.allocPrint(
        allocator,
        "{{\"alsoKnownAs\":[\"at://{s}\"],\"verificationMethods\":{f},\"rotationKeys\":{s},\"services\":{{\"atproto_pds\":{{\"type\":\"AtprotoPersonalDataServer\",\"endpoint\":{f}}}}}}}",
        .{
            account.handle,
            keys,
            rotation_keys_json,
            std.json.fmt(config.publicUrl(), .{}),
        },
    );
    return http_api.json(request, .ok, body);
}

pub fn requestPlcOperationSignature(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 = requireMigratingAccount(request, allocator) catch return;
    try requireIdentityScope(request, auth_ctx.oauth_scope, .wildcard);
    const account = auth_ctx.account;
    const info = store.getEmailInfo(allocator, account.did) orelse {
        return http_api.xrpcError(request, .not_found, "AccountNotFound", "Account not found");
    };
    var code_buf: [11]u8 = undefined;
    const code = email_tokens.makeCode(&code_buf);
    try store.setEmailToken(account.did, .plc_operation, code, store.nowMs() + (10 * 60 * 1000));
    try mail.sendCode(store.currentIo(), allocator, info.email, account.handle, "PLC operation", "PLC operation", code);
    return http_api.json(request, .ok, "{}");
}

pub fn signPlcOperation(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 = requireMigratingAccount(request, allocator) catch return;
    try requireIdentityScope(request, auth_ctx.oauth_scope, .wildcard);
    const account = auth_ctx.account;
    const body = try http_api.readBodyAlloc(request, allocator, 1024 * 1024);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const input = switch (parsed.value) {
        .object => |object| object,
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected object"),
    };
    const token = switch (input.get("token") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "email confirmation token required to sign PLC operations")) {
        .string => |string| string,
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "email confirmation token required to sign PLC operations"),
    };
    switch (store.validateEmailToken(account.did, .plc_operation, token, store.nowMs())) {
        .valid => {},
        .expired => return http_api.xrpcError(request, .bad_request, "ExpiredToken", "token expired"),
        .invalid => return http_api.xrpcError(request, .bad_request, "InvalidToken", "invalid token"),
    }

    const last_op = fetchLastPlcOp(allocator, account.did) catch {
        return http_api.xrpcError(request, .bad_gateway, "PlcFetchFailed", "failed to fetch current PLC operation");
    };
    if (jsonObjectStringEquals(last_op, "type", "plc_tombstone")) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "DID is tombstoned");
    }

    const prev = try zat.plc.cidForJson(allocator, last_op);
    const unsigned_json = try writeUnsignedPlcOperationJson(allocator, last_op, input, prev);
    var signing_keypair = try plcOperationSigningKeypair(request, allocator, account, last_op);
    const operation = try zat.plc.signJson(allocator, unsigned_json, &signing_keypair);
    try store.clearEmailToken(account.did, .plc_operation);
    return http_api.json(request, .ok, try std.fmt.allocPrint(allocator, "{{\"operation\":{s}}}", .{operation}));
}

pub fn submitPlcOperation(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;
    try requireIdentityScope(request, auth_ctx.oauth_scope, .wildcard);
    const account = auth_ctx.account;
    const body = try http_api.readBodyAlloc(request, allocator, 1024 * 1024);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const operation = switch (parsed.value) {
        .object => |object| object.get("operation") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing operation");
        },
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected object"),
    };
    try validatePlcOperation(request, allocator, account, operation);

    const op_json = try stringifyJson(allocator, operation);
    const submission: plc.Submission = if (zat.json.getString(operation, "prev") != null) .update else .genesis;
    plc.submitOperation(allocator, account.did, op_json, submission) catch |err| {
        const message = if (err == error.PlcSubmissionRejected)
            "PLC directory rejected operation"
        else
            "failed to submit PLC operation";
        return http_api.xrpcError(request, .bad_gateway, "PlcSubmissionFailed", message);
    };
    return http_api.json(request, .ok, "{}");
}

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

    var handle_buf: [256]u8 = undefined;
    const handle_param = http_api.queryParam(request.url.raw, "handle", &handle_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing handle");
    };
    const handle = handles.normalize(allocator, handle_param) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidHandle", "Invalid handle format");
    };

    const did = if (try store.findActiveAccount(allocator, handle)) |account|
        account.did
    else if (handles.isHostedAuthority(handle, config.handleDomains()))
        return http_api.xrpcError(request, .not_found, "HandleNotFound", "Unable to resolve handle")
    else did: {
        const parsed_handle = zat.Handle.parse(handle) orelse unreachable;
        var resolver = zat.HandleResolver.init(store.currentIo(), allocator);
        defer resolver.deinit();
        break :did resolver.resolve(parsed_handle) catch {
            return http_api.xrpcError(request, .not_found, "HandleNotFound", "Unable to resolve handle");
        };
    };

    const body = try std.fmt.allocPrint(allocator, "{{\"did\":{f}}}", .{std.json.fmt(did, .{})});
    return http_api.json(request, .ok, body);
}

pub fn updateHandle(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;
    try requireIdentityScope(request, auth_ctx.oauth_scope, .handle);
    const account = auth_ctx.account;
    try http_api.requireActiveAccount(request, account.did, .takedown);
    const now = store.nowMs();
    store.consumeRateLimit(account.did, "identity.updateHandle.5m", now, 5 * 60 * 1000, 10) catch |err| switch (err) {
        error.RateLimitExceeded => return http_api.xrpcError(request, .too_many_requests, "RateLimitExceeded", "Too many handle updates"),
        else => return err,
    };
    store.consumeRateLimit(account.did, "identity.updateHandle.day", now, 24 * 60 * 60 * 1000, 50) catch |err| switch (err) {
        error.RateLimitExceeded => return http_api.xrpcError(request, .too_many_requests, "RateLimitExceeded", "Too many handle updates"),
        else => return err,
    };

    const body = try http_api.readBodyAlloc(request, allocator, 16 * 1024);
    const parsed = try http_api.parseJsonBody(request, allocator, body);
    const raw_handle = zat.json.getString(parsed.value, "handle") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing handle");
    };
    const handle = handles.normalize(allocator, raw_handle) catch {
        return http_api.xrpcError(request, .bad_request, "InvalidHandle", "Invalid handle");
    };

    if (handles.isHosted(handle, config.handleDomains())) {
        handles.validateHosted(handle, config.handleDomains()) catch |err| switch (err) {
            error.InvalidHostedHandle => return http_api.xrpcError(request, .bad_request, "InvalidHandle", "Invalid hosted handle"),
            else => return http_api.xrpcError(request, .bad_request, "UnsupportedDomain", "Unsupported handle domain"),
        };
    }

    if (std.ascii.eqlIgnoreCase(handle, account.handle)) {
        store.sequenceIdentityEvent(allocator, account.did, handle) catch |err| {
            log.err("failed to resequence identity event did={s} handle={s} error={s}\n", .{ account.did, handle, @errorName(err) });
        };
        return http_api.json(request, .ok, "{}");
    }

    if (!handles.isHosted(handle, config.handleDomains())) {
        const parsed_handle = zat.Handle.parse(handle) orelse unreachable;
        var resolver = zat.HandleResolver.init(store.currentIo(), allocator);
        defer resolver.deinit();
        const resolved_did = resolver.resolve(parsed_handle) catch {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "External handle did not resolve to account DID");
        };
        if (!std.mem.eql(u8, resolved_did, account.did)) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "External handle did not resolve to account DID");
        }
        if (std.mem.startsWith(u8, account.did, "did:web:")) {
            var did_resolver = service_auth.didResolver(allocator);
            defer did_resolver.deinit();
            var did_doc = did_resolver.resolve(zat.Did.parse(account.did).?) catch {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account DID did not resolve");
            };
            defer did_doc.deinit();
            const did_handle = did_doc.handle() orelse {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account DID does not declare the requested handle");
            };
            if (!std.ascii.eqlIgnoreCase(did_handle, handle)) {
                return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account DID does not declare the requested handle");
            }
        }
    }

    if (try store.findAccount(allocator, handle)) |existing| {
        if (!std.mem.eql(u8, existing.did, account.did)) {
            return http_api.xrpcError(request, .bad_request, "HandleNotAvailable", "Handle is already in use");
        }
    }

    if (std.mem.startsWith(u8, account.did, "did:plc:")) {
        const last_op = plc.fetchLastOperation(allocator, account.did) catch {
            return http_api.xrpcError(request, .bad_gateway, "PlcUpdateFailed", "Failed to fetch current PLC operation");
        };
        if (jsonObjectStringEquals(last_op, "type", "plc_tombstone")) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "DID is tombstoned");
        }

        var rotation_keypair = plc.configuredRotationKeypair() catch {
            return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is not configured");
        };
        const rotation_did_key = try rotation_keypair.did(allocator);
        if (!jsonArrayContainsString(zat.json.getPath(last_op, "rotationKeys"), rotation_did_key)) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "PDS rotation key is not authorized by current PLC operation");
        }

        const prev = try plc.cidForJsonValue(allocator, last_op);
        const unsigned = try plc.updateHandleOperationJson(allocator, last_op, handle, prev);
        const operation = try plc.signOperationJson(allocator, unsigned, &rotation_keypair);
        plc.submitOperation(allocator, account.did, operation, .update) catch {
            return http_api.xrpcError(request, .bad_gateway, "PlcUpdateFailed", "Failed to update PLC handle");
        };
    }

    store.updateAccountHandle(account.did, handle) catch |err| switch (err) {
        error.HandleNotAvailable => return http_api.xrpcError(request, .bad_request, "HandleNotAvailable", "Handle is already in use"),
        error.AccountNotFound => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Account not found"),
        else => return err,
    };
    store.sequenceIdentityEvent(allocator, account.did, handle) catch |err| {
        log.err("failed to sequence identity event did={s} handle={s} error={s}\n", .{ account.did, handle, @errorName(err) });
    };
    return http_api.json(request, .ok, "{}");
}

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;
    };
}

/// Signing a PLC operation is how a taken-down account points its identity at a
/// new host, so these routes also take the takendown session.
fn requireMigratingAccount(request: *http_api.Request, allocator: std.mem.Allocator) !http_api.BearerAccount {
    return http_api.requireBearerAccessOrTakendown(request, allocator) catch |err| {
        try http_api.bearerErrorResponse(request, err);
        return error.HandledResponse;
    };
}

fn requireIdentityScope(request: *http_api.Request, maybe_scope: ?[]const u8, attr: scopes.IdentityAttr) !void {
    if (scopes.identityAllows(maybe_scope, attr)) return;
    try http_api.xrpcError(request, .forbidden, "InsufficientScope", "Insufficient scope");
    return error.HandledResponse;
}

fn plcOperationSigningKeypair(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    _: auth.Account,
    last_op: std.json.Value,
) !zat.Keypair {
    var rotation_keypair = plc.configuredRotationKeypair() catch |err| switch (err) {
        error.MissingPlcRotationKey => {
            try http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is not configured");
            return error.HandledResponse;
        },
        error.InvalidPlcRotationKey => {
            try http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is invalid");
            return error.HandledResponse;
        },
    };
    const rotation_did_key = try rotation_keypair.did(allocator);
    if (jsonArrayContainsString(zat.json.getPath(last_op, "rotationKeys"), rotation_did_key)) {
        return rotation_keypair;
    }
    try http_api.xrpcError(request, .bad_request, "InvalidRequest", "PDS rotation key is not authorized by current PLC rotation keys");
    return error.HandledResponse;
}

fn validatePlcOperation(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    account: auth.Account,
    operation: std.json.Value,
) !void {
    var keypair = try store.signingKeypair(account.did);
    const did_key = try keypair.did(allocator);
    const rotation_did_key = if (std.mem.startsWith(u8, account.did, "did:plc:")) key: {
        var rotation_keypair = plc.configuredRotationKeypair() catch |err| switch (err) {
            error.MissingPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is not configured"),
            error.InvalidPlcRotationKey => return http_api.xrpcError(request, .internal_server_error, "InternalServerError", "PLC rotation key is invalid"),
        };
        break :key try rotation_keypair.did(allocator);
    } else did_key;
    const object = switch (operation) {
        .object => |object| object,
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid operation"),
    };
    if (!jsonArrayContainsString(object.get("rotationKeys"), rotation_did_key)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Rotation keys do not include server rotation key");
    }
    if (jsonArrayContainsString(object.get("rotationKeys"), did_key)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Rotation keys must not include the account signing key");
    }
    const verification_methods = object.get("verificationMethods") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing verificationMethods");
    };
    if (!jsonObjectStringEquals(verification_methods, "atproto", did_key)) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Incorrect signing key");
    }
    if (try store.kemDidKey(allocator, account.did)) |kem_did_key| {
        if (!jsonObjectStringEquals(verification_methods, "atproto_kem", kem_did_key)) {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Incorrect KEM key");
        }
    }
    if (!jsonArrayFirstStringEquals(object.get("alsoKnownAs"), try std.fmt.allocPrint(allocator, "at://{s}", .{account.handle}))) {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Incorrect handle in alsoKnownAs");
    }
    const services = object.get("services") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing services");
    };
    const atproto_pds = switch (services) {
        .object => |services_object| services_object.get("atproto_pds") orelse {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing atproto_pds service");
        },
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid services"),
    };
    if (!jsonObjectStringEquals(atproto_pds, "type", "AtprotoPersonalDataServer") or
        !jsonObjectStringEquals(atproto_pds, "endpoint", config.publicUrl()))
    {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Incorrect atproto_pds service");
    }
}

fn jsonStringArray(allocator: std.mem.Allocator, items: []const []const u8) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeByte('[');
    for (items, 0..) |item, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try out.writer.print("{f}", .{std.json.fmt(item, .{})});
    }
    try out.writer.writeByte(']');
    return out.toOwnedSlice();
}

fn stringifyJson(allocator: std.mem.Allocator, value: std.json.Value) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.print("{f}", .{std.json.fmt(value, .{})});
    return out.toOwnedSlice();
}

fn fetchLastPlcOp(allocator: std.mem.Allocator, did: []const u8) !std.json.Value {
    const escaped_did = try zat.oauth.percentEncodeAlloc(allocator, did);
    var url_buf: [340]u8 = undefined;
    const url = try std.fmt.bufPrint(&url_buf, "{s}/{s}/log/last", .{ config.plcDirectory(), escaped_did });
    var transport = zat.HttpTransport.init(store.currentIo(), allocator);
    defer transport.deinit();
    const result = try transport.fetch(.{
        .url = url,
        .method = .GET,
        .accept = "application/json",
        .max_response_size = 1024 * 1024,
    });
    if (@backingInt(result.status) < 200 or @backingInt(result.status) >= 300) return error.PlcFetchFailed;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, result.body, .{});
    return parsed.value;
}

fn writeUnsignedPlcOperationJson(
    allocator: std.mem.Allocator,
    last_op: std.json.Value,
    input: std.json.ObjectMap,
    prev: []const u8,
) ![]const u8 {
    const last = switch (last_op) {
        .object => |object| object,
        else => return error.InvalidPlcOperation,
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"type\":\"plc_operation\"");
    try writePlcField(allocator, &out.writer, "verificationMethods", input, last);
    try writePlcField(allocator, &out.writer, "rotationKeys", input, last);
    try writePlcField(allocator, &out.writer, "alsoKnownAs", input, last);
    try writePlcField(allocator, &out.writer, "services", input, last);
    try out.writer.print(",\"prev\":{f}}}", .{std.json.fmt(prev, .{})});
    return out.toOwnedSlice();
}

fn writePlcField(
    allocator: std.mem.Allocator,
    writer: anytype,
    name: []const u8,
    input: std.json.ObjectMap,
    last: std.json.ObjectMap,
) !void {
    const value = input.get(name) orelse last.get(name) orelse return error.InvalidPlcOperation;
    try writer.print(",{f}:{s}", .{ std.json.fmt(name, .{}), try stringifyJson(allocator, value) });
}

/// Accounts created before KEM keys existed lack an `#atproto_kem` key, and their
/// space reads that need a MAC fail until they get one. So do accounts that
/// arrived with a caller-built PLC operation. This gives each one a key and
/// publishes it to the account's PLC document. An account whose document this
/// PDS cannot update still gets a key, and its owner must publish it. Mirrors
/// upstream's `kem-key-backfill.ts`, rescanning instead of finishing once.
pub fn startKemKeyBackfill() !void {
    const thread = try std.Thread.spawn(.{}, kemKeyBackfillWorker, .{});
    thread.detach();
}

const kem_backfill_rescan_seconds = 10 * 60;
const kem_backfill_max_retry_seconds = 60 * 60;

fn kemKeyBackfillWorker() void {
    var retry_seconds: i64 = 60;
    while (true) {
        const failed = backfillKemKeys() catch |err| blk: {
            log.err("kem key backfill failed error={s}\n", .{@errorName(err)});
            break :blk 1;
        };
        const wait_seconds: i64 = if (failed == 0) kem_backfill_rescan_seconds else retry_seconds;
        if (failed == 0) {
            retry_seconds = 60;
        } else {
            log.err("kem key backfill will retry failed={d} in_seconds={d}\n", .{ failed, retry_seconds });
            retry_seconds = @min(retry_seconds * 2, kem_backfill_max_retry_seconds);
        }
        store.currentIo().sleep(std.Io.Duration.fromSeconds(wait_seconds), .awake) catch {};
    }
}

// Returns the number of accounts that failed.
fn backfillKemKeys() !usize {
    var cursor_arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer cursor_arena.deinit();
    var cursor: ?[]const u8 = null;
    var done: usize = 0;
    var failed: usize = 0;
    while (true) {
        const dids = try store.listDidsWithoutKemKey(cursor_arena.allocator(), cursor, 100);
        if (dids.len == 0) break;
        for (dids) |did| {
            var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
            defer arena.deinit();
            backfillKemKey(arena.allocator(), did) catch |err| {
                failed += 1;
                log.err("kem key backfill failed did={s} error={s}\n", .{ did, @errorName(err) });
                continue;
            };
            done += 1;
        }
        cursor = dids[dids.len - 1];
    }
    if (done > 0 or failed > 0) log.info("kem key backfill pass done={d} failed={d}\n", .{ done, failed });
    return failed;
}

fn backfillKemKey(allocator: std.mem.Allocator, did: []const u8) !void {
    const kem_key = try store.generateKemSecretKey();
    const kem_keypair = try zat.Keypair.fromSecretKey(.p256, kem_key);
    const kem_did_key = try kem_keypair.did(allocator);
    const published = try publishKemKey(allocator, did, kem_did_key);
    if (!try store.setMissingKemSecretKey(did, kem_key)) return;
    if (!published) {
        log.info("kem key backfill cannot publish, account must update its did doc did={s}\n", .{did});
        return;
    }
    const account = (try store.findAccount(allocator, did)) orelse return;
    try store.sequenceIdentityEvent(allocator, did, account.handle);
}

// False when this PDS cannot update the account's PLC document.
fn publishKemKey(allocator: std.mem.Allocator, did: []const u8, kem_did_key: []const u8) !bool {
    if (!std.mem.startsWith(u8, did, "did:plc:")) return false;
    var rotation_keypair = plc.configuredRotationKeypair() catch return false;
    const last_op = plc.fetchLastOperation(allocator, did) catch |err| switch (err) {
        error.PlcDidNotFound => return false,
        else => return err,
    };
    if (!jsonObjectStringEquals(last_op, "type", "plc_operation")) return false;
    if (!jsonArrayContainsString(zat.json.getPath(last_op, "rotationKeys"), try rotation_keypair.did(allocator))) return false;
    // Migrated to another PDS
    const endpoint = zat.json.getString(last_op, "services.atproto_pds.endpoint") orelse return false;
    if (!std.mem.eql(u8, endpoint, config.publicUrl())) return false;

    const prev = try plc.cidForJsonValue(allocator, last_op);
    const unsigned = try plc.addKemKeyOperationJson(allocator, last_op, kem_did_key, prev);
    const operation = try plc.signOperationJson(allocator, unsigned, &rotation_keypair);
    try plc.submitOperation(allocator, did, operation, .update);
    return true;
}

fn jsonObjectStringEquals(value: std.json.Value, key: []const u8, expected: []const u8) bool {
    const actual = switch (value) {
        .object => |object| switch (object.get(key) orelse return false) {
            .string => |string| string,
            else => return false,
        },
        else => return false,
    };
    return std.mem.eql(u8, actual, expected);
}

fn jsonArrayContainsString(value: ?std.json.Value, expected: []const u8) bool {
    const items = switch (value orelse return false) {
        .array => |array| array.items,
        else => return false,
    };
    for (items) |item| switch (item) {
        .string => |string| if (std.mem.eql(u8, string, expected)) return true,
        else => {},
    };
    return false;
}

fn jsonArrayFirstStringEquals(value: ?std.json.Value, expected: []const u8) bool {
    const items = switch (value orelse return false) {
        .array => |array| array.items,
        else => return false,
    };
    if (items.len == 0) return false;
    return switch (items[0]) {
        .string => |string| std.mem.eql(u8, string, expected),
        else => false,
    };
}