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

zat.dev/zat

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

0
0
252 lines · 14.9 KB Raw History
const std = @import("std");
const zat = @import("zat");
const hegel = @import("hegel");

const Kind = enum { codecs, syntax, parsers, crypto, structured };
var tally: hegel.Tally(Kind) = .{};

fn equal(case: *hegel.TestCase, a: []const u8, b: []const u8, comptime origin: [:0]const u8) !void {
    if (!std.mem.eql(u8, a, b)) return case.fail(origin);
}

fn tolerate(result: anytype) !void {
    _ = result catch |err| {
        if (err == error.OutOfMemory) return err;
        return;
    };
}

fn oauthJson(a: std.mem.Allocator, bytes: []const u8) !void {
    const parsed = std.json.parseFromSlice(std.json.Value, a, bytes, .{}) catch |err| {
        if (err == error.OutOfMemory) return err;
        return;
    };
    defer parsed.deinit();
    try tolerate(zat.oauth.parseTokenResponse(a, parsed.value, null));
    try tolerate(zat.oauth.parseAuthorizationServerMetadata(a, parsed.value));
}

fn spaceUris(a: std.mem.Allocator, case: *hegel.TestCase) !void {
    const space_did = try std.fmt.allocPrint(a, "did:plc:owner{d}", .{try case.int(u16, 0, 65535)});
    const author_did = try std.fmt.allocPrint(a, "did:web:example.com:user{d}", .{try case.int(u16, 0, 65535)});
    const skey = try std.fmt.allocPrint(a, "key-{d}", .{try case.int(u16, 0, 65535)});
    const rkey = try std.fmt.allocPrint(a, "record_{d}", .{try case.int(u16, 0, 65535)});
    const space_type = "com.example.space";
    const collection = "com.example.post";
    const SpaceUri = zat.space.SpaceUri;
    const ref = try SpaceUri.formatRef(a, space_did, space_type, skey);
    const record = try SpaceUri.formatRecord(a, ref, author_did, collection, rkey);
    case.note("space ref {s}, record {s}", .{ ref, record });
    try equal(case, try std.fmt.allocPrint(a, "at:space/{s}/com.example.space/{s}", .{ space_did, skey }), ref, "space ref has wrong wire form");
    try equal(case, try std.fmt.allocPrint(a, "{s}/{s}/com.example.post/{s}", .{ ref, author_did, rkey }), record, "space record has wrong wire form");
    const parsed_ref = SpaceUri.parseRef(ref) orelse return case.fail("space ref rejected");
    const parsed_record = SpaceUri.parse(record) orelse return case.fail("space record rejected");
    if (!parsed_ref.isSpaceRef() or SpaceUri.parseRef(record) != null) return case.fail("space ref and record conflated");
    try equal(case, space_did, parsed_ref.space_did, "space authority lost");
    try equal(case, space_did, parsed_record.space_did, "space record authority lost");
    try equal(case, space_type, parsed_record.space_type, "space type lost");
    try equal(case, skey, parsed_record.skey, "space key lost");
    try equal(case, author_did, parsed_record.author_did orelse return case.fail("record lacks author"), "record author lost");
    try equal(case, collection, parsed_record.collection orelse return case.fail("record lacks collection"), "record collection lost");
    try equal(case, rkey, parsed_record.rkey orelse return case.fail("record lacks key"), "record key lost");
    case.event("space ref and record roundtrip");

    const previous = try std.fmt.allocPrint(a, "at://{s}/space/com.example.space/{s}", .{ space_did, skey });
    const partial = try std.fmt.allocPrint(a, "{s}/{s}/com.example.post", .{ ref, author_did });
    const handle_author = try std.fmt.allocPrint(a, "{s}/alice.example/com.example.post/{s}", .{ ref, rkey });
    const trailing_slash = try std.mem.concat(a, u8, &.{ record, "/" });
    case.event("space uri legacy and malformed mutations");
    for ([_][]const u8{ previous, partial, handle_author, trailing_slash }) |bad| {
        case.note("malformed space uri {s}", .{bad});
        if (SpaceUri.parse(bad) != null) return case.fail("malformed space URI accepted");
    }
}

