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

zat.dev/zat

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

0
0
485 lines · 22.1 KB Raw History
//! did:plc operations: DAG-CBOR encoding, signing, CIDs and DID derivation
//!
//! an operation is signed over its DAG-CBOR encoding without the `sig` field,
//! with a rotation key (ECDSA-SHA256, low-S, 64-byte r||s, base64url without
//! padding). the CID of an operation (what the next one's `prev` names) is a
//! CIDv1 dag-cbor sha-256 of the signed operation's DAG-CBOR, as a base32
//! multibase string. a did:plc is the first 24 characters of the base32 sha-256
//! of the signed genesis operation.
//!
//! `Operation` builds a `plc_operation`. the `*Json` functions take any
//! operation as JSON, including `plc_tombstone` and the legacy `create`
//! genesis format, which validators must still accept. which keys, handles and
//! services go into an operation is the caller's policy.
//!
//! see: https://web.plc.directory/spec/v0.1/did-plc

const std = @import("std");
const Allocator = std.mem.Allocator;
const cbor = @import("../repo/cbor.zig");
const multibase = @import("../crypto/multibase.zig");
const multicodec = @import("../crypto/multicodec.zig");
const jwt = @import("../crypto/jwt.zig");
const Keypair = @import("../crypto/keypair.zig").Keypair;

/// the directory's limit on an operation's DAG-CBOR size (spec v0.1).
pub const max_operation_bytes = 7500;

pub const did_prefix = "did:plc:";
/// length of a did:plc: the prefix plus 24 base32 characters.
pub const did_len = did_prefix.len + 24;

pub const VerificationMethod = struct {
    /// e.g. "atproto"
    id: []const u8,
    /// a did:key
    key: []const u8,
};

pub const Service = struct {
    /// e.g. "atproto_pds"
    id: []const u8,
    /// e.g. "AtprotoPersonalDataServer"
    type: []const u8,
    endpoint: []const u8,
};

