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

zat.dev/zat

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

0
0
368 lines · 15.2 KB Raw History
//! labeler event stream: `com.atproto.label.subscribeLabels`.
//!
//! a labeler publishes `com.atproto.label.defs#label` records on a sequenced
//! stream framed like the repo firehose: a CBOR header `{op, t}` followed by a
//! CBOR payload. `#labels` carries `{seq, labels}`; `#info` is advisory (e.g.
//! `OutdatedCursor`); an error frame (`op: -1`) carries `{error, message}`,
//! such as `FutureCursor`, after which the labeler closes the connection.
//!
//! `LabelClient` reconnects from the last delivered seq exactly as
//! `FirehoseClient` does; handlers implement `onEvent(*H, Event)`.
//!
//! see: https://atproto.com/specs/label

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

const Allocator = std.mem.Allocator;
const mem = std.mem;

pub const nsid = "com.atproto.label.subscribeLabels";

/// `com.atproto.label.defs#label`
pub const Label = struct {
    ver: u64 = 1,
    /// DID of the labeler that created the label
    src: []const u8,
    /// subject: a DID for an account, or an at:// URI for a record
    uri: []const u8,
    /// optional CID pinning the label to one version of the record
    cid: ?[]const u8 = null,
    val: []const u8,
    /// true withdraws an earlier label with the same src, uri and val
    neg: bool = false,
    cts: []const u8,
    exp: ?[]const u8 = null,
    sig: ?[]const u8 = null,

    /// read a label from its decoded CBOR map. slices borrow from `value`.
    pub fn fromValue(value: cbor.Value) DecodeError!Label {
        if (value != .map) return error.InvalidLabel;
        return .{
            .ver = value.getUint("ver") orelse 1,
            .src = value.getString("src") orelse return error.MissingField,
            .uri = value.getString("uri") orelse return error.MissingField,
            .cid = value.getString("cid"),
            .val = value.getString("val") orelse return error.MissingField,
            .neg = value.getBool("neg") orelse false,
            .cts = value.getString("cts") orelse return error.MissingField,
            .exp = value.getString("exp"),
            .sig = value.getBytes("sig"),
        };
    }

    /// the label as a CBOR map; `entries` backs the returned value
    pub fn toValue(self: Label, entries: *[9]cbor.Value.MapEntry, include_sig: bool) cbor.Value {
        var n: usize = 0;
        const put = struct {
            fn put(buf: *[9]cbor.Value.MapEntry, i: *usize, key: []const u8, v: cbor.Value) void {
                buf[i.*] = .{ .key = key, .value = v };
                i.* += 1;
            }
        }.put;
        put(entries, &n, "ver", .{ .unsigned = self.ver });
        put(entries, &n, "src", .{ .text = self.src });
        put(entries, &n, "uri", .{ .text = self.uri });
        if (self.cid) |c| put(entries, &n, "cid", .{ .text = c });
        put(entries, &n, "val", .{ .text = self.val });
        if (self.neg) put(entries, &n, "neg", .{ .boolean = true });
        put(entries, &n, "cts", .{ .text = self.cts });
        if (self.exp) |e| put(entries, &n, "exp", .{ .text = e });
        if (include_sig) if (self.sig) |s| put(entries, &n, "sig", .{ .bytes = s });
        return .{ .map = entries[0..n] };
    }

    /// the bytes a labeler signs: the label as DAG-CBOR without `sig`.
    /// caller owns the returned slice.
    pub fn encodeUnsigned(self: Label, allocator: Allocator) ![]u8 {
        var entries: [9]cbor.Value.MapEntry = undefined;
        return cbor.encodeAlloc(allocator, self.toValue(&entries, false));
    }

    /// the label as DAG-CBOR, `sig` included when set. caller owns the slice.
    pub fn encode(self: Label, allocator: Allocator) ![]u8 {
        var entries: [9]cbor.Value.MapEntry = undefined;
        return cbor.encodeAlloc(allocator, self.toValue(&entries, true));
    }

    /// sign as the labeler: the signature over `encodeUnsigned`. set `sig`
    /// to its bytes before `encode`.
    pub fn sign(self: Label, allocator: Allocator, keypair: *const Keypair) !jwt.Signature {
        const unsigned = try self.encodeUnsigned(allocator);
        defer allocator.free(unsigned);
        return keypair.sign(unsigned);
    }

    /// verify `sig` against the labeler's signing key, given as a `did:key`
    /// (the `#atproto_label` verification method of the labeler's DID document).
    pub fn verify(self: Label, allocator: Allocator, signing_key: []const u8) !void {
        const sig = self.sig orelse return error.MissingSignature;
        const unsigned = try self.encodeUnsigned(allocator);
        defer allocator.free(unsigned);
        try multicodec.verifyDidKeySignature(allocator, signing_key, unsigned, sig);
    }
};

