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

zat.dev/zds

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

0
0
410 lines · 18.9 KB Raw History
const std = @import("std");
const config = @import("../core/config.zig");
const store = @import("../storage/store.zig");
const zat = @import("zat");

pub const Operation = struct {
    did: []const u8,
    json: []const u8,
};

pub fn configuredRotationKeypair() !zat.Keypair {
    const key = config.plcRotationKey() orelse return error.MissingPlcRotationKey;
    return parsePrivateKey(std.heap.smp_allocator, key) catch error.InvalidPlcRotationKey;
}

pub fn parsePrivateKey(allocator: std.mem.Allocator, key: []const u8) !zat.Keypair {
    if (key.len == 64 and isHex(key)) {
        return parseHexPrivateKey(key);
    }
    if (key.len >= 2 and key[0] == 'z') {
        return parsePrivateMultikey(allocator, key);
    }
    return error.InvalidPrivateKey;
}

fn parseHexPrivateKey(hex: []const u8) !zat.Keypair {
    var secret: [32]u8 = undefined;
    _ = std.fmt.hexToBytes(&secret, hex) catch return error.InvalidPrivateKey;
    return zat.Keypair.fromSecretKey(.secp256k1, secret) catch error.InvalidPrivateKey;
}

fn parsePrivateMultikey(allocator: std.mem.Allocator, key: []const u8) !zat.Keypair {
    return zat.Keypair.fromPrivateMultikey(allocator, key) catch error.InvalidPrivateKey;
}

fn isHex(input: []const u8) bool {
    for (input) |c| switch (c) {
        '0'...'9', 'a'...'f', 'A'...'F' => {},
        else => return false,
    };
    return true;
}

pub fn rotationDidKeys(allocator: std.mem.Allocator, rotation_key: *const zat.Keypair) ![]const []const u8 {
    const base_len: usize = if (config.recoveryDidKey() == null) 1 else 2;
    const keys = try allocator.alloc([]const u8, base_len);
    var idx: usize = 0;
    if (config.recoveryDidKey()) |recovery| {
        keys[idx] = recovery;
        idx += 1;
    }
    keys[idx] = try rotation_key.did(allocator);
    return keys;
}

pub fn createGenesisOperation(
    allocator: std.mem.Allocator,
    handle: []const u8,
    signing_key: *const zat.Keypair,
    kem_key: *const zat.Keypair,
    rotation_key: *const zat.Keypair,
) !Operation {
    const operation: zat.plc.Operation = .{
        .rotation_keys = try rotationDidKeys(allocator, rotation_key),
        .verification_methods = &.{
            .{ .id = "atproto", .key = try signing_key.did(allocator) },
            .{ .id = "atproto_kem", .key = try kem_key.did(allocator) },
        },
        .also_known_as = &.{try std.fmt.allocPrint(allocator, "at://{s}", .{handle})},
        .services = &.{.{ .id = "atproto_pds", .type = "AtprotoPersonalDataServer", .endpoint = config.publicUrl() }},
    };
    const signed = try operation.sign(allocator, rotation_key);
    return .{ .did = try allocator.dupe(u8, &signed.did()), .json = signed.json };
}

pub const Submission = enum { genesis, update };

pub fn submitOperation(allocator: std.mem.Allocator, did: []const u8, operation_json: []const u8, submission: Submission) !void {
    const escaped_did = try zat.oauth.percentEncodeAlloc(allocator, did);
    const url = try std.fmt.allocPrint(allocator, "{s}/{s}", .{ config.plcDirectory(), escaped_did });
    var transport = zat.HttpTransport.init(store.currentIo(), allocator);
    defer transport.deinit();
    const result = try transport.fetch(.{
        .url = url,
        .method = .POST,
        .payload = operation_json,
        .content_type = "application/json",
        .extra_headers = switch (submission) {
            .genesis => &.{},
            .update => &.{.{ .name = "If-Match", .value = "*" }},
        },
        .max_response_size = 64 * 1024,
    });
    if (@backingInt(result.status) < 200 or @backingInt(result.status) >= 300) {
        return error.PlcSubmissionRejected;
    }
}

