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

zat.dev/zat

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

0
0
329 lines · 16.5 KB Raw History
const std = @import("std");
const zat = @import("zat");
const hegel = @import("hegel");
const sim = @import("sim_io.zig");

const Rule = enum { plc, web, handle };
var tally: hegel.Tally(Rule) = .{};

const plc_dids = [_][]const u8{ "did:plc:abcdefghijklmnopqrstuvwx", "did:plc:zyxwvutsrqponmlkjihgfedc" };
const web_hosts = [_][]const u8{ "alice.example.com", "bob.example.org" };
const handles = [_][]const u8{ "alice.test", "bob.example.com" };

const Class = enum { routable, unsafe, malformed };

const addresses = [_]struct { record: u8, data: []const u8, class: Class }{
    .{ .record = 1, .data = "34.1.2.3", .class = .routable },
    .{ .record = 1, .data = "151.101.1.1", .class = .routable },
    .{ .record = 1, .data = "127.0.0.1", .class = .unsafe },
    .{ .record = 1, .data = "10.20.30.40", .class = .unsafe },
    .{ .record = 1, .data = "169.254.169.254", .class = .unsafe },
    .{ .record = 1, .data = "100.100.1.1", .class = .unsafe },
    .{ .record = 1, .data = "192.168.1.1", .class = .unsafe },
    .{ .record = 1, .data = "0.0.0.0", .class = .unsafe },
    .{ .record = 1, .data = "255.255.255.255", .class = .unsafe },
    .{ .record = 1, .data = "localhost.localdomain", .class = .malformed },
    .{ .record = 1, .data = "internal.example", .class = .malformed },
    .{ .record = 28, .data = "2606:4700::1111", .class = .routable },
    .{ .record = 28, .data = "::1", .class = .unsafe },
    .{ .record = 28, .data = "fd00::1", .class = .unsafe },
    .{ .record = 28, .data = "fe80::1", .class = .unsafe },
    .{ .record = 28, .data = "::ffff:10.0.0.1", .class = .unsafe },
    .{ .record = 28, .data = "2001:db8::1", .class = .unsafe },
    .{ .record = 28, .data = "3fff::1", .class = .unsafe },
    .{ .record = 5, .data = "alias.example.net.", .class = .routable },
};

const Reply = union(enum) {
    answers: []const usize,
    status: u16,
    garbage,
    fault: sim.Fault,
};

const World = struct {
    a: std.mem.Allocator,
    plc_reply: union(enum) { document: []const u8, status: u16, garbage, fault: sim.Fault } = .{ .status = 404 },
    a_reply: Reply = .garbage,
    aaaa_reply: Reply = .garbage,
    txt_reply: Reply = .garbage,
    txt_records: []const []const u8 = &.{},
    doh_queries: std.ArrayList([]const u8) = .empty,
    bad_wire: bool = false,

    fn handle(raw: *anyopaque, request: sim.Request) sim.Response {
        const self: *World = @ptrCast(@alignCast(raw));
        if (std.mem.eql(u8, request.host, "plc.sim")) return switch (self.plc_reply) {
            .document => |body| .{ .body = body, .headers = "content-type: application/json\r\n" },
            .status => |status| .{ .status = status },
            .garbage => .{ .body = "{\"id\":" },
            .fault => |fault| .{ .body = "{\"id\":\"did:plc:abcdefghijklmnopqrstuvwx\"}", .fault = fault },
        };
        if (!std.mem.eql(u8, request.header("accept") orelse "", "application/dns-json")) self.bad_wire = true;
        self.doh_queries.append(self.a, self.a.dupe(u8, request.target) catch "") catch {};
        const record_type = request.target[(std.mem.lastIndexOf(u8, request.target, "type=") orelse return .{ .status = 400 }) + 5 ..];
        const reply = if (std.mem.eql(u8, record_type, "A")) self.a_reply else if (std.mem.eql(u8, record_type, "AAAA")) self.aaaa_reply else self.txt_reply;
        return switch (reply) {
            .status => |status| .{ .status = status },
            .garbage => .{ .body = "<html>" },
            .fault => |fault| .{ .body = "{\"Status\":0,\"TC\":false,\"RD\":true,\"RA\":true,\"AD\":false,\"CD\":false}", .fault = fault },
            .answers => |indices| .{ .body = self.dohBody(indices, std.mem.eql(u8, record_type, "TXT")) catch "" },
        };
    }

    fn dohBody(self: *World, indices: []const usize, txt: bool) ![]const u8 {
        var out: std.Io.Writer.Allocating = .init(self.a);
        try out.writer.writeAll("{\"Status\":0,\"TC\":false,\"RD\":true,\"RA\":true,\"AD\":false,\"CD\":false,\"Comment\":\"sim\",\"Answer\":[");
        if (txt) {
            for (self.txt_records, 0..) |record, index| {
                if (index != 0) try out.writer.writeByte(',');
                try out.writer.print("{{\"name\":\"_atproto\",\"type\":16,\"TTL\":60,\"data\":{f}}}", .{std.json.fmt(record, .{})});
            }
        } else {
            for (indices, 0..) |pick, index| {
                if (index != 0) try out.writer.writeByte(',');
                const entry = addresses[pick];
                try out.writer.print("{{\"name\":\"host\",\"type\":{d},\"TTL\":60,\"data\":\"{s}\"}}", .{ entry.record, entry.data });
            }
        }
        try out.writer.writeAll("]}");
        return out.written();
    }
};