pub const LabelsEvent = struct {
    seq: i64,
    labels: []const Label,
};

/// an error frame. the labeler closes the stream after sending one.
pub const ErrorEvent = struct {
    name: ?[]const u8 = null,
    message: ?[]const u8 = null,
};

pub const Event = union(enum) {
    labels: LabelsEvent,
    info: firehose.InfoEvent,
    err: ErrorEvent,

    pub fn seq(self: Event) ?i64 {
        return switch (self) {
            .labels => |l| l.seq,
            .info, .err => null,
        };
    }
};

pub const DecodeError = error{
    InvalidHeader,
    InvalidLabel,
    MissingField,
    UnknownEventType,
} || cbor.DecodeError || Allocator.Error;

/// decode one stream frame. slices in the result borrow from `allocator`'s
/// allocations and from `data`; use an arena per frame.
pub fn decodeFrame(allocator: Allocator, data: []const u8) DecodeError!Event {
    const header_result = try cbor.decode(allocator, data);
    const header = header_result.value;
    const payload = try cbor.decodeAll(allocator, data[header_result.consumed..]);

    const op = header.getInt("op") orelse return error.InvalidHeader;
    if (op == -1) return .{ .err = .{
        .name = payload.getString("error"),
        .message = payload.getString("message"),
    } };
    if (op != 1) return error.InvalidHeader;

    const t = header.getString("t") orelse return error.InvalidHeader;
    if (mem.eql(u8, t, "#info")) return .{ .info = .{
        .name = payload.getString("name"),
        .message = payload.getString("message"),
    } };
    if (!mem.eql(u8, t, "#labels")) return error.UnknownEventType;

    const seq = payload.getInt("seq") orelse return error.MissingField;
    const values = payload.getArray("labels") orelse return error.MissingField;
    const labels = try allocator.alloc(Label, values.len);
    for (values, labels) |v, *l| l.* = try Label.fromValue(v);
    return .{ .labels = .{ .seq = seq, .labels = labels } };
}

/// encode one stream frame, as a labeler serves it. caller owns the slice.
pub fn encodeFrame(allocator: Allocator, event: Event) ![]u8 {
    var arena_state = std.heap.ArenaAllocator.init(allocator);
    defer arena_state.deinit();
    const arena = arena_state.allocator();

    var aw: std.Io.Writer.Allocating = .init(allocator);
    errdefer aw.deinit();

    const header: cbor.Value = switch (event) {
        .err => .{ .map = &.{.{ .key = "op", .value = .{ .negative = -1 } }} },
        .labels => .{ .map = &.{
            .{ .key = "op", .value = .{ .unsigned = 1 } },
            .{ .key = "t", .value = .{ .text = "#labels" } },
        } },
        .info => .{ .map = &.{
            .{ .key = "op", .value = .{ .unsigned = 1 } },
            .{ .key = "t", .value = .{ .text = "#info" } },
        } },
    };
    try cbor.encode(allocator, &aw.writer, header);

    const payload: cbor.Value = switch (event) {
        .labels => |l| blk: {
            const values = try arena.alloc(cbor.Value, l.labels.len);
            for (l.labels, values) |label, *v| {
                const entries = try arena.create([9]cbor.Value.MapEntry);
                v.* = label.toValue(entries, true);
            }
            break :blk .{ .map = try arena.dupe(cbor.Value.MapEntry, &.{
                .{ .key = "seq", .value = if (l.seq >= 0) .{ .unsigned = @intCast(l.seq) } else .{ .negative = l.seq } },
                .{ .key = "labels", .value = .{ .array = values } },
            }) };
        },
        .info => |i| try optionalTextMap(arena, "name", i.name, i.message),
        .err => |e| try optionalTextMap(arena, "error", e.name, e.message),
    };
    try cbor.encode(allocator, &aw.writer, payload);
    return aw.toOwnedSlice();
}