/// Tombstones a did:plc with this PDS's rotation key. A did:web, a DID the
/// directory doesn't know, and one already tombstoned need nothing; a DID whose
/// rotation keys no longer include this PDS's key is refused.
pub fn tombstone(allocator: std.mem.Allocator, did: []const u8) !void {
    if (!std.mem.startsWith(u8, did, "did:plc:")) return;
    const last = fetchLastOperation(allocator, did) catch |err| switch (err) {
        error.PlcDidNotFound => return,
        else => return err,
    };
    const op_type = zat.json.getString(last, "type") orelse return error.PlcFetchFailed;
    if (std.mem.eql(u8, op_type, "plc_tombstone")) return;
    var rotation_key = try configuredRotationKeypair();
    const rotation_did = try rotation_key.did(allocator);
    const rotation_keys = switch (last) {
        .object => |object| switch (object.get("rotationKeys") orelse return error.NotARotationKey) {
            .array => |array| array.items,
            else => return error.NotARotationKey,
        },
        else => return error.PlcFetchFailed,
    };
    for (rotation_keys) |key| {
        if (key == .string and std.mem.eql(u8, key.string, rotation_did)) break;
    } else return error.NotARotationKey;
    const prev = try cidForJsonValue(allocator, last);
    const unsigned = try std.fmt.allocPrint(allocator, "{{\"type\":\"plc_tombstone\",\"prev\":{f}}}", .{std.json.fmt(prev, .{})});
    try submitOperation(allocator, did, try signOperationJson(allocator, unsigned, &rotation_key), .update);
}