var rotation: usize = 0;

fn isolated(case: *hegel.TestCase, a: std.mem.Allocator, record: u8) !Reply {
    var same: [addresses.len]usize = undefined;
    var count: usize = 0;
    for (addresses, 0..) |entry, index| {
        if (entry.record != record) continue;
        same[count] = index;
        count += 1;
    }
    const picks = try a.alloc(usize, 1);
    rotation += 1;
    picks[0] = same[(rotation + try case.index(count)) % count];
    return .{ .answers = picks };
}

fn routable(case: *hegel.TestCase, a: std.mem.Allocator, record: u8) !Reply {
    const picks = try a.alloc(usize, try case.int(usize, 1, 2));
    for (picks) |*pick| pick.* = if (record == 1) 0 else 11;
    if (try case.boolean()) picks[picks.len - 1] = 18;
    if (record == 1) picks[0] = 1 - @min(1, try case.index(2));
    return .{ .answers = picks };
}

fn drawReply(case: *hegel.TestCase, a: std.mem.Allocator, record: u8) !Reply {
    switch (try case.int(u8, 0, 11)) {
        10, 11 => return isolated(case, a, record),
        0 => return .{ .status = 500 },
        1 => return .garbage,
        2 => return .{ .fault = .reset_before_response },
        3, 4, 5 => return routable(case, a, record),
        else => {
            const picks = try a.alloc(usize, try case.int(usize, 0, 3));
            for (picks) |*pick| pick.* = try case.index(addresses.len);
            return .{ .answers = picks };
        },
    }
}

fn document(a: std.mem.Allocator, id: []const u8) ![]const u8 {
    return std.fmt.allocPrint(a,
        \\{{"@context":["https://www.w3.org/ns/did/v1"],"id":"{s}","alsoKnownAs":["at://alice.test"],"verificationMethod":[{{"id":"{s}#atproto","type":"Multikey","controller":"{s}","publicKeyMultibase":"zQ3shXjHeiBuRCKmM36cuYnm7YEMzhGnCmCyW92sRJ9pribSF"}}],"service":[{{"id":"#atproto_pds","type":"AtprotoPersonalDataServer","serviceEndpoint":"https://pds.example"}}]}}
    , .{ id, id, id });
}

const Preflight = enum { unsafe, dns_failed, passed };

fn expectPreflight(a_reply: Reply, aaaa_reply: Reply) Preflight {
    var saw_address = false;
    var saw_a = false;
    for ([_]Reply{ a_reply, aaaa_reply }, 0..) |reply, query| {
        const picks = switch (reply) {
            .answers => |picks| picks,
            else => return .dns_failed,
        };
        for (picks) |pick| {
            const entry = addresses[pick];
            if (entry.record == 5) continue;
            saw_address = true;
            if (query == 0 and entry.record == 1) saw_a = true;
            switch (entry.class) {
                .routable => {},
                .unsafe => return .unsafe,
                .malformed => return .dns_failed,
            }
        }
    }
    if (!saw_address or !saw_a) return .dns_failed;
    return .passed;
}