fn optionalTextMap(arena: Allocator, name_key: []const u8, name: ?[]const u8, message: ?[]const u8) !cbor.Value {
    var entries: std.ArrayList(cbor.Value.MapEntry) = .empty;
    if (name) |n| try entries.append(arena, .{ .key = name_key, .value = .{ .text = n } });
    if (message) |m| try entries.append(arena, .{ .key = "message", .value = .{ .text = m } });
    return .{ .map = entries.items };
}

pub const LabelStream = struct {
    pub const nsid = "com.atproto.label.subscribeLabels";
    pub const StreamEvent = Event;
    pub const decode = decodeFrame;
};

/// reconnecting `subscribeLabels` reader. `Options.hosts` are labeler
/// stream URLs (e.g. "wss://mod.bsky.app": a DID document's `#atproto_labeler`
/// service is published as https, so swap the scheme); `Options.cursor`
/// resumes after that seq. see `firehose.SubscriptionClient` for the handler
/// contract.
pub const LabelClient = firehose.SubscriptionClient(LabelStream);

// === tests ===

const testing = std.testing;

const fixture: Label = .{
    .src = "did:plc:ar7c4by46qjdydhdevvrndac",
    .uri = "did:plc:quqqrcopzs4eaeiehjjcvjrb",
    .val = "spam",
    .cts = "2026-06-26T00:06:15.938Z",
};

test "a #labels frame round-trips" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();

    const profile: Label = .{
        .src = fixture.src,
        .uri = "at://did:plc:quqqrcopzs4eaeiehjjcvjrb/app.bsky.actor.profile/self",
        .cid = "bafyreie2bk36ce4b6vokiy62f5iurnlv4v7ytm2xcx372nfu3a466gxxzu",
        .val = "!hide",
        .neg = true,
        .cts = fixture.cts,
        .exp = "2026-12-01T00:00:00.000Z",
        .sig = &[_]u8{ 1, 2, 3 },
    };
    const frame = try encodeFrame(alloc, .{ .labels = .{ .seq = 45261615, .labels = &.{ fixture, profile } } });
    const event = try decodeFrame(alloc, frame);
    try testing.expectEqual(@as(?i64, 45261615), event.seq());
    const labels = event.labels.labels;
    try testing.expectEqual(@as(usize, 2), labels.len);
    try testing.expectEqualStrings("spam", labels[0].val);
    try testing.expect(!labels[0].neg);
    try testing.expectEqual(@as(?[]const u8, null), labels[0].exp);
    try testing.expectEqualStrings(profile.uri, labels[1].uri);
    try testing.expectEqualStrings(profile.cid.?, labels[1].cid.?);
    try testing.expect(labels[1].neg);
    try testing.expectEqualStrings(profile.exp.?, labels[1].exp.?);
    try testing.expectEqualSlices(u8, profile.sig.?, labels[1].sig.?);
}

test "info and error frames decode without a seq" {
    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();

    const info = try decodeFrame(alloc, try encodeFrame(alloc, .{ .info = .{ .name = "OutdatedCursor" } }));
    try testing.expectEqualStrings("OutdatedCursor", info.info.name.?);
    try testing.expectEqual(@as(?i64, null), info.seq());

    const err = try decodeFrame(alloc, try encodeFrame(alloc, .{ .err = .{ .name = "FutureCursor", .message = "Cursor in the future." } }));
    try testing.expectEqualStrings("FutureCursor", err.err.name.?);
    try testing.expectEqualStrings("Cursor in the future.", err.err.message.?);
}