/// a `plc_operation`: a genesis operation when `prev` is null, otherwise an
/// update naming the CID of the operation it follows.
pub const Operation = struct {
    rotation_keys: []const []const u8,
    verification_methods: []const VerificationMethod,
    also_known_as: []const []const u8,
    services: []const Service,
    prev: ?[]const u8 = null,

    /// the operation as a CBOR data-model value, with `sig` when given.
    /// allocates from `arena`.
    pub fn toCbor(self: Operation, arena: Allocator, sig: ?[]const u8) Allocator.Error!cbor.Value {
        const rotation = try arena.alloc(cbor.Value, self.rotation_keys.len);
        for (self.rotation_keys, rotation) |key, *slot| slot.* = .{ .text = key };

        const methods = try arena.alloc(cbor.Value.MapEntry, self.verification_methods.len);
        for (self.verification_methods, methods) |method, *slot| slot.* = .{ .key = method.id, .value = .{ .text = method.key } };

        const aka = try arena.alloc(cbor.Value, self.also_known_as.len);
        for (self.also_known_as, aka) |name, *slot| slot.* = .{ .text = name };

        const services = try arena.alloc(cbor.Value.MapEntry, self.services.len);
        for (self.services, services) |service, *slot| {
            const fields = try arena.alloc(cbor.Value.MapEntry, 2);
            fields[0] = .{ .key = "type", .value = .{ .text = service.type } };
            fields[1] = .{ .key = "endpoint", .value = .{ .text = service.endpoint } };
            slot.* = .{ .key = service.id, .value = .{ .map = fields } };
        }

        const entries = try arena.alloc(cbor.Value.MapEntry, if (sig == null) 6 else 7);
        entries[0] = .{ .key = "type", .value = .{ .text = "plc_operation" } };
        entries[1] = .{ .key = "rotationKeys", .value = .{ .array = rotation } };
        entries[2] = .{ .key = "verificationMethods", .value = .{ .map = methods } };
        entries[3] = .{ .key = "alsoKnownAs", .value = .{ .array = aka } };
        entries[4] = .{ .key = "services", .value = .{ .map = services } };
        entries[5] = .{ .key = "prev", .value = if (self.prev) |prev| .{ .text = prev } else .null };
        if (sig) |s| entries[6] = .{ .key = "sig", .value = .{ .text = s } };
        return .{ .map = entries };
    }

    /// DAG-CBOR of the operation, signed when `sig` is given.
    /// caller owns the returned slice.
    pub fn encode(self: Operation, allocator: Allocator, sig: ?[]const u8) ![]u8 {
        var arena: std.heap.ArenaAllocator = .init(allocator);
        defer arena.deinit();
        const value = try self.toCbor(arena.allocator(), sig);
        return cbor.encodeAlloc(allocator, value);
    }

    /// write the operation as JSON in the field order the reference
    /// implementation uses: type, rotationKeys, verificationMethods,
    /// alsoKnownAs, services, prev, then sig when given.
    pub fn writeJson(self: Operation, writer: *std.Io.Writer, sig: ?[]const u8) std.Io.Writer.Error!void {
        try writer.writeAll("{\"type\":\"plc_operation\",\"rotationKeys\":[");
        for (self.rotation_keys, 0..) |key, i| {
            if (i != 0) try writer.writeByte(',');
            try writer.print("{f}", .{std.json.fmt(key, .{})});
        }
        try writer.writeAll("],\"verificationMethods\":{");
        for (self.verification_methods, 0..) |method, i| {
            if (i != 0) try writer.writeByte(',');
            try writer.print("{f}:{f}", .{ std.json.fmt(method.id, .{}), std.json.fmt(method.key, .{}) });
        }
        try writer.writeAll("},\"alsoKnownAs\":[");
        for (self.also_known_as, 0..) |name, i| {
            if (i != 0) try writer.writeByte(',');
            try writer.print("{f}", .{std.json.fmt(name, .{})});
        }
        try writer.writeAll("],\"services\":{");
        for (self.services, 0..) |service, i| {
            if (i != 0) try writer.writeByte(',');
            try writer.print("{f}:{{\"type\":{f},\"endpoint\":{f}}}", .{
                std.json.fmt(service.id, .{}),
                std.json.fmt(service.type, .{}),
                std.json.fmt(service.endpoint, .{}),
            });
        }
        try writer.print("}},\"prev\":{f}", .{std.json.fmt(self.prev, .{})});
        if (sig) |s| try writer.print(",\"sig\":{f}", .{std.json.fmt(s, .{})});
        try writer.writeByte('}');
    }

    /// sign the operation with a rotation key.
    pub fn sign(self: Operation, allocator: Allocator, rotation_key: *const Keypair) !Signed {
        const unsigned = try self.encode(allocator, null);
        defer allocator.free(unsigned);
        const sig = try signatureText(allocator, unsigned, rotation_key);
        errdefer allocator.free(sig);

        const signed_cbor = try self.encode(allocator, sig);
        errdefer allocator.free(signed_cbor);

        var json: std.Io.Writer.Allocating = .init(allocator);
        errdefer json.deinit();
        self.writeJson(&json.writer, sig) catch return error.OutOfMemory;

        return .{ .sig = sig, .cbor = signed_cbor, .json = try json.toOwnedSlice() };
    }
};

/// a signed operation. all slices are owned; free with `deinit`.
pub const Signed = struct {
    /// base64url signature, the `sig` field
    sig: []u8,
    /// DAG-CBOR of the signed operation
    cbor: []u8,
    /// JSON of the signed operation, as submitted to the directory
    json: []u8,

    pub fn deinit(self: Signed, allocator: Allocator) void {
        allocator.free(self.sig);
        allocator.free(self.cbor);
        allocator.free(self.json);
    }

    /// the operation's CID string ("bafyrei..."). caller owns the slice.
    pub fn cid(self: Signed, allocator: Allocator) ![]u8 {
        return cidForCbor(allocator, self.cbor);
    }

    /// the did:plc this operation creates, when it is a genesis operation.
    pub fn did(self: Signed) [did_len]u8 {
        return didForCbor(self.cbor);
    }
};