pub fn fetchLastOperation(allocator: std.mem.Allocator, did: []const u8) !std.json.Value {
    const escaped_did = try zat.oauth.percentEncodeAlloc(allocator, did);
    const url = try std.fmt.allocPrint(allocator, "{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) == 404) return error.PlcDidNotFound;
    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;
}

pub fn updateOperationJson(
    allocator: std.mem.Allocator,
    handle: []const u8,
    keys: VerificationKeys,
    rotation_keys: []const []const u8,
    prev: []const u8,
) ![]const u8 {
    const rotation_keys_json = try jsonStringArray(allocator, rotation_keys);
    return std.fmt.allocPrint(
        allocator,
        "{{\"type\":\"plc_operation\",\"rotationKeys\":{s},\"verificationMethods\":{f},\"alsoKnownAs\":[{f}],\"services\":{{\"atproto_pds\":{{\"type\":\"AtprotoPersonalDataServer\",\"endpoint\":{f}}}}},\"prev\":{f}}}",
        .{
            rotation_keys_json,
            keys,
            std.json.fmt(try std.fmt.allocPrint(allocator, "at://{s}", .{handle}), .{}),
            std.json.fmt(config.publicUrl(), .{}),
            std.json.fmt(prev, .{}),
        },
    );
}

pub fn updateHandleOperationJson(
    allocator: std.mem.Allocator,
    last_op: std.json.Value,
    handle: []const u8,
    prev: []const u8,
) ![]const u8 {
    const last = switch (last_op) {
        .object => |object| object,
        else => return error.InvalidPlcOperation,
    };
    const rotation_keys = last.get("rotationKeys") orelse return error.InvalidPlcOperation;
    const verification_methods = last.get("verificationMethods") orelse return error.InvalidPlcOperation;
    const services = last.get("services") orelse return error.InvalidPlcOperation;
    const also_known_as = try std.fmt.allocPrint(allocator, "at://{s}", .{handle});

    return std.fmt.allocPrint(
        allocator,
        "{{\"type\":\"plc_operation\",\"rotationKeys\":{s},\"verificationMethods\":{s},\"alsoKnownAs\":[{f}],\"services\":{s},\"prev\":{f}}}",
        .{
            try stringifyJson(allocator, rotation_keys),
            try stringifyJson(allocator, verification_methods),
            std.json.fmt(also_known_as, .{}),
            try stringifyJson(allocator, services),
            std.json.fmt(prev, .{}),
        },
    );
}

/// Republish an account's PLC data with an `#atproto_kem` verification method,
/// keeping its rotation keys, other verification methods, handle, and services.
pub fn addKemKeyOperationJson(
    allocator: std.mem.Allocator,
    last_op: std.json.Value,
    kem_did_key: []const u8,
    prev: []const u8,
) ![]const u8 {
    const last = switch (last_op) {
        .object => |object| object,
        else => return error.InvalidPlcOperation,
    };
    const rotation_keys = last.get("rotationKeys") orelse return error.InvalidPlcOperation;
    const verification_methods = switch (last.get("verificationMethods") orelse return error.InvalidPlcOperation) {
        .object => |object| object,
        else => return error.InvalidPlcOperation,
    };
    const also_known_as = last.get("alsoKnownAs") orelse return error.InvalidPlcOperation;
    const services = last.get("services") orelse return error.InvalidPlcOperation;

    var methods: std.Io.Writer.Allocating = .init(allocator);
    defer methods.deinit();
    try methods.writer.writeByte('{');
    var it = verification_methods.iterator();
    var first = true;
    while (it.next()) |entry| {
        if (std.mem.eql(u8, entry.key_ptr.*, "atproto_kem")) continue;
        if (!first) try methods.writer.writeByte(',');
        first = false;
        try methods.writer.print("{f}:{f}", .{ std.json.fmt(entry.key_ptr.*, .{}), std.json.fmt(entry.value_ptr.*, .{}) });
    }
    if (!first) try methods.writer.writeByte(',');
    try methods.writer.print("\"atproto_kem\":{f}}}", .{std.json.fmt(kem_did_key, .{})});

    return std.fmt.allocPrint(
        allocator,
        "{{\"type\":\"plc_operation\",\"rotationKeys\":{s},\"verificationMethods\":{s},\"alsoKnownAs\":{s},\"services\":{s},\"prev\":{f}}}",
        .{
            try stringifyJson(allocator, rotation_keys),
            methods.written(),
            try stringifyJson(allocator, also_known_as),
            try stringifyJson(allocator, services),
            std.json.fmt(prev, .{}),
        },
    );
}

pub fn signOperationJson(allocator: std.mem.Allocator, unsigned_json: []const u8, signing_key: *const zat.Keypair) ![]const u8 {
    return zat.plc.signJson(allocator, unsigned_json, signing_key);
}

pub fn cidForJsonValue(allocator: std.mem.Allocator, value: std.json.Value) ![]const u8 {
    return zat.plc.cidForJson(allocator, value);
}

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

/// The PLC verification methods this PDS publishes for an account. `atproto_kem`
/// is the P-256 key syncers derive space MAC secrets against.
pub const VerificationKeys = struct {
    atproto: []const u8,
    atproto_kem: ?[]const u8 = null,

    pub fn format(self: VerificationKeys, writer: *std.Io.Writer) std.Io.Writer.Error!void {
        try writer.print("{{\"atproto\":{f}", .{std.json.fmt(self.atproto, .{})});
        if (self.atproto_kem) |kem| try writer.print(",\"atproto_kem\":{f}", .{std.json.fmt(kem, .{})});
        try writer.writeByte('}');
    }
};

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

test "PLC genesis operation is signed and derives a did:plc" {
    const allocator = std.testing.allocator;
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const before = config.publicUrl();
    defer config.setPublicUrl(before);
    config.setPublicUrl("https://pds.example.com");

    const secret: [32]u8 = .{
        0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08,
        0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, 0x10,
        0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18,
        0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f, 0x20,
    };
    const keypair = try zat.Keypair.fromSecretKey(.secp256k1, secret);
    const kem_keypair = try zat.Keypair.fromSecretKey(.p256, @splat(0x31));
    const op = try createGenesisOperation(a, "alice.example.com", &keypair, &kem_keypair, &keypair);
    try std.testing.expect(std.mem.startsWith(u8, op.did, "did:plc:"));
    try std.testing.expectEqual(@as(usize, "did:plc:".len + 24), op.did.len);
    try std.testing.expect(std.mem.indexOf(u8, op.json, "\"type\":\"plc_operation\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, op.json, "\"sig\"") != null);
    try std.testing.expect(std.mem.indexOf(u8, op.json, "https://pds.example.com") != null);

    const parsed = try std.json.parseFromSlice(std.json.Value, a, op.json, .{});
    const sig_text = parsed.value.object.get("sig").?.string;
    const sig_bytes = try zat.jwt.base64UrlDecode(a, sig_text);
    const did_key = try keypair.did(a);
    const kem_did_key = try kem_keypair.did(a);
    try std.testing.expectEqualStrings(kem_did_key, parsed.value.object.get("verificationMethods").?.object.get("atproto_kem").?.string);
    try std.testing.expect(std.mem.startsWith(u8, kem_did_key, "did:key:zDnae"));
    _ = sig_bytes;
    // The directory checks the signature against the JSON it receives.
    try zat.plc.verifyJson(a, parsed.value, did_key);
}

test "KEM key operation adds atproto_kem and keeps the rest of the PLC data" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const current =
        \\{"type":"plc_operation","rotationKeys":["did:key:recovery","did:key:pds"],"verificationMethods":{"atproto":"did:key:account","atproto_kem":"did:key:stale"},"alsoKnownAs":["at://alice.example.com","https://alice.example.com"],"services":{"atproto_pds":{"type":"AtprotoPersonalDataServer","endpoint":"https://pds.example.com"}},"prev":"bafyprev","sig":"old-signature"}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, current, .{});
    const updated = try addKemKeyOperationJson(allocator, parsed.value, "did:key:zDnaekem", "bafycurrent");
    const operation = try std.json.parseFromSlice(std.json.Value, allocator, updated, .{});
    const object = operation.value.object;

    const methods = object.get("verificationMethods").?.object;
    try std.testing.expectEqual(@as(usize, 2), methods.count());
    try std.testing.expectEqualStrings("did:key:account", methods.get("atproto").?.string);
    try std.testing.expectEqualStrings("did:key:zDnaekem", methods.get("atproto_kem").?.string);
    try std.testing.expectEqual(@as(usize, 2), object.get("alsoKnownAs").?.array.items.len);
    try std.testing.expectEqual(@as(usize, 2), object.get("rotationKeys").?.array.items.len);
    try std.testing.expectEqualStrings("https://pds.example.com", object.get("services").?.object.get("atproto_pds").?.object.get("endpoint").?.string);
    try std.testing.expectEqualStrings("bafycurrent", object.get("prev").?.string);
    try std.testing.expect(object.get("sig") == null);
}