test "a label missing a required field is rejected" {
    const value: cbor.Value = .{ .map = &.{
        .{ .key = "src", .value = .{ .text = fixture.src } },
        .{ .key = "uri", .value = .{ .text = fixture.uri } },
        .{ .key = "val", .value = .{ .text = "spam" } },
    } };
    try testing.expectError(error.MissingField, Label.fromValue(value));
}

test "the signed bytes omit sig and sort keys as DAG-CBOR" {
    const alloc = testing.allocator;
    var signed = fixture;
    const fake_sig: [64]u8 = @splat(0xaa);
    signed.sig = &fake_sig;
    const unsigned = try signed.encodeUnsigned(alloc);
    defer alloc.free(unsigned);
    const plain = try fixture.encode(alloc);
    defer alloc.free(plain);
    try testing.expectEqualSlices(u8, plain, unsigned);
    var arena = std.heap.ArenaAllocator.init(alloc);
    defer arena.deinit();
    const decoded = try cbor.decodeAll(arena.allocator(), unsigned);
    try testing.expectEqualStrings("cts", decoded.map[0].key);
    try testing.expectEqualStrings("ver", decoded.map[decoded.map.len - 1].key);
}

test "verify accepts the labeler's signature and rejects a changed label" {
    const alloc = testing.allocator;
    const kp = try Keypair.fromSecretKey(.secp256k1, @as([32]u8, @splat(0x42)));
    const did_key = try kp.did(alloc);
    defer alloc.free(did_key);

    const sig = try fixture.sign(alloc, &kp);
    var label = fixture;
    label.sig = &sig.bytes;
    try label.verify(alloc, did_key);

    label.val = "!hide";
    try testing.expectError(error.SignatureVerificationFailed, label.verify(alloc, did_key));
}

test "LabelClient stops cleanly after a failed connect" {
    var threaded: std.Io.Threaded = .init(testing.allocator, .{});
    defer threaded.deinit();
    const Handler = struct {
        errors: usize = 0,
        pub fn onEvent(_: *@This(), _: Event) void {}
        pub fn shouldStop(self: *@This()) bool {
            return self.errors > 0;
        }
        pub fn onError(self: *@This(), _: anyerror) void {
            self.errors += 1;
        }
    };
    var client = LabelClient.init(threaded.io(), testing.allocator, .{ .hosts = &.{"ws://127.0.0.1:9"} });
    defer client.deinit();
    var handler: Handler = .{};
    try client.subscribe(&handler);
    try testing.expectEqual(@as(usize, 1), handler.errors);
}

test "a recorded Bluesky moderation frame decodes and its signature verifies" {
    // seq 45271183 from wss://mod.bsky.app, captured 2026-11-01, and the
    // #atproto_label key plc.directory served for did:plc:ar7c4by46qjdydhdevvrndac
    const hex = "a2617467236c6162656c73626f7001a2637365711a02b2c88f666c6162656c7381a6636374737818323032362d31312d30315430363a35353a33322e3338335a6373696758404150bd098f5b6614227c7a82158c06c0bc1ad585c2e0e2e19e04e69856eeca585c99859a8d70e7a0c7aff217ef21723b3d856969d6e07207d79ba930e3c3d8a96373726378206469643a706c633a617237633462793436716a6479646864657676726e6461636375726978206469643a706c633a6b376b716976686e683562353266797074726370346534616376616c692174616b65646f776e6376657201";
    const key = "did:key:zQ3shmV1BNcX17coaDbfen6zArEad6SCLT3jVWCbC6Y9iinTa";

    var arena = std.heap.ArenaAllocator.init(testing.allocator);
    defer arena.deinit();
    const alloc = arena.allocator();
    var frame: [hex.len / 2]u8 = undefined;
    _ = try std.fmt.hexToBytes(&frame, hex);

    const event = try decodeFrame(alloc, &frame);
    try testing.expectEqual(@as(i64, 45271183), event.labels.seq);
    const label = event.labels.labels[0];
    try testing.expectEqualStrings("!takedown", label.val);
    try testing.expectEqualStrings("did:plc:k7kqivhnh5b52fyptrcp4e4a", label.uri);
    try label.verify(alloc, key);

    var forged = label;
    forged.val = "spam";
    try testing.expectError(error.SignatureVerificationFailed, forged.verify(alloc, key));
}