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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
//! Handle Resolver - resolve handles to DIDs
//!
//! resolves AT Protocol handles via HTTP:
//! https://{handle}/.well-known/atproto-did
//!
//! DNS TXT resolution uses DNS-over-HTTPS because Zig stdlib does not expose
//! direct TXT lookup. the same path resolves an NSID's lexicon authority
//! (`_lexicon.<reversed authority>` TXT `did=`).
//!
//! see: https://atproto.com/specs/handle, https://atproto.com/specs/lexicon
const std = @import("std");
const Handle = @import("../syntax/handle.zig").Handle;
const Nsid = @import("../syntax/nsid.zig").Nsid;
const Did = @import("../syntax/did.zig").Did;
const HttpTransport = @import("zttp").Client;
const network_safety = @import("network_safety.zig");
const max_handle_response_size = 8 * 1024;
const max_dns_txt_response_size = 1 * 1024 * 1024;
pub const HandleResolver = struct {
allocator: std.mem.Allocator,
transport: HttpTransport,
doh_endpoint: []const u8,
pub fn init(io: std.Io, allocator: std.mem.Allocator) HandleResolver {
return .{
.allocator = allocator,
.transport = HttpTransport.initWithUserAgent(io, allocator, @import("../xrpc/user_agent.zig").default_user_agent),
.doh_endpoint = "https://cloudflare-dns.com/dns-query",
};
}
pub fn deinit(self: *HandleResolver) void {
self.transport.deinit();
}
/// resolve a handle to a DID via HTTP well-known
pub fn resolve(self: *HandleResolver, handle: Handle) ![]const u8 {
// Reserved TLDs must fail resolution outright (handle spec).
if (handle.hasDisallowedTld()) return error.DisallowedTld;
if (self.resolveHttp(handle)) |did| {
return did;
} else |err| switch (err) {
error.UnsafeIdentityHost, error.Canceled, error.OutOfMemory => return err,
else => return try self.resolveDns(handle),
}
}
/// resolve via HTTP at https://{handle}/.well-known/atproto-did
fn resolveHttp(self: *HandleResolver, handle: Handle) ![]const u8 {
const url = try std.fmt.allocPrint(
self.allocator,
"https://{s}/.well-known/atproto-did",
.{handle.str()},
);
defer self.allocator.free(url);
var checked_url = network_safety.resolveIdentityUrl(
self.allocator,
&self.transport,
self.doh_endpoint,
url,
) catch |err| switch (err) {
error.OutOfMemory => |e| return e,
error.UnsafeIdentityHost => |e| return e,
else => return error.HttpResolutionFailed,
};
defer checked_url.deinit(self.allocator);
const result = self.transport.fetch(.{
.url = url,
.max_response_size = max_handle_response_size,
.on_redirect = .refuse,
.resolved_connection = checked_url.resolvedConnection(),
}) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
else => return error.HttpResolutionFailed,
};
defer self.allocator.free(result.body);
if (result.status != .ok) {
return error.HttpResolutionFailed;
}
// response body should be the DID as plain text
const did_str = std.mem.trim(u8, result.body, &std.ascii.whitespace);
// validate it's a proper DID
if (Did.parse(did_str) == null) {
return error.InvalidDidInResponse;
}
return try self.allocator.dupe(u8, did_str);
}
/// resolve via DoH default: https://cloudflare-dns.com/dns-query
pub fn resolveDns(self: *HandleResolver, handle: Handle) ![]const u8 {
const dns_name = try std.fmt.allocPrint(
self.allocator,
"_atproto.{s}",
.{handle.str()},
);
defer self.allocator.free(dns_name);
return self.resolveTxtDid(dns_name);
}
/// resolve the DID that publishes an NSID's lexicons: the `did=` TXT
/// record at `_lexicon.<authority domain>` ("app.bsky.feed.post" looks up
/// `_lexicon.feed.bsky.app`), over the same DoH endpoint as `resolveDns`.
/// per the lexicon spec no other name is tried when that lookup fails.
/// caller owns the returned DID.
pub fn resolveLexiconAuthority(self: *HandleResolver, nsid: Nsid) ![]const u8 {
var buf: [Nsid.max_length]u8 = undefined;
const dns_name = try std.fmt.allocPrint(
self.allocator,
"_lexicon.{s}",
.{nsid.authorityDomain(&buf)},
);
defer self.allocator.free(dns_name);
return self.resolveTxtDid(dns_name);
}
/// look up `dns_name`'s TXT records over DoH and return its one `did=` value
fn resolveTxtDid(self: *HandleResolver, dns_name: []const u8) ![]const u8 {
const url = try std.fmt.allocPrint(
self.allocator,
"{s}?name={s}&type=TXT",
.{ self.doh_endpoint, dns_name },
);
defer self.allocator.free(url);
const result = self.transport.fetch(.{
.url = url,
.accept = "application/dns-json",
.max_response_size = max_dns_txt_response_size,
.on_redirect = .refuse,
}) catch |err| switch (err) {
error.Canceled, error.OutOfMemory => |e| return e,
else => return error.DnsResolutionFailed,
};
defer self.allocator.free(result.body);
if (result.status != .ok) {
return error.DnsResolutionFailed;
}
return self.didFromDohBody(result.body);
}
/// parse a Cloudflare DoH JSON body and extract exactly one valid `did=` TXT value.
fn didFromDohBody(self: *HandleResolver, body: []const u8) ![]const u8 {
// Cloudflare appends an unknown `Comment` field for DNSSEC zones, so the
// parse must tolerate fields `DnsResponse` doesn't declare.
const parsed = std.json.parseFromSlice(
DnsResponse,
self.allocator,
body,
.{ .ignore_unknown_fields = true },
) catch return error.InvalidDnsResponse;
defer parsed.deinit();
const dns_response = parsed.value;
if (dns_response.Answer == null or dns_response.Answer.?.len == 0) {
return error.NoDnsRecordsFound;
}
var found: ?[]const u8 = null;
var found_count: usize = 0;
for (dns_response.Answer.?) |answer| {
const data = answer.data orelse continue;
const did_str = extractDidFromTxt(data) orelse continue;
found_count += 1;
found = did_str;
}
if (found_count != 1) {
return error.NoValidDidFound;
}
const did_str = found.?;
if (Did.parse(did_str) == null) {
return error.NoValidDidFound;
}
return try self.allocator.dupe(u8, did_str);
}
};
fn extractDidFromTxt(txt_data: []const u8) ?[]const u8 {
var data = txt_data;
if (data.len >= 2 and data[0] == '"' and data[data.len - 1] == '"') {
data = data[1 .. data.len - 1];
}
const prefix = "did=";
if (std.mem.startsWith(u8, data, prefix)) {
return data[prefix.len..];
}
return null;
}
const DnsResponse = struct {
Status: i32,
TC: bool,
RD: bool,
RA: bool,
AD: bool,
CD: bool,
Question: ?[]Question = null,
Answer: ?[]Answer = null,
};
const Question = struct {
name: []const u8,
type: i32,
};
const Answer = struct {
name: []const u8,
type: i32,
TTL: i32,
data: ?[]const u8 = null,
};
// === integration tests ===
// these actually hit the network - run with: zig test src/internal/handle_resolver.zig
test "didFromDohBody tolerates Cloudflare DNSSEC Comment field" {
var resolver = HandleResolver.init(std.Options.debug_io, std.testing.allocator);
defer resolver.deinit();
// real Cloudflare DoH body for `_atproto.dholms.at`: includes a `Comment`
// field that `DnsResponse` doesn't declare (regression for strict parse).
const body =
\\{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,
\\ "Question":[{"name":"_atproto.dholms.at","type":16}],
\\ "Answer":[{"name":"_atproto.dholms.at","type":16,"TTL":3600,
\\ "data":"\"did=did:plc:yk4dd2qkboz2yv6tpubpc6co\""}],
\\ "Comment":["EDE(10): RRSIGs Missing for DNSKEY at., id = 1253"]}
;
const did = try resolver.didFromDohBody(body);
defer std.testing.allocator.free(did);
try std.testing.expectEqualStrings("did:plc:yk4dd2qkboz2yv6tpubpc6co", did);
}
test "didFromDohBody requires exactly one did TXT record" {
var resolver = HandleResolver.init(std.Options.debug_io, std.testing.allocator);
defer resolver.deinit();
const single =
\\{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,
\\ "Answer":[
\\ {"name":"_atproto.example.com","type":16,"TTL":300,"data":"\"foo=bar\""},
\\ {"name":"_atproto.example.com","type":16,"TTL":300,"data":"\"did=did:plc:abc123\""}
\\ ]}
;
const did = try resolver.didFromDohBody(single);
defer std.testing.allocator.free(did);
try std.testing.expectEqualStrings("did:plc:abc123", did);
const multiple =
\\{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,
\\ "Answer":[
\\ {"name":"_atproto.example.com","type":16,"TTL":300,"data":"\"did=did:plc:abc123\""},
\\ {"name":"_atproto.example.com","type":16,"TTL":300,"data":"\"did=did:plc:def456\""}
\\ ]}
;
try std.testing.expectError(error.NoValidDidFound, resolver.didFromDohBody(multiple));
const invalid =
\\{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,
\\ "Answer":[{"name":"_atproto.example.com","type":16,"TTL":300,"data":"\"did=not-a-did\""}]}
;
try std.testing.expectError(error.NoValidDidFound, resolver.didFromDohBody(invalid));
}
test "resolveLexiconAuthority queries only _lexicon.<reversed authority>" {
const io = std.testing.io;
const allocator = std.testing.allocator;
const DohServer = struct {
listener: std.Io.net.Server,
request_line: [512]u8 = undefined,
request_line_len: usize = 0,
fn serve(self: *@This(), server_io: std.Io) void {
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);
const line = reader.interface.takeDelimiterExclusive('\n') catch return;
const n = @min(line.len, self.request_line.len);
@memcpy(self.request_line[0..n], line[0..n]);
self.request_line_len = n;
while (true) {
const header = reader.interface.takeDelimiterExclusive('\n') catch return;
if (std.mem.trim(u8, header, "\r").len == 0) break;
}
const body =
\\{"Status":0,"TC":false,"RD":true,"RA":true,"AD":false,"CD":false,
\\ "Answer":[{"name":"_lexicon.blogging.lab.dept.university.edu","type":16,"TTL":300,
\\ "data":"\"did=did:plc:ewvi7nxzyoun6zhxrhs64oiz\""}]}
;
var wbuf: [1024]u8 = undefined;
var writer = conn.writer(server_io, &wbuf);
writer.interface.print("HTTP/1.1 200 OK\r\nContent-Type: application/dns-json\r\nContent-Length: {d}\r\nConnection: close\r\n\r\n{s}", .{ body.len, body }) catch return;
writer.interface.flush() catch {};
}
};
var server: DohServer = .{
.listener = try (std.Io.net.IpAddress{ .ip4 = .loopback(0) }).listen(io, .{ .reuse_address = true }),
};
defer server.listener.deinit(io);
var task = try io.concurrent(DohServer.serve, .{ &server, io });
defer task.cancel(io);
var resolver = HandleResolver.init(io, allocator);
defer resolver.deinit();
const endpoint = try std.fmt.allocPrint(
allocator,
"http://127.0.0.1:{d}/dns-query",
.{server.listener.socket.address.getPort()},
);
defer allocator.free(endpoint);
resolver.doh_endpoint = endpoint;
const nsid = Nsid.parse("edu.university.dept.lab.blogging.getBlogPost").?;
const did = try resolver.resolveLexiconAuthority(nsid);
defer allocator.free(did);
try std.testing.expectEqualStrings("did:plc:ewvi7nxzyoun6zhxrhs64oiz", did);
try std.testing.expect(std.mem.indexOf(
u8,
server.request_line[0..server.request_line_len],
"/dns-query?name=_lexicon.blogging.lab.dept.university.edu&type=TXT ",
) != null);
}
test "resolve lexicon authority - integration" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var resolver = HandleResolver.init(std.Options.debug_io, arena.allocator());
defer resolver.deinit();
const did = resolver.resolveLexiconAuthority(Nsid.parse("app.bsky.feed.post").?) catch {
return; // network error, expected in CI
};
try std.testing.expect(Did.parse(did) != null);
}
test "resolve handle (http) - integration" {
// use arena for http client internals that may leak
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var resolver = HandleResolver.init(std.Options.debug_io, arena.allocator());
defer resolver.deinit();
// resolve a known handle that has .well-known/atproto-did
const handle = Handle.parse("jay.bsky.social") orelse return error.InvalidHandle;
const did = resolver.resolveHttp(handle) catch {
return; // network error, expected in CI
};
// should be a valid did:plc
try std.testing.expect(Did.parse(did) != null);
try std.testing.expect(std.mem.startsWith(u8, did, "did:plc:"));
}
test "resolve handle (dns over http) - integration" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var resolver = HandleResolver.init(std.Options.debug_io, arena.allocator());
defer resolver.deinit();
const handle = Handle.parse("seiso.moe") orelse return error.InvalidHandle;
const did = resolver.resolveDns(handle) catch {
return; // network error, expected in CI
};
// should be a valid DID
try std.testing.expect(Did.parse(did) != null);
try std.testing.expect(std.mem.startsWith(u8, did, "did:"));
}
test "resolve handle - integration" {
var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
defer arena.deinit();
var resolver = HandleResolver.init(std.Options.debug_io, arena.allocator());
defer resolver.deinit();
const handle = Handle.parse("jay.bsky.social") orelse return error.InvalidHandle;
const did = resolver.resolve(handle) catch {
return; // network error, expected in CI
};
// should be a valid DID
try std.testing.expect(Did.parse(did) != null);
try std.testing.expect(std.mem.startsWith(u8, did, "did:"));
}
test "resolveDns returns error.Canceled when canceled mid-response" {
const io = std.testing.io;
const allocator = std.testing.allocator;
const Origin = struct {
listener: std.Io.net.Server,
stalled: std.Io.Event = .unset,
// answers with a head that promises a body, then goes quiet until
// the client hangs up.
fn serve(self: *@This(), server_io: std.Io) void {
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: [256]u8 = undefined;
var writer = conn.writer(server_io, &wbuf);
writer.interface.writeAll("HTTP/1.1 200 OK\r\nContent-Length: 4096\r\n\r\n{") catch {};
writer.interface.flush() catch {};
self.stalled.set(server_io);
var sink: [1]u8 = undefined;
var tail = [_][]u8{&sink};
_ = reader.interface.readVec(&tail) 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 = HandleResolver.init(io, allocator);
defer resolver.deinit();
const endpoint = try std.fmt.allocPrint(
allocator,
"http://127.0.0.1:{d}/dns-query",
.{origin.listener.socket.address.getPort()},
);
defer allocator.free(endpoint);
resolver.doh_endpoint = endpoint;
const handle = Handle.parse("example.com") orelse return error.InvalidHandle;
var lookup = try io.concurrent(HandleResolver.resolveDns, .{ &resolver, handle });
try origin.stalled.wait(io);
// zttp only surfaces a cancel once it is streaming the body, so give the
// client time to get past the response head.
try io.sleep(.fromMilliseconds(200), .awake);
try std.testing.expectError(error.Canceled, lookup.cancel(io));
}
test "a handle under a reserved TLD fails resolution without a lookup" {
var resolver = HandleResolver.init(std.testing.io, std.testing.allocator);
defer resolver.deinit();
for ([_][]const u8{ "alice.local", "bob.onion", "carol.example", "dave.localhost" }) |name| {
try std.testing.expectError(error.DisallowedTld, resolver.resolve(Handle.parse(name).?));
}
}