1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
//! 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").?));
}