/// the CID string of a signed operation's DAG-CBOR. caller owns the slice.
pub fn cidForCbor(allocator: Allocator, signed_cbor: []const u8) ![]u8 {
    const c = try cbor.Cid.forDagCbor(allocator, signed_cbor);
    defer allocator.free(c.raw);
    return c.toString(allocator);
}

/// the did:plc derived from a signed genesis operation's DAG-CBOR.
pub fn didForCbor(signed_cbor: []const u8) [did_len]u8 {
    var digest: [32]u8 = undefined;
    std.crypto.hash.sha2.Sha256.hash(signed_cbor, &digest, .{});
    var encoded: [52]u8 = undefined;
    _ = multibase.base32lower.encodeInto(&encoded, &digest);
    var out: [did_len]u8 = undefined;
    out[0..did_prefix.len].* = did_prefix.*;
    out[did_prefix.len..].* = encoded[0..24].*;
    return out;
}

/// DAG-CBOR of an operation given as JSON, with or without its `sig` field.
/// the operation must be an object with a string `type`. caller owns the slice.
pub fn encodeJson(allocator: Allocator, operation: std.json.Value, comptime sig: enum { keep, strip }) ![]u8 {
    const object = try operationObject(operation);
    var arena: std.heap.ArenaAllocator = .init(allocator);
    defer arena.deinit();
    // PLC operations hold only strings, arrays, objects and null, so the
    // atproto JSON conventions fromJson applies ($bytes, $link, floats) never
    // come into play.
    const value = cbor.fromJson(arena.allocator(), operation) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        else => return error.InvalidOperation,
    };
    if (sig == .strip and object.get("sig") != null) {
        const entries = value.map;
        const kept = try arena.allocator().alloc(cbor.Value.MapEntry, entries.len - 1);
        var i: usize = 0;
        for (entries) |entry| {
            if (std.mem.eql(u8, entry.key, "sig")) continue;
            kept[i] = entry;
            i += 1;
        }
        return cbor.encodeAlloc(allocator, .{ .map = kept });
    }
    return cbor.encodeAlloc(allocator, value);
}

/// sign an unsigned operation given as JSON text and return the signed JSON:
/// the input with `,"sig":"..."` appended before its closing brace, so the
/// caller's field order is kept. caller owns the slice.
pub fn signJson(allocator: Allocator, unsigned_json: []const u8, rotation_key: *const Keypair) ![]u8 {
    const parsed = std.json.parseFromSlice(std.json.Value, allocator, unsigned_json, .{}) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        else => return error.InvalidOperation,
    };
    defer parsed.deinit();
    const object = try operationObject(parsed.value);
    if (object.get("sig") != null) return error.AlreadySigned;

    const unsigned = try encodeJson(allocator, parsed.value, .keep);
    defer allocator.free(unsigned);
    const sig = try signatureText(allocator, unsigned, rotation_key);
    defer allocator.free(sig);

    const trimmed = std.mem.trimEnd(u8, unsigned_json, " \t\r\n");
    std.debug.assert(trimmed[trimmed.len - 1] == '}');
    return std.fmt.allocPrint(allocator, "{s},\"sig\":{f}}}", .{ trimmed[0 .. trimmed.len - 1], std.json.fmt(sig, .{}) });
}

/// the CID string of a signed operation given as JSON. caller owns the slice.
pub fn cidForJson(allocator: Allocator, operation: std.json.Value) ![]u8 {
    const encoded = try encodeJson(allocator, operation, .keep);
    defer allocator.free(encoded);
    return cidForCbor(allocator, encoded);
}

/// the did:plc derived from a signed genesis operation given as JSON.
pub fn didForJson(allocator: Allocator, operation: std.json.Value) ![did_len]u8 {
    const encoded = try encodeJson(allocator, operation, .keep);
    defer allocator.free(encoded);
    return didForCbor(encoded);
}

