@fedify/webfinger 2.5.0-dev.2664 → 2.5.0-dev.2710

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1644 +0,0 @@
1
- import { createTestMeterProvider, test } from "@fedify/fixture";
2
- import { UrlError } from "@fedify/vocab-runtime";
3
- import { configure, type LogRecord, reset } from "@logtape/logtape";
4
- import { withTimeout } from "es-toolkit";
5
- import fetchMock from "fetch-mock";
6
- import { deepStrictEqual, ok } from "node:assert/strict";
7
- import type { ResourceDescriptor } from "./jrd.ts";
8
- import {
9
- lookupWebFinger,
10
- type LookupWebFingerOptions,
11
- lookupWebFingerWithDependencies,
12
- type WebFingerLookupOutcome,
13
- } from "./lookup.ts";
14
- import {
15
- type LookupWebFingerDependencies,
16
- lookupWebFingerInternal,
17
- } from "./lookup-impl.ts";
18
- import {
19
- openDirectFetch,
20
- openPublicFetch,
21
- type PublicFetchSession,
22
- } from "@fedify/vocab-runtime/internal";
23
- import type { LookupAddress } from "node:dns";
24
- import { test as nodeTest } from "node:test";
25
-
26
- // Inject only the transport boundary, so the public tracing and metrics
27
- // wrapper remains under test while fetch-mock sees the original hostname.
28
- function lookupMock(
29
- resource: URL | string,
30
- options: LookupWebFingerOptions & { withDiagnostics: true },
31
- ): Promise<WebFingerLookupOutcome>;
32
- function lookupMock(
33
- resource: URL | string,
34
- options?: LookupWebFingerOptions & { withDiagnostics?: false },
35
- ): Promise<ResourceDescriptor | null>;
36
- function lookupMock(
37
- resource: URL | string,
38
- options: LookupWebFingerOptions & { withDiagnostics?: boolean } = {},
39
- ): Promise<ResourceDescriptor | null | WebFingerLookupOutcome> {
40
- if (resource.toString().includes("fedify-test.internal")) {
41
- return lookupWebFingerWithDependencies(resource, options, {
42
- openHop: (url) =>
43
- Promise.resolve({
44
- url: new URL(url),
45
- fetch: () => Promise.reject(new TypeError("Connection refused")),
46
- close: () => Promise.resolve(),
47
- }),
48
- });
49
- }
50
- return lookupWebFingerWithDependencies(resource, options, {
51
- openHop: options.allowPrivateAddress === true
52
- ? openDirectFetch
53
- : openExampleDirectly,
54
- });
55
- }
56
-
57
- function lookupDirect(
58
- resource: URL | string,
59
- options?: LookupWebFingerOptions,
60
- ): Promise<ResourceDescriptor | null> {
61
- return lookupWebFingerWithDependencies(resource, options, {
62
- openHop: openDirectFetch,
63
- });
64
- }
65
-
66
- function lookupResolving(
67
- addresses: readonly LookupAddress[],
68
- ): (hostname: string) => Promise<readonly LookupAddress[]> {
69
- return () => Promise.resolve(addresses);
70
- }
71
-
72
- function openExampleDirectly(url: string): Promise<PublicFetchSession> {
73
- return new URL(url).hostname === "example.com"
74
- ? openDirectFetch(url)
75
- : openPublicFetch(url, {
76
- lookup: lookupResolving([{ address: "93.184.215.14", family: 4 }]),
77
- });
78
- }
79
-
80
- async function lookupResourceWithDependencies(
81
- resource: URL | string,
82
- options: LookupWebFingerOptions,
83
- deps: LookupWebFingerDependencies,
84
- ): Promise<ResourceDescriptor | null> {
85
- return (await lookupWebFingerInternal(resource, options, deps)).resource;
86
- }
87
-
88
- test({
89
- name: "lookupWebFinger()",
90
- sanitizeOps: false,
91
- sanitizeResources: false,
92
- async fn(t) {
93
- const responseTimers: ReturnType<typeof setTimeout>[] = [];
94
- await t.step("invalid resource", async () => {
95
- deepStrictEqual(await lookupMock("acct:johndoe"), null);
96
- deepStrictEqual(await lookupMock(new URL("acct:johndoe")), null);
97
- deepStrictEqual(await lookupMock("acct:johndoe@"), null);
98
- deepStrictEqual(await lookupMock(new URL("acct:johndoe@")), null);
99
- // Per RFC 7565, the acct: authority is bare `host`: no path,
100
- // query, or fragment is allowed. Reject such inputs rather than
101
- // forwarding them to a remote WebFinger lookup.
102
- deepStrictEqual(
103
- await lookupMock("acct:johndoe@example.com/exploit"),
104
- null,
105
- );
106
- deepStrictEqual(
107
- await lookupMock("acct:johndoe@example.com?x=1"),
108
- null,
109
- );
110
- deepStrictEqual(
111
- await lookupMock("acct:johndoe@example.com#frag"),
112
- null,
113
- );
114
- });
115
-
116
- await t.step("connection refused", async () => {
117
- deepStrictEqual(
118
- await lookupMock("acct:johndoe@fedify-test.internal"),
119
- null,
120
- );
121
- deepStrictEqual(
122
- await lookupMock("https://fedify-test.internal/foo"),
123
- null,
124
- );
125
- });
126
-
127
- fetchMock.spyGlobal();
128
- // Wrap the rest of the outer test in try/finally so the global
129
- // `fetch` spy is torn down even if a t.step assertion below
130
- // throws. Matches the cleanup pattern of the metrics test
131
- // further down in this file.
132
- try {
133
- fetchMock.get(
134
- "begin:https://example.com/.well-known/webfinger?",
135
- { status: 404 },
136
- );
137
-
138
- await t.step("not found", async () => {
139
- deepStrictEqual(
140
- await lookupMock("acct:johndoe@example.com"),
141
- null,
142
- );
143
- deepStrictEqual(await lookupMock("https://example.com/foo"), null);
144
- });
145
-
146
- const expected: ResourceDescriptor = {
147
- subject: "acct:johndoe@example.com",
148
- links: [],
149
- };
150
- fetchMock.removeRoutes();
151
- fetchMock.get(
152
- "https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com",
153
- { body: expected },
154
- );
155
-
156
- await t.step("acct", async () => {
157
- deepStrictEqual(
158
- await lookupMock("acct:johndoe@example.com"),
159
- expected,
160
- );
161
- });
162
-
163
- const expected2: ResourceDescriptor = {
164
- subject: "https://example.com/foo",
165
- links: [],
166
- };
167
- fetchMock.removeRoutes();
168
- fetchMock.get(
169
- "https://example.com/.well-known/webfinger?resource=https%3A%2F%2Fexample.com%2Ffoo",
170
- { body: expected2 },
171
- );
172
-
173
- await t.step("https", async () => {
174
- deepStrictEqual(
175
- await lookupMock("https://example.com/foo"),
176
- expected2,
177
- );
178
- });
179
-
180
- const mailtoExpected: ResourceDescriptor = {
181
- subject: "mailto:juliet@example.com",
182
- links: [],
183
- };
184
- fetchMock.removeRoutes();
185
- fetchMock.get(
186
- "https://example.com/.well-known/webfinger?resource=mailto%3Ajuliet%40example.com",
187
- { body: mailtoExpected },
188
- );
189
-
190
- await t.step("mailto", async () => {
191
- // RFC 7033 permits any URI as a WebFinger resource, and RFC 7565
192
- // explicitly references `mailto:` as an example. The opaque-path
193
- // host extraction (after the last `@`) applies to `mailto:` just
194
- // like `acct:`.
195
- deepStrictEqual(
196
- await lookupMock("mailto:juliet@example.com"),
197
- mailtoExpected,
198
- );
199
- });
200
-
201
- const mailtoQueryExpected: ResourceDescriptor = {
202
- subject: "mailto:juliet@example.com?subject=Hi",
203
- links: [],
204
- };
205
- fetchMock.removeRoutes();
206
- fetchMock.get(
207
- "https://example.com/.well-known/webfinger?resource=mailto%3Ajuliet%40example.com%3Fsubject%3DHi",
208
- { body: mailtoQueryExpected },
209
- );
210
-
211
- await t.step("mailto with hfields", async () => {
212
- // RFC 6068 §2 allows `mailto:` URIs to carry `?hfields=...`
213
- // header fields and fragment identifiers. Unlike `acct:`,
214
- // those components are part of the grammar, so the lookup
215
- // must accept them and forward the full resource URI to the
216
- // WebFinger endpoint.
217
- deepStrictEqual(
218
- await lookupMock("mailto:juliet@example.com?subject=Hi"),
219
- mailtoQueryExpected,
220
- );
221
- });
222
-
223
- fetchMock.removeRoutes();
224
- fetchMock.get(
225
- "begin:https://example.com/.well-known/webfinger?",
226
- { body: "not json" },
227
- );
228
-
229
- await t.step("invalid response", async () => {
230
- deepStrictEqual(
231
- await lookupMock("acct:johndoe@example.com"),
232
- null,
233
- );
234
- });
235
-
236
- fetchMock.removeRoutes();
237
- fetchMock.get(
238
- "begin:https://localhost/.well-known/webfinger?",
239
- {
240
- subject: "acct:test@localhost",
241
- links: [
242
- {
243
- rel: "self",
244
- type: "application/activity+json",
245
- href: "https://localhost/actor",
246
- },
247
- ],
248
- },
249
- );
250
-
251
- await t.step("private address", async () => {
252
- deepStrictEqual(await lookupMock("acct:test@localhost"), null);
253
- deepStrictEqual(
254
- await lookupMock("acct:test@localhost", {
255
- allowPrivateAddress: true,
256
- }),
257
- {
258
- subject: "acct:test@localhost",
259
- links: [
260
- {
261
- rel: "self",
262
- type: "application/activity+json",
263
- href: "https://localhost/actor",
264
- },
265
- ],
266
- },
267
- );
268
- });
269
-
270
- fetchMock.removeRoutes();
271
- fetchMock.get(
272
- "begin:https://example.com/.well-known/webfinger?",
273
- {
274
- status: 302,
275
- headers: { Location: "/.well-known/webfinger2" },
276
- },
277
- );
278
- fetchMock.get(
279
- "begin:https://example.com/.well-known/webfinger2",
280
- { body: expected },
281
- );
282
-
283
- await t.step("redirection", async () => {
284
- deepStrictEqual(
285
- await lookupMock("acct:johndoe@example.com"),
286
- expected,
287
- );
288
- });
289
-
290
- fetchMock.removeRoutes();
291
- fetchMock.get(
292
- "begin:https://example.com/.well-known/webfinger?",
293
- {
294
- status: 302,
295
- headers: { Location: "/.well-known/webfinger" },
296
- },
297
- );
298
-
299
- await t.step("infinite redirection", async () => {
300
- const result = await withTimeout(
301
- () => lookupMock("acct:johndoe@example.com"),
302
- 2000,
303
- );
304
- deepStrictEqual(result, null);
305
- });
306
-
307
- fetchMock.removeRoutes();
308
- fetchMock.get(
309
- "begin:https://example.com/.well-known/webfinger?",
310
- {
311
- status: 302,
312
- headers: { Location: "ftp://example.com/" },
313
- },
314
- );
315
-
316
- await t.step("redirection to different protocol", async () => {
317
- deepStrictEqual(
318
- await lookupMock("acct:johndoe@example.com"),
319
- null,
320
- );
321
- });
322
-
323
- fetchMock.removeRoutes();
324
- fetchMock.get(
325
- "begin:https://example.com/.well-known/webfinger?",
326
- {
327
- status: 302,
328
- headers: { Location: "https://localhost/" },
329
- },
330
- );
331
-
332
- await t.step("redirection to private address", async () => {
333
- deepStrictEqual(
334
- await lookupMock("acct:johndoe@example.com"),
335
- null,
336
- );
337
- });
338
-
339
- fetchMock.removeRoutes();
340
- let redirectCount = 0;
341
- fetchMock.get(
342
- "begin:https://example.com/.well-known/webfinger",
343
- () => {
344
- redirectCount++;
345
- if (redirectCount < 3) {
346
- return {
347
- status: 302,
348
- headers: {
349
- Location: `/.well-known/webfinger?redirect=${redirectCount}`,
350
- },
351
- };
352
- }
353
- return { body: expected };
354
- },
355
- );
356
-
357
- await t.step("custom maxRedirection", async () => {
358
- // Test with maxRedirection: 1 (should fail; mock has 2 redirects)
359
- redirectCount = 0;
360
- deepStrictEqual(
361
- await lookupMock("acct:johndoe@example.com", {
362
- maxRedirection: 1,
363
- }),
364
- null,
365
- );
366
-
367
- // Test with maxRedirection: 2 (should succeed; mock has exactly 2
368
- // redirects, and `maxRedirection: N` follows up to N redirects)
369
- redirectCount = 0;
370
- deepStrictEqual(
371
- await lookupMock("acct:johndoe@example.com", {
372
- maxRedirection: 2,
373
- }),
374
- expected,
375
- );
376
-
377
- // Test with maxRedirection: 3 (should succeed)
378
- redirectCount = 0;
379
- deepStrictEqual(
380
- await lookupMock("acct:johndoe@example.com", {
381
- maxRedirection: 3,
382
- }),
383
- expected,
384
- );
385
-
386
- // Test with default maxRedirection: 5 (should succeed)
387
- redirectCount = 0;
388
- deepStrictEqual(
389
- await lookupMock("acct:johndoe@example.com"),
390
- expected,
391
- );
392
- });
393
-
394
- // Regression: `maxRedirection: 1` must allow exactly one 302 to be
395
- // followed. An earlier implementation incremented the counter before
396
- // the `>=` check, so `maxRedirection: 1` rejected the first redirect
397
- // instead of following it. The expected semantics is "follow up to
398
- // N redirects".
399
- await t.step(
400
- "maxRedirection: 1 follows exactly one redirect",
401
- async () => {
402
- // Mock with a single redirect: 302 → 200. Under the corrected
403
- // semantics, `maxRedirection: 1` follows it and reaches the body.
404
- fetchMock.removeRoutes();
405
- let count = 0;
406
- fetchMock.get(
407
- "begin:https://example.com/.well-known/webfinger",
408
- () => {
409
- count++;
410
- return count < 2
411
- ? {
412
- status: 302,
413
- headers: { Location: "/.well-known/webfinger?after=1" },
414
- }
415
- : { body: expected };
416
- },
417
- );
418
- deepStrictEqual(
419
- await lookupMock("acct:johndoe@example.com", {
420
- maxRedirection: 1,
421
- }),
422
- expected,
423
- );
424
-
425
- // Mock with two redirects. `maxRedirection: 1` rejects the
426
- // second redirect.
427
- fetchMock.removeRoutes();
428
- count = 0;
429
- fetchMock.get(
430
- "begin:https://example.com/.well-known/webfinger",
431
- () => {
432
- count++;
433
- return count < 3
434
- ? {
435
- status: 302,
436
- headers: {
437
- Location: `/.well-known/webfinger?after=${count}`,
438
- },
439
- }
440
- : { body: expected };
441
- },
442
- );
443
- deepStrictEqual(
444
- await lookupMock("acct:johndoe@example.com", {
445
- maxRedirection: 1,
446
- }),
447
- null,
448
- );
449
- },
450
- );
451
-
452
- fetchMock.removeRoutes();
453
- fetchMock.get(
454
- "begin:https://example.com/.well-known/webfinger?",
455
- () =>
456
- new Promise((resolve) => {
457
- const timeoutId = setTimeout(() => {
458
- resolve({ body: expected });
459
- }, 1000);
460
-
461
- responseTimers.push(timeoutId);
462
- }),
463
- );
464
-
465
- await t.step("request cancellation", async () => {
466
- // Test cancelling a request immediately using AbortController
467
- const controller = new AbortController();
468
- const promise = lookupMock("acct:johndoe@example.com", {
469
- signal: controller.signal,
470
- });
471
-
472
- // Abort the request right after starting it
473
- controller.abort();
474
- deepStrictEqual(await promise, null);
475
- });
476
-
477
- fetchMock.removeRoutes();
478
- let redirectCount2 = 0;
479
- fetchMock.get(
480
- "begin:https://example.com/.well-known/webfinger",
481
- () => {
482
- redirectCount2++;
483
- if (redirectCount2 === 1) {
484
- return {
485
- status: 302,
486
- headers: { Location: "/.well-known/webfinger2" },
487
- };
488
- }
489
- return new Promise((resolve) => {
490
- const timeoutId = setTimeout(() => {
491
- resolve({ body: expected });
492
- }, 1000);
493
-
494
- responseTimers.push(timeoutId);
495
- });
496
- },
497
- );
498
-
499
- await t.step("cancellation during redirection", async () => {
500
- // Test cancelling a request during redirection process
501
- const controller = new AbortController();
502
- const promise = lookupMock("acct:johndoe@example.com", {
503
- signal: controller.signal,
504
- });
505
-
506
- // Cancel during the delayed second request after redirection
507
- setTimeout(() => controller.abort(), 100);
508
- deepStrictEqual(await promise, null);
509
- });
510
-
511
- fetchMock.removeRoutes();
512
- fetchMock.get(
513
- "begin:https://example.com/.well-known/webfinger?",
514
- () =>
515
- new Promise((resolve) => {
516
- const timeoutId = setTimeout(() => {
517
- resolve({ body: expected });
518
- }, 500);
519
-
520
- responseTimers.push(timeoutId);
521
- }),
522
- );
523
-
524
- await t.step("cancellation with immediate abort", async () => {
525
- // Test starting a request with an already aborted AbortController
526
- const controller = new AbortController();
527
- controller.abort();
528
-
529
- // Use a signal that was already aborted before starting the request
530
- const result = await lookupMock("acct:johndoe@example.com", {
531
- signal: controller.signal,
532
- });
533
- deepStrictEqual(result, null);
534
- });
535
-
536
- fetchMock.removeRoutes();
537
- fetchMock.get(
538
- "begin:https://example.com/.well-known/webfinger?",
539
- { body: expected },
540
- );
541
-
542
- await t.step("successful request with signal", async () => {
543
- // Test successful request with a normal AbortController signal
544
- const controller = new AbortController();
545
- const result = await lookupMock("acct:johndoe@example.com", {
546
- signal: controller.signal,
547
- });
548
- deepStrictEqual(result, expected);
549
- });
550
- } finally {
551
- for (const timer of responseTimers) clearTimeout(timer);
552
- fetchMock.removeRoutes();
553
- fetchMock.hardReset();
554
- }
555
- },
556
- });
557
-
558
- test("lookupWebFinger() records webfinger.lookup counter and duration", {
559
- sanitizeOps: false,
560
- sanitizeResources: false,
561
- }, async (t) => {
562
- fetchMock.spyGlobal();
563
- try {
564
- const expected: ResourceDescriptor = {
565
- subject: "acct:johndoe@example.com",
566
- links: [],
567
- };
568
-
569
- await t.step(
570
- "records result=found for a successful acct lookup",
571
- async () => {
572
- fetchMock.removeRoutes();
573
- fetchMock.get(
574
- "https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com",
575
- { body: expected },
576
- );
577
- const [meterProvider, recorder] = createTestMeterProvider();
578
- const result = await lookupMock("acct:johndoe@example.com", {
579
- meterProvider,
580
- });
581
- deepStrictEqual(result, expected);
582
-
583
- const counters = recorder.getMeasurements("webfinger.lookup");
584
- deepStrictEqual(counters.length, 1);
585
- deepStrictEqual(counters[0].type, "counter");
586
- deepStrictEqual(counters[0].value, 1);
587
- deepStrictEqual(
588
- counters[0].attributes["webfinger.lookup.result"],
589
- "found",
590
- );
591
- deepStrictEqual(
592
- counters[0].attributes["webfinger.resource.scheme"],
593
- "acct",
594
- );
595
- deepStrictEqual(
596
- counters[0].attributes["activitypub.remote.host"],
597
- "example.com",
598
- );
599
- deepStrictEqual(
600
- counters[0].attributes["http.response.status_code"],
601
- 200,
602
- );
603
-
604
- const durations = recorder.getMeasurements("webfinger.lookup.duration");
605
- deepStrictEqual(durations.length, 1);
606
- deepStrictEqual(durations[0].type, "histogram");
607
- deepStrictEqual(
608
- durations[0].attributes["webfinger.lookup.result"],
609
- "found",
610
- );
611
- deepStrictEqual(
612
- durations[0].attributes["webfinger.resource.scheme"],
613
- "acct",
614
- );
615
- ok(typeof durations[0].value === "number" && durations[0].value >= 0);
616
- },
617
- );
618
-
619
- await t.step(
620
- "records scheme=https for an https resource lookup",
621
- async () => {
622
- fetchMock.removeRoutes();
623
- fetchMock.get(
624
- "https://example.com/.well-known/webfinger?resource=https%3A%2F%2Fexample.com%2Ffoo",
625
- { body: { subject: "https://example.com/foo", links: [] } },
626
- );
627
- const [meterProvider, recorder] = createTestMeterProvider();
628
- await lookupMock("https://example.com/foo", { meterProvider });
629
- const counters = recorder.getMeasurements("webfinger.lookup");
630
- deepStrictEqual(counters.length, 1);
631
- deepStrictEqual(
632
- counters[0].attributes["webfinger.resource.scheme"],
633
- "https",
634
- );
635
- deepStrictEqual(
636
- counters[0].attributes["webfinger.lookup.result"],
637
- "found",
638
- );
639
- },
640
- );
641
-
642
- await t.step(
643
- "records non-default ports for URL resources",
644
- async () => {
645
- fetchMock.removeRoutes();
646
- fetchMock.get(
647
- "https://example.com:8443/.well-known/webfinger?resource=https%3A%2F%2Fexample.com%3A8443%2Ffoo",
648
- { body: { subject: "https://example.com:8443/foo", links: [] } },
649
- );
650
- const [meterProvider, recorder] = createTestMeterProvider();
651
- await lookupMock("https://example.com:8443/foo", {
652
- meterProvider,
653
- });
654
- const counter = recorder.getMeasurement("webfinger.lookup");
655
- ok(counter != null);
656
- deepStrictEqual(
657
- counter.attributes["activitypub.remote.host"],
658
- "example.com:8443",
659
- );
660
- },
661
- );
662
-
663
- await t.step("records result=not_found with status 404", async () => {
664
- fetchMock.removeRoutes();
665
- fetchMock.get(
666
- "begin:https://example.com/.well-known/webfinger?",
667
- { status: 404 },
668
- );
669
- const [meterProvider, recorder] = createTestMeterProvider();
670
- const result = await lookupMock("acct:johndoe@example.com", {
671
- meterProvider,
672
- });
673
- deepStrictEqual(result, null);
674
-
675
- const counters = recorder.getMeasurements("webfinger.lookup");
676
- deepStrictEqual(counters.length, 1);
677
- deepStrictEqual(
678
- counters[0].attributes["webfinger.lookup.result"],
679
- "not_found",
680
- );
681
- deepStrictEqual(
682
- counters[0].attributes["http.response.status_code"],
683
- 404,
684
- );
685
- deepStrictEqual(
686
- counters[0].attributes["activitypub.remote.host"],
687
- "example.com",
688
- );
689
-
690
- const durations = recorder.getMeasurements("webfinger.lookup.duration");
691
- deepStrictEqual(durations.length, 1);
692
- deepStrictEqual(
693
- durations[0].attributes["webfinger.lookup.result"],
694
- "not_found",
695
- );
696
- });
697
-
698
- await t.step("records result=not_found with status 410", async () => {
699
- fetchMock.removeRoutes();
700
- fetchMock.get(
701
- "begin:https://example.com/.well-known/webfinger?",
702
- { status: 410 },
703
- );
704
- const [meterProvider, recorder] = createTestMeterProvider();
705
- await lookupMock("acct:johndoe@example.com", { meterProvider });
706
- const counter = recorder.getMeasurement("webfinger.lookup");
707
- ok(counter != null);
708
- deepStrictEqual(
709
- counter.attributes["webfinger.lookup.result"],
710
- "not_found",
711
- );
712
- deepStrictEqual(counter.attributes["http.response.status_code"], 410);
713
- });
714
-
715
- await t.step(
716
- "records result=error for non-2xx, non-404/410 HTTP responses",
717
- async () => {
718
- fetchMock.removeRoutes();
719
- fetchMock.get(
720
- "begin:https://example.com/.well-known/webfinger?",
721
- { status: 500 },
722
- );
723
- const [meterProvider, recorder] = createTestMeterProvider();
724
- await lookupMock("acct:johndoe@example.com", { meterProvider });
725
- const counter = recorder.getMeasurement("webfinger.lookup");
726
- ok(counter != null);
727
- deepStrictEqual(
728
- counter.attributes["webfinger.lookup.result"],
729
- "error",
730
- );
731
- deepStrictEqual(counter.attributes["http.response.status_code"], 500);
732
- },
733
- );
734
-
735
- await t.step(
736
- "records result=invalid for malformed JSON bodies",
737
- async () => {
738
- fetchMock.removeRoutes();
739
- fetchMock.get(
740
- "begin:https://example.com/.well-known/webfinger?",
741
- { body: "not json" },
742
- );
743
- const [meterProvider, recorder] = createTestMeterProvider();
744
- await lookupMock("acct:johndoe@example.com", { meterProvider });
745
- const counter = recorder.getMeasurement("webfinger.lookup");
746
- ok(counter != null);
747
- deepStrictEqual(
748
- counter.attributes["webfinger.lookup.result"],
749
- "invalid",
750
- );
751
- deepStrictEqual(counter.attributes["http.response.status_code"], 200);
752
- },
753
- );
754
-
755
- await t.step(
756
- "records result=network_error when fetch never reaches the remote",
757
- async () => {
758
- fetchMock.removeRoutes();
759
- const [meterProvider, recorder] = createTestMeterProvider();
760
- const result = await lookupMock(
761
- "acct:johndoe@fedify-test.internal",
762
- { meterProvider },
763
- );
764
- deepStrictEqual(result, null);
765
- const counter = recorder.getMeasurement("webfinger.lookup");
766
- ok(counter != null);
767
- deepStrictEqual(
768
- counter.attributes["webfinger.lookup.result"],
769
- "network_error",
770
- );
771
- deepStrictEqual(
772
- "http.response.status_code" in counter.attributes,
773
- false,
774
- "no HTTP response means no status code attribute",
775
- );
776
- deepStrictEqual(
777
- counter.attributes["activitypub.remote.host"],
778
- "fedify-test.internal",
779
- );
780
- },
781
- );
782
-
783
- await t.step(
784
- "records result=invalid for malformed acct: resources",
785
- async () => {
786
- const [meterProvider, recorder] = createTestMeterProvider();
787
- const result = await lookupMock("acct:johndoe", { meterProvider });
788
- deepStrictEqual(result, null);
789
- const counter = recorder.getMeasurement("webfinger.lookup");
790
- ok(counter != null);
791
- deepStrictEqual(
792
- counter.attributes["webfinger.lookup.result"],
793
- "invalid",
794
- );
795
- deepStrictEqual(
796
- counter.attributes["webfinger.resource.scheme"],
797
- "acct",
798
- );
799
- deepStrictEqual(
800
- "activitypub.remote.host" in counter.attributes,
801
- false,
802
- "a malformed acct resource has no usable remote host",
803
- );
804
- },
805
- );
806
-
807
- await t.step(
808
- "records result=invalid when the redirect chain exceeds maxRedirection",
809
- async () => {
810
- fetchMock.removeRoutes();
811
- // The redirect Location drops the original `?resource=...` query
812
- // string, so the second hop's URL no longer contains a `?`. The
813
- // route pattern omits the trailing `?` so it still matches.
814
- fetchMock.get(
815
- "begin:https://example.com/.well-known/webfinger",
816
- {
817
- status: 302,
818
- headers: { Location: "/.well-known/webfinger" },
819
- },
820
- );
821
- const [meterProvider, recorder] = createTestMeterProvider();
822
- const result = await withTimeout(
823
- () =>
824
- lookupMock("acct:johndoe@example.com", {
825
- meterProvider,
826
- maxRedirection: 3,
827
- }),
828
- 2000,
829
- );
830
- deepStrictEqual(result, null);
831
- const counter = recorder.getMeasurement("webfinger.lookup");
832
- ok(counter != null);
833
- deepStrictEqual(
834
- counter.attributes["webfinger.lookup.result"],
835
- "invalid",
836
- );
837
- deepStrictEqual(counter.attributes["http.response.status_code"], 302);
838
- deepStrictEqual(
839
- counter.attributes["activitypub.remote.host"],
840
- "example.com",
841
- );
842
- },
843
- );
844
-
845
- await t.step(
846
- "records result=invalid for cross-protocol redirects",
847
- async () => {
848
- fetchMock.removeRoutes();
849
- fetchMock.get(
850
- "begin:https://example.com/.well-known/webfinger?",
851
- {
852
- status: 302,
853
- headers: { Location: "ftp://example.com/" },
854
- },
855
- );
856
- const [meterProvider, recorder] = createTestMeterProvider();
857
- await lookupMock("acct:johndoe@example.com", { meterProvider });
858
- const counter = recorder.getMeasurement("webfinger.lookup");
859
- ok(counter != null);
860
- deepStrictEqual(
861
- counter.attributes["webfinger.lookup.result"],
862
- "invalid",
863
- );
864
- deepStrictEqual(counter.attributes["http.response.status_code"], 302);
865
- },
866
- );
867
-
868
- await t.step(
869
- "records result=network_error when a redirect points to a private address",
870
- async () => {
871
- fetchMock.removeRoutes();
872
- fetchMock.get(
873
- "begin:https://example.com/.well-known/webfinger?",
874
- {
875
- status: 302,
876
- headers: { Location: "https://localhost/" },
877
- },
878
- );
879
- const [meterProvider, recorder] = createTestMeterProvider();
880
- await lookupMock("acct:johndoe@example.com", { meterProvider });
881
- const counter = recorder.getMeasurement("webfinger.lookup");
882
- ok(counter != null);
883
- deepStrictEqual(
884
- counter.attributes["webfinger.lookup.result"],
885
- "network_error",
886
- );
887
- deepStrictEqual(
888
- counter.attributes["activitypub.remote.host"],
889
- "localhost",
890
- "remote.host reflects the latest URL we attempted, even after a redirect",
891
- );
892
- },
893
- );
894
-
895
- await t.step(
896
- "records result=invalid for malformed Location headers",
897
- async () => {
898
- fetchMock.removeRoutes();
899
- fetchMock.get(
900
- "begin:https://example.com/.well-known/webfinger?",
901
- {
902
- status: 302,
903
- headers: { Location: "http://[bad" },
904
- },
905
- );
906
- const [meterProvider, recorder] = createTestMeterProvider();
907
- await lookupMock("acct:johndoe@example.com", { meterProvider });
908
- const counter = recorder.getMeasurement("webfinger.lookup");
909
- ok(counter != null);
910
- deepStrictEqual(
911
- counter.attributes["webfinger.lookup.result"],
912
- "invalid",
913
- );
914
- deepStrictEqual(counter.attributes["http.response.status_code"], 302);
915
- deepStrictEqual(
916
- counter.attributes["activitypub.remote.host"],
917
- "example.com",
918
- );
919
- },
920
- );
921
-
922
- await t.step(
923
- "buckets unknown resource schemes as 'other' to keep metric cardinality bounded",
924
- async () => {
925
- // Lookups whose redirect chain ends on an unusual scheme (or a
926
- // resource the caller passes with a non-fediverse scheme) must
927
- // not leak that scheme into the metric attribute.
928
- fetchMock.removeRoutes();
929
- const [meterProvider, recorder] = createTestMeterProvider();
930
- // `ssh:` is not a WebFinger scheme; lookupWebFingerInternal will
931
- // attempt to build a host from the URL, fail, and return null.
932
- // The metric still records, and its scheme attribute must be
933
- // bucketed as `other`.
934
- await lookupMock("ssh://example.com/foo", { meterProvider });
935
- const counter = recorder.getMeasurement("webfinger.lookup");
936
- ok(counter != null);
937
- deepStrictEqual(
938
- counter.attributes["webfinger.resource.scheme"],
939
- "other",
940
- );
941
- },
942
- );
943
-
944
- await t.step(
945
- "omits measurements when no meterProvider is provided",
946
- async () => {
947
- fetchMock.removeRoutes();
948
- fetchMock.get(
949
- "https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com",
950
- { body: expected },
951
- );
952
- const [_unused, recorder] = createTestMeterProvider();
953
- await lookupMock("acct:johndoe@example.com");
954
- deepStrictEqual(
955
- recorder.getMeasurements("webfinger.lookup").length,
956
- 0,
957
- );
958
- deepStrictEqual(
959
- recorder.getMeasurements("webfinger.lookup.duration").length,
960
- 0,
961
- );
962
- },
963
- );
964
- } finally {
965
- fetchMock.removeRoutes();
966
- fetchMock.hardReset();
967
- }
968
- });
969
-
970
- // cSpell: ignore johndoe
971
-
972
- test("lookupWebFinger() bounds resource descriptors", async () => {
973
- fetchMock.mockGlobal();
974
- let oversized = true;
975
- try {
976
- fetchMock.get(
977
- "begin:https://example.com/.well-known/webfinger?",
978
- () =>
979
- new Response(
980
- '{"subject":"acct:alice@example.com"}' +
981
- (oversized ? " ".repeat(16 * 1024 * 1024) : ""),
982
- {
983
- headers: {
984
- "Content-Type": "application/jrd+json",
985
- "Content-Length": "1",
986
- },
987
- },
988
- ),
989
- );
990
- deepStrictEqual(
991
- await lookupMock("acct:alice@example.com", {
992
- allowPrivateAddress: true,
993
- }),
994
- null,
995
- );
996
- oversized = false;
997
- deepStrictEqual(
998
- await lookupMock("acct:alice@example.com", {
999
- allowPrivateAddress: true,
1000
- }),
1001
- { subject: "acct:alice@example.com" },
1002
- );
1003
- } finally {
1004
- fetchMock.hardReset();
1005
- }
1006
- });
1007
-
1008
- test("lookupWebFinger() logs DNS failures as such", async (t) => {
1009
- for (const result of ["throws", "empty", "private"] as const) {
1010
- await t.step(result, async () => {
1011
- const lookup = () =>
1012
- result === "throws"
1013
- ? Promise.reject(new Error("Resolver unavailable"))
1014
- : Promise.resolve(
1015
- result === "empty" ? [] : [{ address: "127.0.0.1", family: 4 }],
1016
- );
1017
- const records: LogRecord[] = [];
1018
- await configure({
1019
- sinks: {
1020
- buffer: (record) => records.push(record),
1021
- },
1022
- loggers: [
1023
- { category: "fedify", sinks: ["buffer"], lowestLevel: "debug" },
1024
- { category: ["logtape", "meta"], sinks: [] },
1025
- ],
1026
- reset: true,
1027
- });
1028
- try {
1029
- deepStrictEqual(
1030
- await lookupResourceWithDependencies(
1031
- "acct:alice@dns-failure.invalid",
1032
- {},
1033
- {
1034
- openHop: (url) => openPublicFetch(url, { lookup }),
1035
- },
1036
- ),
1037
- null,
1038
- );
1039
- const failures = records.filter((r) =>
1040
- r.rawMessage !==
1041
- "Fetching WebFinger resource descriptor from {url}..."
1042
- );
1043
- deepStrictEqual(
1044
- failures.map((r) => [r.level, r.rawMessage]),
1045
- [
1046
- result === "private"
1047
- ? [
1048
- "error",
1049
- "Invalid URL for WebFinger resource descriptor: {error}",
1050
- ]
1051
- : ["debug", "DNS lookup failed for {url}"],
1052
- ],
1053
- );
1054
- const { error } = failures[0].properties;
1055
- ok(error instanceof UrlError);
1056
- deepStrictEqual(
1057
- error.reason,
1058
- result === "private" ? "disallowed" : "dns",
1059
- );
1060
- } finally {
1061
- await reset();
1062
- }
1063
- });
1064
- }
1065
- });
1066
-
1067
- test("lookupWebFinger() with withDiagnostics: true", {
1068
- sanitizeOps: false,
1069
- sanitizeResources: false,
1070
- }, async (t) => {
1071
- // Inject the same failed session as the connection-refused transport test,
1072
- // so the diagnostics path does not depend on real DNS or networking.
1073
- await t.step("network_error", async () => {
1074
- const outcome = await lookupMock(
1075
- "acct:johndoe@fedify-test.internal",
1076
- { withDiagnostics: true },
1077
- );
1078
- deepStrictEqual(outcome.resource, null);
1079
- deepStrictEqual(outcome.result, "network_error");
1080
- deepStrictEqual(
1081
- "statusCode" in outcome,
1082
- false,
1083
- "no HTTP response means no status code",
1084
- );
1085
- });
1086
-
1087
- fetchMock.spyGlobal();
1088
- try {
1089
- await t.step("found", async () => {
1090
- fetchMock.removeRoutes();
1091
- const expected: ResourceDescriptor = {
1092
- subject: "acct:johndoe@example.com",
1093
- links: [],
1094
- };
1095
- fetchMock.get(
1096
- "https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com",
1097
- { body: expected },
1098
- );
1099
- const outcome = await lookupMock("acct:johndoe@example.com", {
1100
- withDiagnostics: true,
1101
- });
1102
- deepStrictEqual(outcome.resource, expected);
1103
- deepStrictEqual(outcome.result, "found");
1104
- deepStrictEqual(outcome.statusCode, 200);
1105
- deepStrictEqual(outcome.remoteHost, "example.com");
1106
- });
1107
-
1108
- await t.step("not_found", async () => {
1109
- fetchMock.removeRoutes();
1110
- fetchMock.get(
1111
- "begin:https://example.com/.well-known/webfinger?",
1112
- { status: 404 },
1113
- );
1114
- const outcome = await lookupMock("acct:johndoe@example.com", {
1115
- withDiagnostics: true,
1116
- });
1117
- deepStrictEqual(outcome.resource, null);
1118
- deepStrictEqual(outcome.result, "not_found");
1119
- deepStrictEqual(outcome.statusCode, 404);
1120
- deepStrictEqual(outcome.remoteHost, "example.com");
1121
- });
1122
-
1123
- await t.step("invalid", async () => {
1124
- fetchMock.removeRoutes();
1125
- fetchMock.get(
1126
- "begin:https://example.com/.well-known/webfinger?",
1127
- { body: "not json" },
1128
- );
1129
- const outcome = await lookupMock("acct:johndoe@example.com", {
1130
- withDiagnostics: true,
1131
- });
1132
- deepStrictEqual(outcome.resource, null);
1133
- deepStrictEqual(outcome.result, "invalid");
1134
- deepStrictEqual(outcome.statusCode, 200);
1135
- deepStrictEqual(outcome.remoteHost, "example.com");
1136
- });
1137
-
1138
- await t.step(
1139
- "invalid: a literal JSON null body is not a resource descriptor",
1140
- async () => {
1141
- // JSON.parse("null") succeeds and yields the JS value `null`.
1142
- // Regression test for a server that returns 200 with a literal
1143
- // `null` body instead of an object: this must not be classified
1144
- // as "found" with a null resource.
1145
- fetchMock.removeRoutes();
1146
- fetchMock.get(
1147
- "begin:https://example.com/.well-known/webfinger?",
1148
- { body: "null" },
1149
- );
1150
- const outcome = await lookupMock("acct:johndoe@example.com", {
1151
- withDiagnostics: true,
1152
- });
1153
- deepStrictEqual(outcome.resource, null);
1154
- deepStrictEqual(outcome.result, "invalid");
1155
- deepStrictEqual(outcome.statusCode, 200);
1156
- deepStrictEqual(outcome.remoteHost, "example.com");
1157
- },
1158
- );
1159
-
1160
- await t.step(
1161
- "invalid: a JSON array body is not a resource descriptor",
1162
- async () => {
1163
- // typeof [] === "object" and [] !== null, so the null-only guard
1164
- // above does not catch an array body; it needs its own check.
1165
- fetchMock.removeRoutes();
1166
- fetchMock.get(
1167
- "begin:https://example.com/.well-known/webfinger?",
1168
- { body: "[]" },
1169
- );
1170
- const outcome = await lookupMock("acct:johndoe@example.com", {
1171
- withDiagnostics: true,
1172
- });
1173
- deepStrictEqual(outcome.resource, null);
1174
- deepStrictEqual(outcome.result, "invalid");
1175
- deepStrictEqual(outcome.statusCode, 200);
1176
- deepStrictEqual(outcome.remoteHost, "example.com");
1177
- },
1178
- );
1179
-
1180
- await t.step("error", async () => {
1181
- fetchMock.removeRoutes();
1182
- fetchMock.get(
1183
- "begin:https://example.com/.well-known/webfinger?",
1184
- { status: 500 },
1185
- );
1186
- const outcome = await lookupMock("acct:johndoe@example.com", {
1187
- withDiagnostics: true,
1188
- });
1189
- deepStrictEqual(outcome.resource, null);
1190
- deepStrictEqual(outcome.result, "error");
1191
- deepStrictEqual(outcome.statusCode, 500);
1192
- deepStrictEqual(outcome.remoteHost, "example.com");
1193
- });
1194
- } finally {
1195
- fetchMock.removeRoutes();
1196
- fetchMock.hardReset();
1197
- }
1198
- });
1199
-
1200
- test(
1201
- "lookupWebFinger() accepts a plain LookupWebFingerOptions-typed variable",
1202
- async () => {
1203
- // Regression test: a variable typed as `LookupWebFingerOptions`, built
1204
- // separately from the call site and never mentioning `withDiagnostics`,
1205
- // must still match the default overload. This is a type-level
1206
- // concern; the point of this test is that the file compiles at all.
1207
- fetchMock.spyGlobal();
1208
- try {
1209
- const expected: ResourceDescriptor = {
1210
- subject: "acct:johndoe@example.com",
1211
- links: [],
1212
- };
1213
- fetchMock.get(
1214
- "https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com",
1215
- { body: expected },
1216
- );
1217
- const options: LookupWebFingerOptions = {
1218
- userAgent: "test-agent",
1219
- allowPrivateAddress: true,
1220
- };
1221
- const result = await lookupWebFinger(
1222
- "acct:johndoe@example.com",
1223
- options,
1224
- );
1225
- deepStrictEqual(result, expected);
1226
- } finally {
1227
- fetchMock.removeRoutes();
1228
- fetchMock.hardReset();
1229
- }
1230
- },
1231
- );
1232
-
1233
- interface FakeResponse {
1234
- readonly status?: number;
1235
- readonly headers?: Record<string, string>;
1236
- readonly body?: string;
1237
- /** The `url` of the response, as a pinned fetch reports it. */
1238
- readonly url?: string;
1239
- /** Makes cancelling the body fail. */
1240
- readonly cancelFails?: boolean;
1241
- /** Makes cancelling the body never settle. */
1242
- readonly cancelNeverSettles?: boolean;
1243
- }
1244
-
1245
- interface HopRecorder {
1246
- readonly events: string[];
1247
- readonly openHop: (url: string) => Promise<PublicFetchSession>;
1248
- /**
1249
- * Asserts that every opened session is closed, and that every response
1250
- * body was consumed or cancelled before its session was closed.
1251
- */
1252
- assertInvariants(): void;
1253
- }
1254
-
1255
- // A fake server that records the lifecycle of each session and response.
1256
- // Unlike real sessions, closing a fake session never cancels bodies, so that
1257
- // the caller's own cleanup is observed:
1258
- function recordHops(respond: (url: URL) => FakeResponse): HopRecorder {
1259
- const events: string[] = [];
1260
- const unsettled: string[] = [];
1261
- let opens = 0;
1262
- let closes = 0;
1263
- let responses = 0;
1264
- return {
1265
- events,
1266
- // oxlint-disable-next-line eslint/require-await
1267
- async openHop(url) {
1268
- opens++;
1269
- events.push(`open ${url}`);
1270
- const states: { id: number; settled: boolean }[] = [];
1271
- let closed = false;
1272
- return {
1273
- url: new URL(url),
1274
- // oxlint-disable-next-line eslint/require-await
1275
- async fetch(input) {
1276
- if (closed) throw new TypeError("The fetch session is closed.");
1277
- const target = new URL(input instanceof Request ? input.url : input);
1278
- const id = ++responses;
1279
- events.push(`fetch ${target.href} #${id}`);
1280
- const fake = respond(target);
1281
- const state = { id, settled: false };
1282
- states.push(state);
1283
- let sent = false;
1284
- const body = new ReadableStream<Uint8Array>({
1285
- pull(controller) {
1286
- if (!sent && fake.body != null && fake.body !== "") {
1287
- sent = true;
1288
- controller.enqueue(new TextEncoder().encode(fake.body));
1289
- return;
1290
- }
1291
- state.settled = true;
1292
- events.push(`consumed #${id}`);
1293
- controller.close();
1294
- },
1295
- cancel() {
1296
- state.settled = true;
1297
- events.push(`cancel #${id}`);
1298
- if (fake.cancelFails) throw new Error("Cancellation failed");
1299
- if (fake.cancelNeverSettles) return new Promise(() => {});
1300
- },
1301
- }, { highWaterMark: 0 });
1302
- const response = new Response(body, {
1303
- status: fake.status ?? 200,
1304
- headers: fake.headers,
1305
- });
1306
- if (fake.url != null) {
1307
- Object.defineProperty(response, "url", { value: fake.url });
1308
- }
1309
- return response;
1310
- },
1311
- // oxlint-disable-next-line eslint/require-await
1312
- async close() {
1313
- if (closed) return;
1314
- closed = true;
1315
- closes++;
1316
- for (const state of states) {
1317
- if (!state.settled) unsettled.push(`#${state.id}`);
1318
- }
1319
- events.push(`close ${url}`);
1320
- },
1321
- };
1322
- },
1323
- assertInvariants() {
1324
- deepStrictEqual(closes, opens);
1325
- deepStrictEqual(unsettled, []);
1326
- },
1327
- };
1328
- }
1329
-
1330
- test("lookupWebFinger() closes each hop after cleaning up its body", async (t) => {
1331
- const descriptor: ResourceDescriptor = {
1332
- subject: "acct:johndoe@example.com",
1333
- links: [],
1334
- };
1335
- const first =
1336
- "https://example.com/.well-known/webfinger?resource=acct%3Ajohndoe%40example.com";
1337
- const second = "https://example.com/.well-known/webfinger2";
1338
-
1339
- await t.step("redirect", async () => {
1340
- const recorder = recordHops((url) =>
1341
- url.pathname === "/.well-known/webfinger"
1342
- ? {
1343
- status: 302,
1344
- headers: { Location: "/.well-known/webfinger2" },
1345
- body: "redirecting",
1346
- // A pinned response's url has the IP address, which must not be
1347
- // used as the base of the Location:
1348
- url: url.href.replace("example.com", "93.184.215.14"),
1349
- }
1350
- : { body: JSON.stringify(descriptor) }
1351
- );
1352
- deepStrictEqual(
1353
- await lookupResourceWithDependencies("acct:johndoe@example.com", {}, {
1354
- openHop: recorder.openHop,
1355
- }),
1356
- descriptor,
1357
- );
1358
- deepStrictEqual(recorder.events, [
1359
- `open ${first}`,
1360
- `fetch ${first} #1`,
1361
- "cancel #1",
1362
- `close ${first}`,
1363
- `open ${second}`,
1364
- `fetch ${second} #2`,
1365
- "consumed #2",
1366
- `close ${second}`,
1367
- ]);
1368
- recorder.assertInvariants();
1369
- });
1370
-
1371
- await t.step("non-2xx response", async () => {
1372
- const recorder = recordHops(() => ({ status: 404, body: "not found" }));
1373
- deepStrictEqual(
1374
- await lookupResourceWithDependencies("acct:johndoe@example.com", {}, {
1375
- openHop: recorder.openHop,
1376
- }),
1377
- null,
1378
- );
1379
- deepStrictEqual(recorder.events, [
1380
- `open ${first}`,
1381
- `fetch ${first} #1`,
1382
- "cancel #1",
1383
- `close ${first}`,
1384
- ]);
1385
- recorder.assertInvariants();
1386
- });
1387
-
1388
- await t.step("too many redirections", async () => {
1389
- const recorder = recordHops(() => ({
1390
- status: 302,
1391
- headers: { Location: "/.well-known/webfinger2" },
1392
- body: "redirecting",
1393
- }));
1394
- deepStrictEqual(
1395
- await lookupResourceWithDependencies("acct:johndoe@example.com", {
1396
- maxRedirection: 1,
1397
- }, { openHop: recorder.openHop }),
1398
- null,
1399
- );
1400
- deepStrictEqual(recorder.events, [
1401
- `open ${first}`,
1402
- `fetch ${first} #1`,
1403
- "cancel #1",
1404
- `close ${first}`,
1405
- `open ${second}`,
1406
- `fetch ${second} #2`,
1407
- "cancel #2",
1408
- `close ${second}`,
1409
- ]);
1410
- recorder.assertInvariants();
1411
- });
1412
-
1413
- await t.step("failed redirect body cancellation", async () => {
1414
- const recorder = recordHops((url) =>
1415
- url.pathname === "/.well-known/webfinger"
1416
- ? {
1417
- status: 302,
1418
- headers: { Location: "/.well-known/webfinger2" },
1419
- body: "redirecting",
1420
- cancelFails: true,
1421
- }
1422
- : { body: JSON.stringify(descriptor) }
1423
- );
1424
- const records: LogRecord[] = [];
1425
- await configure({
1426
- sinks: { buffer: (record) => records.push(record) },
1427
- loggers: [
1428
- { category: "fedify", sinks: ["buffer"], lowestLevel: "debug" },
1429
- { category: ["logtape", "meta"], sinks: [] },
1430
- ],
1431
- reset: true,
1432
- });
1433
- try {
1434
- deepStrictEqual(
1435
- await lookupResourceWithDependencies("acct:johndoe@example.com", {}, {
1436
- openHop: recorder.openHop,
1437
- }),
1438
- descriptor,
1439
- );
1440
- const failures = records.filter((r) =>
1441
- r.rawMessage ===
1442
- "Failed to cancel the response body from {url}: {error}"
1443
- );
1444
- deepStrictEqual(
1445
- failures.map((r) => [r.level, r.properties.url]),
1446
- [["debug", first]],
1447
- );
1448
- const { error } = failures[0].properties;
1449
- ok(error instanceof Error);
1450
- deepStrictEqual(error.message, "Cancellation failed");
1451
- } finally {
1452
- await reset();
1453
- }
1454
- deepStrictEqual(recorder.events, [
1455
- `open ${first}`,
1456
- `fetch ${first} #1`,
1457
- "cancel #1",
1458
- `close ${first}`,
1459
- `open ${second}`,
1460
- `fetch ${second} #2`,
1461
- "consumed #2",
1462
- `close ${second}`,
1463
- ]);
1464
- recorder.assertInvariants();
1465
- });
1466
-
1467
- await t.step("never-settling body cancellation", async () => {
1468
- const recorder = recordHops((url) =>
1469
- url.pathname === "/.well-known/webfinger"
1470
- ? {
1471
- status: 302,
1472
- headers: { Location: "/.well-known/webfinger2" },
1473
- body: "redirecting",
1474
- cancelNeverSettles: true,
1475
- }
1476
- : { status: 404, body: "not found", cancelNeverSettles: true }
1477
- );
1478
- deepStrictEqual(
1479
- await settleWithin(
1480
- lookupResourceWithDependencies("acct:johndoe@example.com", {}, {
1481
- openHop: recorder.openHop,
1482
- }),
1483
- ),
1484
- null,
1485
- );
1486
- deepStrictEqual(recorder.events, [
1487
- `open ${first}`,
1488
- `fetch ${first} #1`,
1489
- "cancel #1",
1490
- `close ${first}`,
1491
- `open ${second}`,
1492
- `fetch ${second} #2`,
1493
- "cancel #2",
1494
- `close ${second}`,
1495
- ]);
1496
- recorder.assertInvariants();
1497
- });
1498
- });
1499
-
1500
- /**
1501
- * Rejects if the given promise does not settle within the timeout, so that
1502
- * a hang fails the test instead of blocking it.
1503
- */
1504
- async function settleWithin<T>(promise: Promise<T>, ms = 5000): Promise<T> {
1505
- let timer: ReturnType<typeof setTimeout> | undefined;
1506
- try {
1507
- return await Promise.race([
1508
- promise,
1509
- new Promise<never>((_, reject) => {
1510
- timer = setTimeout(
1511
- () => reject(new Error(`Did not settle within ${ms} ms.`)),
1512
- ms,
1513
- );
1514
- }),
1515
- ]);
1516
- } finally {
1517
- clearTimeout(timer);
1518
- }
1519
- }
1520
-
1521
- // A body that a real session cannot cancel to completion: fetch-mock returns
1522
- // a clone (a tee) of a Response instance, and the cancellation of a branch of
1523
- // a tee settles only after the other branch is cancelled too. Its source's
1524
- // cancel callback never settles either:
1525
- function neverCancellableResponse(init: ResponseInit): Response {
1526
- return new Response(
1527
- new ReadableStream<Uint8Array>({
1528
- start(controller) {
1529
- controller.enqueue(new TextEncoder().encode("never cancelled"));
1530
- },
1531
- cancel: () => new Promise(() => {}),
1532
- }),
1533
- init,
1534
- );
1535
- }
1536
-
1537
- test("lookupWebFinger() does not wait for cancelling response bodies", async (t) => {
1538
- const descriptor: ResourceDescriptor = {
1539
- subject: "acct:johndoe@example.com",
1540
- links: [],
1541
- };
1542
- fetchMock.mockGlobal();
1543
- try {
1544
- await t.step("redirect", async () => {
1545
- fetchMock.removeRoutes();
1546
- fetchMock.get(
1547
- "begin:https://example.com/.well-known/webfinger?",
1548
- () =>
1549
- neverCancellableResponse({
1550
- status: 302,
1551
- headers: { Location: "/.well-known/webfinger2" },
1552
- }),
1553
- );
1554
- fetchMock.get(
1555
- "https://example.com/.well-known/webfinger2",
1556
- () =>
1557
- new Response(JSON.stringify(descriptor), {
1558
- headers: { "Content-Type": "application/jrd+json" },
1559
- }),
1560
- );
1561
- deepStrictEqual(
1562
- await settleWithin(lookupDirect("acct:johndoe@example.com")),
1563
- descriptor,
1564
- );
1565
- });
1566
-
1567
- await t.step("non-2xx response", async () => {
1568
- fetchMock.removeRoutes();
1569
- fetchMock.get(
1570
- "begin:https://example.com/.well-known/webfinger?",
1571
- () => neverCancellableResponse({ status: 404 }),
1572
- );
1573
- deepStrictEqual(
1574
- await settleWithin(lookupDirect("acct:johndoe@example.com")),
1575
- null,
1576
- );
1577
- });
1578
- } finally {
1579
- fetchMock.hardReset();
1580
- }
1581
- });
1582
-
1583
- nodeTest(
1584
- "lookupWebFinger() records network_error for rejected hop addresses",
1585
- async () => {
1586
- for (
1587
- const lookup of [
1588
- () => Promise.reject(new Error("DNS unavailable")),
1589
- () => Promise.resolve([]),
1590
- () => Promise.resolve([{ address: "127.0.0.1", family: 4 }]),
1591
- ]
1592
- ) {
1593
- const [meterProvider, recorder] = createTestMeterProvider();
1594
- const result = await lookupWebFingerWithDependencies(
1595
- "acct:alice@dns-failure.invalid",
1596
- { meterProvider },
1597
- { openHop: (url) => openPublicFetch(url, { lookup }) },
1598
- );
1599
- deepStrictEqual(result, null);
1600
- const counter = recorder.getMeasurement("webfinger.lookup");
1601
- ok(counter != null);
1602
- deepStrictEqual(
1603
- counter.attributes["webfinger.lookup.result"],
1604
- "network_error",
1605
- );
1606
- deepStrictEqual(
1607
- counter.attributes["activitypub.remote.host"],
1608
- "dns-failure.invalid",
1609
- );
1610
- deepStrictEqual("http.response.status_code" in counter.attributes, false);
1611
- }
1612
- },
1613
- );
1614
-
1615
- nodeTest(
1616
- "WebFinger diagnostics classify non-object JSON after closing the hop",
1617
- async () => {
1618
- for (const body of ["null", "[]", "42", '"text"', "true"]) {
1619
- const hops = recordHops(() => ({ body }));
1620
- const [meterProvider, recorder] = createTestMeterProvider();
1621
- const outcome = await lookupWebFingerWithDependencies(
1622
- "acct:alice@example.com",
1623
- { withDiagnostics: true, meterProvider },
1624
- { openHop: hops.openHop },
1625
- );
1626
- deepStrictEqual(outcome, {
1627
- resource: null,
1628
- result: "invalid",
1629
- statusCode: 200,
1630
- remoteHost: "example.com",
1631
- });
1632
- deepStrictEqual(
1633
- hops.events.at(-1),
1634
- "close https://example.com/.well-known/webfinger?resource=acct%3Aalice%40example.com",
1635
- );
1636
- hops.assertInvariants();
1637
- deepStrictEqual(
1638
- recorder.getMeasurement("webfinger.lookup")
1639
- ?.attributes["webfinger.lookup.result"],
1640
- "invalid",
1641
- );
1642
- }
1643
- },
1644
- );