test "PLC private key parser accepts official hex and PDS Moover private multikey" {
    const allocator = std.testing.allocator;
    const hex = "0102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f20";
    const from_hex = try parsePrivateKey(allocator, hex);

    var secret: [32]u8 = undefined;
    _ = try std.fmt.hexToBytes(&secret, hex);
    var private_multikey_bytes: [34]u8 = undefined;
    private_multikey_bytes[0] = 0x81;
    private_multikey_bytes[1] = 0x26;
    @memcpy(private_multikey_bytes[2..], &secret);

    const private_multikey = try zat.multibase.encode(allocator, .base58btc, &private_multikey_bytes);
    defer allocator.free(private_multikey);

    const from_multikey = try parsePrivateKey(allocator, private_multikey);
    const hex_did = try from_hex.did(allocator);
    defer allocator.free(hex_did);
    const multikey_did = try from_multikey.did(allocator);
    defer allocator.free(multikey_did);

    try std.testing.expectEqualStrings(hex_did, multikey_did);
}

test "handle update operation preserves current PLC authority and services" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const current =
        \\{"type":"plc_operation","rotationKeys":["did:key:recovery","did:key:pds"],"verificationMethods":{"atproto":"did:key:account","extra":"did:key:extra"},"alsoKnownAs":["at://old.example.com"],"services":{"atproto_pds":{"type":"AtprotoPersonalDataServer","endpoint":"https://old-pds.example.com"},"other":{"type":"Other","endpoint":"https://service.example.com"}},"prev":"bafyprev","sig":"old-signature"}
    ;
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, current, .{});
    const updated = try updateHandleOperationJson(allocator, parsed.value, "new.example.com", "bafycurrent");
    const operation = try std.json.parseFromSlice(std.json.Value, allocator, updated, .{});

    try std.testing.expectEqualStrings(
        "at://new.example.com",
        operation.value.object.get("alsoKnownAs").?.array.items[0].string,
    );
    try std.testing.expectEqualStrings(
        "did:key:recovery",
        operation.value.object.get("rotationKeys").?.array.items[0].string,
    );
    try std.testing.expectEqualStrings(
        "did:key:extra",
        operation.value.object.get("verificationMethods").?.object.get("extra").?.string,
    );
    try std.testing.expectEqualStrings(
        "https://service.example.com",
        operation.value.object.get("services").?.object.get("other").?.object.get("endpoint").?.string,
    );
    try std.testing.expectEqualStrings("bafycurrent", operation.value.object.get("prev").?.string);
    try std.testing.expect(operation.value.object.get("sig") == null);
}

test "a genesis operation's JSON and DID are byte-identical to the ones zds published before zat.plc" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const before = config.publicUrl();
    defer config.setPublicUrl(before);
    config.setPublicUrl("https://pds.example.com");
    const keypair = try zat.Keypair.fromSecretKey(.secp256k1, @splat(0x07));
    const kem_keypair = try zat.Keypair.fromSecretKey(.p256, @splat(0x31));
    const op = try createGenesisOperation(a, "alice.example.com", &keypair, &kem_keypair, &keypair);
    try std.testing.expectEqualStrings("did:plc:wkz465lcgbwjdj5zh5oyfirf", op.did);
    try std.testing.expectEqualStrings(
        \\{"type":"plc_operation","rotationKeys":["did:key:zQ3shXgWjVsCJsv9mBm6kVqFSjAnErMg3zG9CcyvmUCCaFRCr"],"verificationMethods":{"atproto":"did:key:zQ3shXgWjVsCJsv9mBm6kVqFSjAnErMg3zG9CcyvmUCCaFRCr","atproto_kem":"did:key:zDnaeqUrfBAawsQSp9qhimokjT1UuvQ8g19vEUHkmVjtZgR6X"},"alsoKnownAs":["at://alice.example.com"],"services":{"atproto_pds":{"type":"AtprotoPersonalDataServer","endpoint":"https://pds.example.com"}},"prev":null,"sig":"ZRgysmsFmEwK6BSs60lWt5j1KJX5qPX_4CAy4fe_5bhSPXEMk5wVw9CiJlmkfI5_abdiLvPLCF-kYxC1ySiz6Q"}
    , op.json);
}