/// verify a signed operation's `sig` against one rotation key (a did:key).
/// the signature must be canonical base64url and low-S.
pub fn verifyJson(allocator: Allocator, operation: std.json.Value, rotation_did_key: []const u8) !void {
    const object = try operationObject(operation);
    const sig_text = switch (object.get("sig") orelse return error.MissingSignature) {
        .string => |s| s,
        else => return error.InvalidSignature,
    };
    const Decoder = std.base64.url_safe_no_pad.Decoder;
    var sig: [64]u8 = undefined;
    if ((Decoder.calcSizeForSlice(sig_text) catch return error.InvalidSignature) != sig.len)
        return error.InvalidSignature;
    Decoder.decode(&sig, sig_text) catch return error.InvalidSignature;
    var canonical: [86]u8 = undefined;
    if (!std.mem.eql(u8, std.base64.url_safe_no_pad.Encoder.encode(&canonical, &sig), sig_text))
        return error.InvalidSignature;

    const unsigned = try encodeJson(allocator, operation, .strip);
    defer allocator.free(unsigned);
    try multicodec.verifyDidKeySignature(allocator, rotation_did_key, unsigned, &sig);
}

fn operationObject(operation: std.json.Value) !std.json.ObjectMap {
    const object = switch (operation) {
        .object => |o| o,
        else => return error.InvalidOperation,
    };
    switch (object.get("type") orelse return error.InvalidOperation) {
        .string => {},
        else => return error.InvalidOperation,
    }
    return object;
}

fn signatureText(allocator: Allocator, unsigned_cbor: []const u8, rotation_key: *const Keypair) ![]u8 {
    const signature = try rotation_key.sign(unsigned_cbor);
    return jwt.base64UrlEncode(allocator, &signature.bytes);
}

// === tests ===

const AuditEntry = struct {
    did: []const u8,
    operation: std.json.Value,
    cid: []const u8,
};

fn parseAudit(allocator: Allocator, text: []const u8) !std.json.Parsed([]AuditEntry) {
    return std.json.parseFromSlice([]AuditEntry, allocator, text, .{ .ignore_unknown_fields = true });
}

fn rotationKeysOf(operation: std.json.Value) ![]const []const u8 {
    const object = operation.object;
    if (object.get("rotationKeys")) |keys| {
        var out: std.ArrayList([]const u8) = .empty;
        for (keys.array.items) |key| try out.append(std.testing.allocator, key.string);
        return out.toOwnedSlice(std.testing.allocator);
    }
    // legacy create: recoveryKey and signingKey both rotate
    const out = try std.testing.allocator.alloc([]const u8, 2);
    out[0] = object.get("recoveryKey").?.string;
    out[1] = object.get("signingKey").?.string;
    return out;
}

fn expectAuditLogReproduces(text: []const u8) !void {
    const allocator = std.testing.allocator;
    const audit = try parseAudit(allocator, text);
    defer audit.deinit();
    const entries = audit.value;

    const genesis_did = try didForJson(allocator, entries[0].operation);
    try std.testing.expectEqualStrings(entries[0].did, &genesis_did);

    for (entries, 0..) |entry, i| {
        const cid = try cidForJson(allocator, entry.operation);
        defer allocator.free(cid);
        try std.testing.expectEqualStrings(entry.cid, cid);

        const signer = if (i == 0) entry.operation else entries[i - 1].operation;
        if (i > 0) try std.testing.expectEqualStrings(entries[i - 1].cid, entry.operation.object.get("prev").?.string);
        const keys = try rotationKeysOf(signer);
        defer allocator.free(keys);
        var verified = false;
        for (keys) |key| {
            verifyJson(allocator, entry.operation, key) catch continue;
            verified = true;
        }
        try std.testing.expect(verified);
    }
}

test "CIDs, signatures and the DID of a plc.directory audit log reproduce" {
    try expectAuditLogReproduces(@embedFile("testdata/plc-audit-mkqt76xvfgxuemlwlx6ruc3w.json"));
}

test "a legacy create genesis derives its DID and CID" {
    try expectAuditLogReproduces(@embedFile("testdata/plc-audit-yk4dd2qkboz2yv6tpubpc6co-genesis.json"));
}

