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

zat.dev/zat

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

0
0
207 lines · 8.1 KB Raw History
//! DID Resolver - fetches and parses DID documents
//!
//! resolves did:plc via plc.directory and did:web via .well-known/did.json
//!
//! see: https://atproto.com/specs/did

const std = @import("std");
const Did = @import("../syntax/did.zig").Did;
const DidDocument = @import("did_document.zig").DidDocument;
const HttpTransport = @import("zttp").Client;
const network_safety = @import("network_safety.zig");

const max_did_document_size = 1 * 1024 * 1024;

pub const DidResolver = struct {
    allocator: std.mem.Allocator,
    transport: HttpTransport,

    /// plc directory url (default: https://plc.directory)
    plc_url: []const u8 = "https://plc.directory",
    /// DoH endpoint for did:web host safety preflight.
    doh_endpoint: []const u8 = "https://cloudflare-dns.com/dns-query",

    pub fn init(io: std.Io, allocator: std.mem.Allocator) DidResolver {
        return initWithOptions(io, allocator, .{});
    }

    pub const Options = struct {
        keep_alive: bool = true,
    };

    pub fn initWithOptions(io: std.Io, allocator: std.mem.Allocator, options: Options) DidResolver {
        var transport = HttpTransport.initWithUserAgent(io, allocator, @import("../xrpc/user_agent.zig").default_user_agent);
        transport.keep_alive = options.keep_alive;
        return .{
            .allocator = allocator,
            .transport = transport,
        };
    }

    pub fn deinit(self: *DidResolver) void {
        self.transport.deinit();
    }

    /// resolve a did to its document
    pub fn resolve(self: *DidResolver, did: Did) !DidDocument {
        return switch (did.method()) {
            .plc => try self.resolvePlc(did),
            .web => try self.resolveWeb(did),
            .other => error.UnsupportedDidMethod,
        };
    }

    /// resolve did:plc via plc.directory
    fn resolvePlc(self: *DidResolver, did: Did) !DidDocument {
        // build url: {plc_url}/{did}
        const url = try std.fmt.allocPrint(self.allocator, "{s}/{s}", .{ self.plc_url, did.raw });
        defer self.allocator.free(url);

        return try self.fetchDidDocument(did, url, null);
    }

    /// resolve did:web via .well-known
    fn resolveWeb(self: *DidResolver, did: Did) !DidDocument {
        const url = try buildDidWebDocumentUrl(self.allocator, did);
        defer self.allocator.free(url);

        var checked_url = try network_safety.resolveIdentityUrl(
            self.allocator,
            &self.transport,
            self.doh_endpoint,
            url,
        );
        defer checked_url.deinit(self.allocator);
        return try self.fetchDidDocument(did, url, checked_url.resolvedConnection());
    }

    /// fetch and parse a did document from url. The document must declare
    /// the DID it was resolved for.
    fn fetchDidDocument(
        self: *DidResolver,
        did: Did,
        url: []const u8,
        resolved_connection: ?HttpTransport.ResolvedConnection,
    ) !DidDocument {
        const result = try self.transport.fetch(.{
            .url = url,
            .max_response_size = max_did_document_size,
            .on_redirect = .refuse,
            .resolved_connection = resolved_connection,
        });
        defer self.allocator.free(result.body);

        if (result.status != .ok) {
            return error.DidResolutionFailed;
        }

        var doc = try DidDocument.parse(self.allocator, result.body);
        errdefer doc.deinit();
        if (!std.mem.eql(u8, doc.id, did.raw)) return error.DidDocumentIdMismatch;
        return doc;
    }
};

fn buildDidWebDocumentUrl(allocator: std.mem.Allocator, did: Did) ![]u8 {
    const identifier = did.identifier();
    if (identifier.len == 0 or std.mem.indexOfScalar(u8, identifier, ':') != null) {
        return error.UnsupportedDidMethod;
    }

    const authority = try @import("../syntax/percent.zig").decodeAlloc(allocator, identifier);
    defer allocator.free(authority);

    const scheme: []const u8 = if (std.mem.eql(u8, authority, "localhost") or std.mem.startsWith(u8, authority, "localhost:"))
        "http"
    else
        "https";

    return try std.fmt.allocPrint(allocator, "{s}://{s}/.well-known/did.json", .{ scheme, authority });
}