fn property(_: void, case: *hegel.TestCase) !void {
    var arena: std.heap.ArenaAllocator = .init(std.heap.page_allocator);
    defer arena.deinit();
    const a = arena.allocator();
    var io_sim = sim.SimIo.init(try case.int(u32, 0, std.math.maxInt(u32)), 1_800_000_000);
    var world: World = .{ .a = a };
    var network = sim.Network.init(a, &world, World.handle);
    network.max_read = try case.int(usize, 1, 512);
    try network.addHost("plc.sim", .{ 34, 2, 0, 1 });
    try network.addHost("doh.sim", .{ 34, 2, 0, 2 });
    io_sim.network = &network;

    var dids = zat.DidResolver.initWithOptions(io_sim.io(), a, .{ .keep_alive = try case.boolean() });
    defer dids.deinit();
    dids.plc_url = "http://plc.sim";
    dids.doh_endpoint = "http://doh.sim/dns-query";
    var handle_resolver = zat.HandleResolver.init(io_sim.io(), a);
    defer handle_resolver.deinit();
    handle_resolver.doh_endpoint = "http://doh.sim/dns-query";
    sim.withoutGuards(&dids.transport);
    sim.withoutGuards(&handle_resolver.transport);

    rotation = try case.int(usize, 0, addresses.len);
    var machine = try case.machine(Rule, &.{ 2, 3, 2 }, 10);
    defer machine.deinit();
    tally.case();
    while (try machine.next()) |rule| {
        tally.step(rule);
        world.doh_queries.clearRetainingCapacity();
        switch (rule) {
            .plc => {
                const did = plc_dids[try case.index(plc_dids.len)];
                const served = plc_dids[try case.index(plc_dids.len)];
                world.plc_reply = switch (try case.int(u8, 0, 5)) {
                    0 => .{ .status = 404 },
                    1 => .garbage,
                    2 => .{ .fault = .reset_before_response },
                    else => .{ .document = try document(a, served) },
                };
                case.note("plc resolve {s}, server {any} for {s}", .{ did, std.meta.activeTag(world.plc_reply), served });
                const result = dids.resolve(zat.Did.parse(did).?);
                if (result) |doc| {
                    if (world.plc_reply != .document) return case.fail("PLC resolution succeeded without a document");
                    if (!std.mem.eql(u8, doc.id, did)) return case.fail("resolver returned a document for a different DID");
                    case.event("PLC document resolved");
                } else |err| {
                    if (err == error.OutOfMemory) return err;
                    if (world.plc_reply == .document and std.mem.eql(u8, served, did)) return case.fail("PLC resolution rejected a valid document");
                    case.event("PLC resolution refused");
                }
            },
            .web => {
                const host = web_hosts[try case.index(web_hosts.len)];
                if (try case.boolean()) {
                    const v4 = try case.boolean();
                    world.a_reply = if (v4) try isolated(case, a, 1) else try routable(case, a, 1);
                    world.aaaa_reply = if (v4) try routable(case, a, 28) else try isolated(case, a, 28);
                    case.event("one address judged in isolation");
                } else {
                    world.a_reply = try drawReply(case, a, 1);
                    world.aaaa_reply = try drawReply(case, a, 28);
                }
                const expected = expectPreflight(world.a_reply, world.aaaa_reply);
                case.note("did:web:{s} A={any} AAAA={any} expect {s}", .{ host, world.a_reply, world.aaaa_reply, @tagName(expected) });
                const did = try std.fmt.allocPrint(a, "did:web:{s}", .{host});
                const actual: Preflight = if (dids.resolve(zat.Did.parse(did).?)) |_|
                    return case.fail("did:web resolved without TLS in the simulation")
                else |err| switch (err) {
                    error.OutOfMemory => return err,
                    error.UnsafeIdentityHost => .unsafe,
                    error.IdentityDnsResolutionFailed => .dns_failed,
                    // macOS loads the certificate bundle before dialing, and the
                    // simulation has none, so a request that clears the
                    // preflight stops there
                    error.CertificateBundleLoadFailure => .passed,
                    // Linux dials first; the document host is not simulated, so
                    // the connect fails. it must go to an address the
                    // preflight checked, not a fresh lookup
                    error.HostUnreachable, error.NetworkUnreachable => if (dialedAnswer(network.attempted, .{ world.a_reply, world.aaaa_reply }))
                        .passed
                    else
                        return case.fail("did:web dialed an address the preflight did not check"),
                    else => return case.fail("did:web failed outside the preflight before reaching TLS"),
                };
                for (world.doh_queries.items) |target| {
                    const expected_prefix = try std.fmt.allocPrint(a, "/dns-query?name={s}&type=", .{host});
                    if (!std.mem.startsWith(u8, target, expected_prefix)) return case.fail("DoH query names a different host");
                }
                if (world.bad_wire) return case.fail("DoH query lacks the dns-json accept header");
                if (actual != expected) {
                    if (expected == .unsafe and actual == .passed) return case.fail("did:web preflight accepted a non-routable or non-literal address");
                    if (expected == .passed and actual == .unsafe) return case.fail("did:web preflight rejected a routable address");
                    return case.fail("did:web preflight outcome differs from DNS model");
                }
                switch (expected) {
                    .unsafe => case.event("did:web preflight rejected unsafe address"),
                    .dns_failed => case.event("did:web preflight found no usable DNS"),
                    .passed => case.event("did:web preflight passed to TLS"),
                }
            },
            .handle => {
                const name = handles[try case.index(handles.len)];
                world.a_reply = try drawReply(case, a, 1);
                world.aaaa_reply = try drawReply(case, a, 28);
                const pool = [_][]const u8{ "did=did:plc:abcdefghijklmnopqrstuvwx", "\"did=did:plc:zyxwvutsrqponmlkjihgfedc\"", "did=not-a-did", "v=spf1 -all", "did=did:web:alice.example.com" };
                const records = try a.alloc([]const u8, try case.int(usize, 0, 3));
                for (records) |*record| record.* = pool[try case.index(pool.len)];
                world.txt_records = records;
                world.txt_reply = switch (try case.int(u8, 0, 7)) {
                    0 => .{ .status = 500 },
                    1 => .garbage,
                    else => .{ .answers = &.{} },
                };
                var expected: ?[]const u8 = null;
                if (world.txt_reply == .answers) {
                    var count: usize = 0;
                    for (records) |record| {
                        const unquoted = std.mem.trim(u8, record, "\"");
                        if (!std.mem.startsWith(u8, unquoted, "did=")) continue;
                        count += 1;
                        expected = unquoted[4..];
                    }
                    if (count != 1 or zat.Did.parse(expected.?) == null) expected = null;
                }
                case.note("handle {s} TXT={any} records={any} expect {?s}", .{ name, std.meta.activeTag(world.txt_reply), records, expected });
                const result = handle_resolver.resolve(zat.Handle.parse(name).?);
                if (result) |did| {
                    if (expected == null or !std.mem.eql(u8, did, expected.?)) return case.fail("handle resolved to a DID the TXT records do not name exactly once");
                    case.event("handle resolved through DNS TXT");
                } else |err| {
                    if (err == error.OutOfMemory) return err;
                    if (err == error.UnsafeIdentityHost) {
                        if (expectPreflight(world.a_reply, world.aaaa_reply) != .unsafe) return case.fail("handle refused as unsafe without an unsafe address");
                        case.event("handle refused for unsafe well-known host");
                    } else {
                        if (expected != null) return case.fail("handle with one valid did= record failed to resolve");
                        case.event("handle resolution refused");
                    }
                }
            },
        }
    }
    tally.finish(network.requests);
}

pub fn main() !void {
    defer tally.print();
    try hegel.run(.{ .key = "identity" }, {}, property);
}

fn dialedAnswer(attempted: ?std.Io.net.IpAddress, replies: [2]Reply) bool {
    const dialed = attempted orelse return false;
    for (replies) |reply| switch (reply) {
        .answers => |picks| for (picks) |pick| {
            const answer = std.Io.net.IpAddress.parse(addresses[pick].data, 0) catch continue;
            const same = switch (dialed) {
                .ip4 => |ip| answer == .ip4 and std.mem.eql(u8, &ip.bytes, &answer.ip4.bytes),
                .ip6 => |ip| answer == .ip6 and std.mem.eql(u8, &ip.bytes, &answer.ip6.bytes),
            };
            if (same) return true;
        },
        else => {},
    };
    return false;
}