test "Operation encodes like the directory's JSON form" {
    const allocator = std.testing.allocator;
    const audit = try parseAudit(allocator, @embedFile("testdata/plc-audit-mkqt76xvfgxuemlwlx6ruc3w.json"));
    defer audit.deinit();
    const genesis = audit.value[0];

    const op: Operation = .{
        .rotation_keys = &.{
            "did:key:zQ3shhCGUqDKjStzuDxPkTxN6ujddP4RkEKJJouJGRRkaLGbg",
            "did:key:zQ3shpKnbdPx3g3CmPf5cRVTPe1HtSwVn5ish3wSnDPQCbLJK",
        },
        .verification_methods = &.{.{ .id = "atproto", .key = "did:key:zQ3shtrFPqnw151sbM7twFKPc3tshKdN54RVDNVdiGMC7VP6t" }},
        .also_known_as = &.{"at://zatdev.bsky.social"},
        .services = &.{.{ .id = "atproto_pds", .type = "AtprotoPersonalDataServer", .endpoint = "https://agrocybe.us-west.host.bsky.network" }},
    };
    const sig = genesis.operation.object.get("sig").?.string;
    const signed = try op.encode(allocator, sig);
    defer allocator.free(signed);
    const cid = try cidForCbor(allocator, signed);
    defer allocator.free(cid);
    try std.testing.expectEqualStrings(genesis.cid, cid);
    try std.testing.expectEqualStrings(genesis.did, &didForCbor(signed));

    const unsigned = try op.encode(allocator, null);
    defer allocator.free(unsigned);
    const stripped = try encodeJson(allocator, genesis.operation, .strip);
    defer allocator.free(stripped);
    try std.testing.expectEqualSlices(u8, stripped, unsigned);

    var json: std.Io.Writer.Allocating = .init(allocator);
    defer json.deinit();
    try op.writeJson(&json.writer, sig);
    const reparsed = try std.json.parseFromSlice(std.json.Value, allocator, json.written(), .{});
    defer reparsed.deinit();
    const reencoded = try encodeJson(allocator, reparsed.value, .keep);
    defer allocator.free(reencoded);
    try std.testing.expectEqualSlices(u8, signed, reencoded);
}

test "Operation.sign produces a verifiable genesis and its DID" {
    const allocator = std.testing.allocator;
    const rotation = try Keypair.fromSecretKey(.secp256k1, @splat(0x07));
    const rotation_did = try rotation.did(allocator);
    defer allocator.free(rotation_did);

    const op: Operation = .{
        .rotation_keys = &.{rotation_did},
        .verification_methods = &.{.{ .id = "atproto", .key = rotation_did }},
        .also_known_as = &.{"at://alice.example.com"},
        .services = &.{.{ .id = "atproto_pds", .type = "AtprotoPersonalDataServer", .endpoint = "https://pds.example.com" }},
    };
    const signed = try op.sign(allocator, &rotation);
    defer signed.deinit(allocator);

    try std.testing.expect(std.mem.startsWith(u8, signed.json, "{\"type\":\"plc_operation\",\"rotationKeys\":["));
    try std.testing.expect(std.mem.indexOf(u8, signed.json, ",\"prev\":null,\"sig\":\"") != null);
    try std.testing.expectEqual(@as(usize, 86), signed.sig.len);

    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, signed.json, .{});
    defer parsed.deinit();
    try verifyJson(allocator, parsed.value, rotation_did);

    const did = signed.did();
    const did_from_json = try didForJson(allocator, parsed.value);
    try std.testing.expectEqualStrings(&did, &did_from_json);
    for (did[did_prefix.len..]) |c| try std.testing.expect(std.mem.indexOfScalar(u8, "abcdefghijklmnopqrstuvwxyz234567", c) != null);

    const cid = try signed.cid(allocator);
    defer allocator.free(cid);
    const cid_from_json = try cidForJson(allocator, parsed.value);
    defer allocator.free(cid_from_json);
    try std.testing.expectEqualStrings(cid, cid_from_json);
    try std.testing.expect(std.mem.startsWith(u8, cid, "bafyrei"));
}