// === tests ===

test "resolve did:plc - integration" {
    var resolver = DidResolver.init(std.Options.debug_io, std.testing.allocator);
    defer resolver.deinit();

    const did = Did.parse("did:plc:z72i7hdynmk6r22z27h6tvur").?;
    var doc = resolver.resolve(did) catch {
        return; // network error, expected in CI
    };
    defer doc.deinit();

    try std.testing.expectEqualStrings("did:plc:z72i7hdynmk6r22z27h6tvur", doc.id);
    try std.testing.expect(doc.handle() != null);
}

test "did:web loopback host is rejected before fetch" {
    var resolver = DidResolver.init(std.Options.debug_io, std.testing.allocator);
    defer resolver.deinit();

    const did = Did.parse("did:web:127.0.0.1") orelse return error.SkipZigTest;
    try std.testing.expectError(error.UnsafeIdentityHost, resolver.resolve(did));
}

test "a document declaring another DID is rejected" {
    const io = std.testing.io;
    const allocator = std.testing.allocator;

    const Origin = struct {
        listener: std.Io.net.Server,

        fn serve(self: *@This(), server_io: std.Io) void {
            for ([_][]const u8{ "did:plc:zyxwvutsrqponmlkjihgfedc", "did:plc:abcdefghijklmnopqrstuvwx" }) |id| {
                var conn = self.listener.accept(server_io) catch return;
                defer conn.close(server_io);
                var rbuf: [4096]u8 = undefined;
                var reader = conn.reader(server_io, &rbuf);
                var scratch: [2048]u8 = undefined;
                var slices = [_][]u8{&scratch};
                _ = reader.interface.readVec(&slices) catch {};
                var wbuf: [512]u8 = undefined;
                var writer = conn.writer(server_io, &wbuf);
                const body_len = "{\"id\":\"\"}".len + id.len;
                writer.interface.print("HTTP/1.1 200 OK\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n{{\"id\":\"{s}\"}}", .{ body_len, id }) catch {};
                writer.interface.flush() catch {};
            }
        }
    };

    var origin: Origin = .{
        .listener = try (std.Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }),
    };
    defer origin.listener.deinit(io);
    var server = try io.concurrent(Origin.serve, .{ &origin, io });
    defer server.cancel(io);

    var resolver = DidResolver.initWithOptions(io, allocator, .{ .keep_alive = false });
    defer resolver.deinit();
    const plc_url = try std.fmt.allocPrint(allocator, "http://127.0.0.1:{d}", .{origin.listener.socket.address.getPort()});
    defer allocator.free(plc_url);
    resolver.plc_url = plc_url;

    const did = Did.parse("did:plc:abcdefghijklmnopqrstuvwx").?;
    try std.testing.expectError(error.DidDocumentIdMismatch, resolver.resolve(did));
    var doc = try resolver.resolve(did);
    defer doc.deinit();
    try std.testing.expectEqualStrings(did.raw, doc.id);
}

test "did:web url construction" {
    const simple = try buildDidWebDocumentUrl(std.testing.allocator, Did.parse("did:web:example.com").?);
    defer std.testing.allocator.free(simple);
    try std.testing.expectEqualStrings("https://example.com/.well-known/did.json", simple);

    const with_port = try buildDidWebDocumentUrl(std.testing.allocator, Did.parse("did:web:example.com%3A3000").?);
    defer std.testing.allocator.free(with_port);
    try std.testing.expectEqualStrings("https://example.com:3000/.well-known/did.json", with_port);

    const localhost = try buildDidWebDocumentUrl(std.testing.allocator, Did.parse("did:web:localhost%3A3000").?);
    defer std.testing.allocator.free(localhost);
    try std.testing.expectEqualStrings("http://localhost:3000/.well-known/did.json", localhost);

    try std.testing.expectError(error.UnsupportedDidMethod, buildDidWebDocumentUrl(std.testing.allocator, Did.parse("did:web:example.com:user:alice").?));
    try std.testing.expectError(error.InvalidPercentEncoding, buildDidWebDocumentUrl(std.testing.allocator, Did.parse("did:web:example.com%xx").?));
    try std.testing.expectError(error.InvalidPercentEncoding, buildDidWebDocumentUrl(std.testing.allocator, Did.parse("did:web:example.com%-0").?));
}