fn property(kind: Kind, case: *hegel.TestCase) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    var buffer: [1024]u8 = undefined;
    const length = try case.int(usize, 0, buffer.len);
    const bytes = try case.bytes(&buffer, length, length);
    case.note("{s}: input={x}", .{ @tagName(kind), bytes });
    tally.case();
    tally.step(kind);
    switch (kind) {
        .codecs => {
            inline for (.{ zat.multibase.Encoding.base58btc, zat.multibase.Encoding.base32lower }) |encoding| {
                const encoded = try zat.multibase.encode(a, encoding, bytes);
                try equal(case, bytes, try zat.multibase.decode(a, encoded), "multibase loses bytes");
            }
            try equal(case, bytes, try zat.jwt.base64UrlDecode(a, try zat.jwt.base64UrlEncode(a, bytes)), "base64url loses bytes");
            const cid = try zat.Cid.forDagCbor(a, bytes);
            const archive = try zat.car.writeAlloc(a, .{ .roots = &.{cid}, .blocks = &.{.{ .cid_raw = cid.raw, .data = bytes }} });
            const decoded = try zat.car.read(a, archive);
            if (decoded.blocks.len != 1 or decoded.roots.len != 1) return case.fail("CAR loses roots or blocks");
            try equal(case, cid.raw, decoded.roots[0].raw, "CAR changes root");
            try equal(case, bytes, decoded.blocks[0].data, "CAR changes block");
            const n = (@as(u64, try case.int(u32, 0, std.math.maxInt(u32))) << 32) | try case.int(u32, 0, std.math.maxInt(u32));
            var out: std.Io.Writer.Allocating = .init(a);
            defer out.deinit();
            try zat.cbor.writeUvarint(&out.writer, n);
            var pos: usize = 0;
            if (zat.cbor.readUvarint(out.written(), &pos) != n or pos != out.written().len) return case.fail("varint loses integer or framing");
            const value: zat.cbor.Value = .{ .array = &.{ .{ .unsigned = n }, .{ .bytes = bytes }, .{ .boolean = try case.boolean() }, .null, .{ .cid = cid } } };
            const encoded = try zat.cbor.encodeAlloc(a, value);
            const roundtrip = try zat.cbor.decodeAll(a, encoded);
            if (roundtrip.array[0].unsigned != n) return case.fail("CBOR loses integer");
            try equal(case, bytes, roundtrip.array[1].bytes, "CBOR loses bytes");
            try equal(case, encoded, try zat.cbor.encodeAlloc(a, roundtrip), "CBOR canonical encoding changes");
            case.event("valid CAR and CBOR roundtrip");
        },
        .syntax => {
            const ts = (try case.int(u64, 0, 7)) << 50 | try case.int(u64, 0, (@as(u64, 1) << 50) - 1);
            const clock = try case.int(u10, 0, 1023);
            const tid = zat.Tid.fromTimestamp(ts, clock);
            const parsed = zat.Tid.parse(&tid.str()) orelse return case.fail("TID rejects generated value");
            if (parsed.timestamp() != ts or parsed.clockId() != clock) return case.fail("TID loses timestamp or clock");
            const micros = try case.int(i64, -62167219200000000, 253402300799999999);
            const date = zat.Datetime.fromMicros(micros);
            const recovered = zat.Datetime.parse(&date.toString()) orelse return case.fail("Datetime rejects formatted instant");
            if (recovered.micros != micros) return case.fail("Datetime loses microseconds");
            _ = zat.Tid.parse(bytes);
            _ = zat.Datetime.parse(bytes);
            _ = zat.Did.parse(bytes);
            _ = zat.Handle.parse(bytes);
            _ = zat.Nsid.parse(bytes);
            _ = zat.Rkey.parse(bytes);
            _ = zat.AtUri.parse(bytes);
            _ = zat.space.SpaceUri.parse(bytes);
            try spaceUris(a, case);
            case.event("valid TID and datetime roundtrip");
        },
        .parsers => {
            try tolerate(zat.cbor.decode(a, bytes));
            try tolerate(zat.cbor.decodeLax(a, bytes));
            try tolerate(zat.car.read(a, bytes));
            try tolerate(zat.car.streamBlocks(a, bytes, .{}));
            try tolerate(zat.multibase.decode(a, bytes));
            try tolerate(zat.multicodec.parsePublicKey(bytes));
            try tolerate(zat.multicodec.parseDidKey(a, bytes));
            try tolerate(zat.Jwt.parse(a, bytes));
            try tolerate(zat.DidDocument.parse(a, bytes));
            try tolerate(zat.jetstream.parseEvent(a, bytes));
            try tolerate(zat.firehose.decodeFrame(a, bytes));
            try tolerate(zat.labels.decodeFrame(a, bytes));
            try oauthJson(a, bytes);
            var input: std.Io.Reader = .fixed(bytes);
            if (zat.star.Reader.init(a, &input, .{ .max_metadata = 2048, .max_key = 2048, .max_value = 2048 })) |initial| {
                var reader = initial;
                defer reader.deinit();
                while (true) {
                    _ = (reader.next() catch break) orelse break;
                    var chunk: [128]u8 = undefined;
                    while (true) {
                        const n = reader.readValue(&chunk) catch break;
                        if (n == 0) break;
                    }
                }
            } else |err| if (err == error.OutOfMemory) return err;
            case.event("arbitrary bytes reach parser boundaries");
        },
        .structured => {
            var out: std.Io.Writer.Allocating = .init(a);
            defer out.deinit();
            var writer = try zat.star.Writer.init(a, &out.writer, .{ .map = &.{.{ .key = "$type", .value = .{ .text = "pbt" } }} }, .{});
            defer writer.deinit();
            try writer.writePair("app.bsky.feed.post/test", bytes);
            try writer.finish();
            var input: std.Io.Reader = .fixed(out.written());
            var reader = try zat.star.Reader.init(a, &input, .{});
            defer reader.deinit();
            const entry = (try reader.next()) orelse return case.fail("STAR loses entry");
            if (entry.value_len != bytes.len) return case.fail("STAR changes value length");
            var recovered: [1024]u8 = undefined;
            var used: usize = 0;
            while (used < bytes.len) used += try reader.readValue(recovered[used..][0..@min(bytes.len - used, 7)]);
            try equal(case, bytes, recovered[0..used], "STAR changes chunked value");
            if (try reader.next() != null) return case.fail("STAR invents entry");
            const label: zat.Label = .{ .src = "did:plc:abcdefghijklmnopqrstuvwx", .uri = "at://test.example/app.bsky.feed.post/key", .val = "test", .cts = "2026-11-04T00:00:00Z", .neg = try case.boolean() };
            const label_bytes = try label.encode(a);
            const decoded = try zat.Label.fromValue(try zat.cbor.decodeAll(a, label_bytes));
            if (label.neg != decoded.neg) return case.fail("label loses negation");
            try equal(case, label_bytes, try decoded.encode(a), "label canonical encoding changes");
            const json_seeds = [_][]const u8{
                "{\"did\":\"did:plc:abcdefghijklmnopqrstuvwx\",\"time_us\":1,\"kind\":\"account\",\"account\":{\"active\":true}}",
                "{\"id\":\"did:plc:abcdefghijklmnopqrstuvwx\",\"alsoKnownAs\":[\"at://test.example\"],\"service\":[]}",
                "{\"access_token\":\"token\",\"token_type\":\"DPoP\",\"expires_in\":300}",
            };
            const seed = json_seeds[try case.index(json_seeds.len)];
            const mutated = try a.dupe(u8, seed);
            if (try case.boolean()) mutated[try case.index(mutated.len)] = try case.int(u8, 0, 255);
            const cut = try case.int(usize, 0, mutated.len);
            try tolerate(zat.jetstream.parseEvent(a, mutated[0..cut]));
            try tolerate(zat.DidDocument.parse(a, mutated[0..cut]));
            try oauthJson(a, mutated[0..cut]);
            const cid = try zat.Cid.forDagCbor(a, bytes);
            const seq = try case.int(i64, 0, std.math.maxInt(i64));
            const frame = try zat.firehose.encodeCommitEvent(a, .{
                .seq = seq,
                .repo_did = label.src,
                .commit_cid = cid,
                .rev = "2222222222222",
                .blocks = bytes,
                .ops = &.{},
                .time = label.cts,
                .rebase = try case.boolean(),
                .too_big = try case.boolean(),
            });
            const event = try zat.firehose.decodeFrame(a, frame);
            if (event.commit.seq != seq) return case.fail("firehose loses sequence");
            if (bytes.len > 0) {
                try equal(case, bytes, event.commit.blocks, "firehose changes blocks");
            } else {
                const empty = zat.car.read(a, event.commit.blocks) catch return case.fail("firehose writes unreadable CAR for empty commit");
                if (empty.blocks.len != 0) return case.fail("firehose invents blocks for empty commit");
                try equal(case, cid.raw, empty.roots[0].raw, "firehose CAR root is not the commit CID");
            }
            try tolerate(zat.firehose.decodeFrame(a, frame[0..try case.int(usize, 0, frame.len)]));
            const encoded = try a.dupe(u8, label_bytes);
            encoded[try case.index(encoded.len)] = try case.int(u8, 0, 255);
            try tolerate(zat.cbor.decodeAll(a, encoded));
            case.event("STAR chunked reads and structured parser mutations");
        },
        .crypto => {
            var secret: [32]u8 = @splat(0);
            const scalar = try case.int(u32, 1, std.math.maxInt(u32));
            std.mem.writeInt(u32, secret[28..32], scalar, .big);
            inline for (.{ zat.multicodec.KeyType.secp256k1, zat.multicodec.KeyType.p256 }) |curve| {
                const key = try zat.Keypair.fromSecretKey(curve, secret);
                const signature = try key.sign(bytes);
                const did = try key.did(a);
                try zat.multicodec.verifyDidKeySignature(a, did, bytes, &signature.bytes);
                const changed = try std.mem.concat(a, u8, &.{ bytes, "!" });
                if (zat.multicodec.verifyDidKeySignature(a, did, changed, &signature.bytes)) |_| return case.fail("signature accepts changed message") else |_| {}
            }
            const cid = try zat.Cid.forDagCbor(a, bytes);
            const key = try zat.Keypair.fromSecretKey(.p256, secret);
            const signed = try zat.signCommit(a, .{ .did = "did:plc:abcdefghijklmnopqrstuvwx", .rev = "2222222222222", .data = cid }, &key);
            const public = try key.publicKey();
            const commit = try zat.cbor.decodeAll(a, signed.bytes);
            try zat.verifyCommitSignature(a, commit, .{ .key_type = .p256, .raw = &public }, "did:plc:abcdefghijklmnopqrstuvwx");
            if (zat.verifyCommitSignature(a, commit, .{ .key_type = .p256, .raw = &public }, "did:plc:wrong")) |_| return case.fail("commit accepts wrong DID") else |_| {}
            case.event("both curves reject modified message");
            case.event("signed commit rejects wrong identity");
        },
    }
    tally.finish(bytes.len);
}

pub fn main() !void {
    inline for (std.meta.tags(Kind)) |kind| {
        const selected = std.c.getenv("PBT_TARGET");
        if (selected == null or std.mem.eql(u8, std.mem.span(selected.?), @tagName(kind))) {
            std.debug.print("property: {s}\n", .{@tagName(kind)});
            hegel.run(.{ .key = @tagName(kind) }, kind, property) catch |err| {
                tally.print();
                return err;
            };
        }
    }
    tally.print();
}