test "signJson keeps field order and signs a tombstone" {
    const allocator = std.testing.allocator;
    const rotation = try Keypair.fromSecretKey(.p256, @splat(0x21));
    const rotation_did = try rotation.did(allocator);
    defer allocator.free(rotation_did);

    const unsigned = "{\"type\":\"plc_tombstone\",\"prev\":\"bafyreiacotue26iggp6tjdj5gum6jpqrawrz5we2k7a4ncmtrtdsctcymu\"}\n";
    const signed = try signJson(allocator, unsigned, &rotation);
    defer allocator.free(signed);
    try std.testing.expect(std.mem.startsWith(u8, signed, unsigned[0 .. unsigned.len - 2] ++ ",\"sig\":\""));

    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, signed, .{});
    defer parsed.deinit();
    try verifyJson(allocator, parsed.value, rotation_did);

    const other = try Keypair.fromSecretKey(.p256, @splat(0x22));
    const other_did = try other.did(allocator);
    defer allocator.free(other_did);
    try std.testing.expectError(error.SignatureVerificationFailed, verifyJson(allocator, parsed.value, other_did));
}

test "signJson and verifyJson reject malformed operations" {
    const allocator = std.testing.allocator;
    const rotation = try Keypair.fromSecretKey(.secp256k1, @splat(0x07));
    try std.testing.expectError(error.InvalidOperation, signJson(allocator, "[]", &rotation));
    try std.testing.expectError(error.InvalidOperation, signJson(allocator, "{}", &rotation));
    try std.testing.expectError(error.InvalidOperation, signJson(allocator, "{\"type\":1}", &rotation));
    try std.testing.expectError(error.InvalidOperation, signJson(allocator, "{\"type\":", &rotation));
    try std.testing.expectError(error.AlreadySigned, signJson(allocator, "{\"type\":\"plc_tombstone\",\"prev\":\"b\",\"sig\":\"x\"}", &rotation));

    const key = "did:key:zQ3shpKnbdPx3g3CmPf5cRVTPe1HtSwVn5ish3wSnDPQCbLJK";
    const genesis_prefix =
        \\{"prev":null,"type":"plc_operation","services":{"atproto_pds":{"type":"AtprotoPersonalDataServer","endpoint":"https://agrocybe.us-west.host.bsky.network"}},"alsoKnownAs":["at://zatdev.bsky.social"],"rotationKeys":["did:key:zQ3shhCGUqDKjStzuDxPkTxN6ujddP4RkEKJJouJGRRkaLGbg","did:key:zQ3shpKnbdPx3g3CmPf5cRVTPe1HtSwVn5ish3wSnDPQCbLJK"],"verificationMethods":{"atproto":"did:key:zQ3shtrFPqnw151sbM7twFKPc3tshKdN54RVDNVdiGMC7VP6t"}
    ;
    const sig = "IZWW7yb1dRpucTcN4YV4QdWHeGU2raCb4EIYTaPCwG9LtEbPCNG-S2xjFiS7pD9uKZna6c47Oubg6cu6_CTTig";
    const cases = [_]struct { sig_field: []const u8, err: ?anyerror }{
        .{ .sig_field = ",\"sig\":\"" ++ sig ++ "\"", .err = null },
        // the last char of a 64-byte base64url signature carries 4 padding
        // bits, which must be zero ('g' is 0b100000, 'h' sets a padding bit)
        .{ .sig_field = ",\"sig\":\"" ++ sig[0 .. sig.len - 1] ++ "h\"", .err = error.InvalidSignature },
        .{ .sig_field = ",\"sig\":\"" ++ sig[0 .. sig.len - 1] ++ "\"", .err = error.InvalidSignature },
        .{ .sig_field = ",\"sig\":7", .err = error.InvalidSignature },
        .{ .sig_field = "", .err = error.MissingSignature },
    };
    for (cases) |case| {
        const text = try std.mem.concat(allocator, u8, &.{ genesis_prefix, case.sig_field, "}" });
        defer allocator.free(text);
        const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
        defer parsed.deinit();
        if (case.err) |err| {
            try std.testing.expectError(err, verifyJson(allocator, parsed.value, key));
        } else {
            try verifyJson(allocator, parsed.value, key);
        }
    }
}