Public: anyone can read this; the crew can change it.

A domain check never queries a private, loopback, metadata or tailnet nameserver #15205

Merged opened this

Check · Review · Land · Live done — Landed and live in production.

Merged

mason/forge:mason/15202-a-domain-check-never-queries-a-private-l → main 2 commits fork

  • Merged. mason/15202-a-domain-check-never-queries-a-private-l was merged into main as 580371f.

Review

Sign in to review this change.
3 files changed +278 −34
src/apps/domains.ts +128 −32
@@ -16,6 +16,7 @@ import {
1616 resolveNs,
1717 resolveTxt,
1818 } from "node:dns/promises";
19 import { isPublicAddress } from "./egress.ts";
1920
2021 export interface DnsRecord {
2122 readonly type: "TXT" | "CNAME" | "ALIAS";
@@ -54,7 +55,8 @@ export function recordsFor(
5455
5556 /** What a check asks of DNS — the system resolver, or a test's stand-in. */
5657 export interface DomainResolver {
57 resolveTxt(name: string): Promise<string[][]>;
58 /** `signal` aborts when the check gives up on the lookup. */
59 resolveTxt(name: string, signal?: AbortSignal): Promise<string[][]>;
5860 resolveCname(name: string): Promise<string[]>;
5961 }
6062
@@ -62,15 +64,34 @@ export interface DomainResolver {
6264 export interface Authority {
6365 resolveNs(zone: string): Promise<string[]>;
6466 resolve4(host: string): Promise<string[]>;
65 /** TXT for `name`, asked of exactly these servers. */
66 resolveTxtAt(servers: string[], name: string): Promise<string[][]>;
67 /**
68 * TXT for `name`, asked of exactly these servers — never more than
69 * {@link MAX_NAMESERVERS}, each a public address. `signal` aborts when
70 * the check gives up, and the question is cancelled then.
71 */
72 resolveTxtAt(
73 servers: string[],
74 name: string,
75 signal?: AbortSignal,
76 ): Promise<string[][]>;
6777 }
6878
79 /** The most nameservers one authoritative question goes to. */
80 export const MAX_NAMESERVERS = 4;
81
82 /**
83 * The zone named nameservers, but none at a public address: loopback, a
84 * private range, link-local or metadata, shared address space, multicast.
85 * The zone is the person's to choose, so its NS records could otherwise
86 * point the forge's own resolver at the forge's network (#15202).
87 */
88 const NO_PUBLIC_NAMESERVER = "ENOPUBLICNS";
89
90 /** The zone's nameservers were asked and did not answer cleanly. */
91 const AUTHORITY_FAILED = "EAUTHORITY";
92
6993 const isNone = (error: unknown): boolean => {
70 const code =
71 typeof error === "object" && error !== null && "code" in error
72 ? String((error as { code: unknown }).code)
73 : "";
94 const code = codeOf(error);
7495 return code === "ENODATA" || code === "ENOTFOUND";
7596 };
7697
@@ -90,10 +111,18 @@ async function nameserversFor(
90111 if (hosts.length === 0) continue;
91112 const addresses = (
92113 await Promise.all(
93 hosts.slice(0, 4).map((h) => authority.resolve4(h).catch(() => [])),
114 hosts
115 .slice(0, MAX_NAMESERVERS)
116 .map((h) => authority.resolve4(h).catch(() => [] as string[])),
94117 )
95118 ).flat();
96 if (addresses.length > 0) return addresses;
119 if (addresses.length === 0) continue;
120 const reachable = [...new Set(addresses)].filter(isPublicAddress);
121 if (reachable.length === 0)
122 throw Object.assign(new Error(`no public nameservers for ${name}`), {
123 code: NO_PUBLIC_NAMESERVER,
124 });
125 return reachable.slice(0, MAX_NAMESERVERS);
97126 }
98127 throw Object.assign(new Error(`no nameservers for ${name}`), {
99128 code: "ENOTFOUND",
@@ -112,23 +141,36 @@ export function withAuthority(
112141 primary: DomainResolver,
113142 authority: Authority,
114143 ): DomainResolver {
115 const authoritative = async (name: string): Promise<string[][]> => {
144 const authoritative = async (
145 name: string,
146 signal?: AbortSignal,
147 ): Promise<string[][]> => {
116148 const servers = await nameserversFor(name, authority);
117 return authority.resolveTxtAt(servers, name);
149 try {
150 return await authority.resolveTxtAt(servers, name, signal);
151 } catch (error) {
152 // What the zone's servers said is theirs to word; the sentence is
153 // the forge's, so only "none" passes through as itself.
154 if (isNone(error)) throw error;
155 throw Object.assign(new Error(`authority failed for ${name}`), {
156 code: AUTHORITY_FAILED,
157 });
158 }
118159 };
119160 return {
120 async resolveTxt(name) {
161 async resolveTxt(name, signal) {
121162 // A stale answer is as misleading as a stale "none": a record changed
122163 // a minute ago still reads as its old value for as long as its TTL
123164 // says. So the authority is asked either way, and both answers count.
124165 let near: string[][] = [];
125166 try {
126 near = await primary.resolveTxt(name);
167 near = await primary.resolveTxt(name, signal);
127168 } catch (error) {
128169 if (!isNone(error)) throw error;
129170 }
130 const far = await authoritative(name).catch((error: unknown) => {
131 if (near.length > 0 && isNone(error)) return [] as string[][];
171 const far = await authoritative(name, signal).catch((error: unknown) => {
172 if (near.length > 0 && (isNone(error) || codeOf(error) === NO_PUBLIC_NAMESERVER))
173 return [] as string[][];
132174 throw error;
133175 });
134176 const seen = new Set(near.map((r) => r.join("")));
@@ -138,6 +180,36 @@ export function withAuthority(
138180 };
139181 }
140182
183 /** The part of `node:dns`'s Resolver an authoritative question uses. */
184 export interface ServerResolver {
185 setServers(servers: string[]): void;
186 resolveTxt(name: string): Promise<string[][]>;
187 cancel(): void;
188 }
189
190 /**
191 * Ask `servers` for `name`'s TXT on a resolver of its own, cancelled when
192 * `signal` aborts so a check that gave up leaves no question in flight.
193 */
194 export async function askServers(
195 servers: string[],
196 name: string,
197 signal?: AbortSignal,
198 make: () => ServerResolver = () => new Resolver({ timeout: 3_000, tries: 1 }),
199 ): Promise<string[][]> {
200 const asked = make();
201 asked.setServers(servers);
202 const cancel = () => asked.cancel();
203 signal?.addEventListener("abort", cancel, { once: true });
204 try {
205 const answer = asked.resolveTxt(`${name}.`);
206 if (signal?.aborted) cancel();
207 return await answer;
208 } finally {
209 signal?.removeEventListener("abort", cancel);
210 }
211 }
212
141213 const systemResolver: DomainResolver = withAuthority(
142214 {
143215 resolveTxt: (name) => resolveTxt(`${name}.`),
@@ -146,11 +218,7 @@ const systemResolver: DomainResolver = withAuthority(
146218 {
147219 resolveNs: (zone) => resolveNs(`${zone}.`),
148220 resolve4: (host) => resolve4(`${host}.`),
149 resolveTxtAt(servers, name) {
150 const asked = new Resolver({ timeout: 3_000, tries: 1 });
151 asked.setServers(servers);
152 return asked.resolveTxt(`${name}.`);
153 },
221 resolveTxtAt: askServers,
154222 },
155223 );
156224
@@ -175,13 +243,13 @@ export async function checkDomain(
175243 resolver: DomainResolver = systemResolver,
176244 ): Promise<DomainCheck> {
177245 const name = verifyName(host);
178 const proof = await lookup(() => resolver.resolveTxt(name));
246 const proof = await lookup((signal) => resolver.resolveTxt(name, signal));
179247 if (proof.kind === "none")
180248 return { verified: false, said: `No TXT record at ${name} yet.` };
181249 if (proof.kind === "failed")
182250 return {
183251 verified: false,
184 said: `The DNS lookup for ${name} ${proof.why}; try again in a minute.`,
252 said: `The DNS lookup for ${name} ${proof.why}; ${proof.next}.`,
185253 };
186254 const values = proof.value.map((chunks) => chunks.join(""));
187255 if (!values.includes(verifyValue(token)))
@@ -205,7 +273,9 @@ export async function checkClaim(
205273 claimantToken: string,
206274 resolver: DomainResolver = systemResolver,
207275 ): Promise<{ claimantPublished: boolean; holderPublished: boolean }> {
208 const proof = await lookup(() => resolver.resolveTxt(verifyName(host)));
276 const proof = await lookup((signal) =>
277 resolver.resolveTxt(verifyName(host), signal),
278 );
209279 if (proof.kind === "failed") return { claimantPublished: false, holderPublished: true };
210280 const values = proof.kind === "none" ? [] : proof.value.map((chunks) => chunks.join(""));
211281 return {
@@ -240,34 +310,60 @@ const canonical = (name: string): string =>
240310 type Lookup<T> =
241311 | { kind: "found"; value: T }
242312 | { kind: "none" }
243 | { kind: "failed"; why: string };
313 | { kind: "failed"; why: string; next: string };
244314
245315 /**
246316 * One lookup, with every way it can go wrong folded into a value. "No such
247317 * record" and "no such name" both mean nothing is published yet; anything
248318 * else is the resolver's trouble, named so the sentence can carry it.
249319 */
250 async function lookup<T>(run: () => Promise<T>): Promise<Lookup<T>> {
320 export async function lookup<T>(
321 run: (signal: AbortSignal) => Promise<T>,
322 ms: number = LOOKUP_TIMEOUT_MS,
323 ): Promise<Lookup<T>> {
324 const giveUp = new AbortController();
251325 let timer: ReturnType<typeof setTimeout> | undefined;
252326 const timeout = new Promise<never>((_, reject) => {
253327 timer = setTimeout(
254328 () => reject(Object.assign(new Error("timed out"), { code: "ETIMEOUT" })),
255 LOOKUP_TIMEOUT_MS,
329 ms,
256330 );
257331 });
258332 try {
259 return { kind: "found", value: await Promise.race([run(), timeout]) };
333 return {
334 kind: "found",
335 value: await Promise.race([run(giveUp.signal), timeout]),
336 };
260337 } catch (error) {
261338 if (isNone(error)) return { kind: "none" };
262 const code =
263 typeof error === "object" && error !== null && "code" in error
264 ? String((error as { code: unknown }).code)
265 : "";
339 const code = codeOf(error);
266340 return {
267341 kind: "failed",
268 why: code === "ETIMEOUT" ? "timed out" : `failed (${code || "error"})`,
342 why: failedWhy(code),
343 next:
344 code === NO_PUBLIC_NAMESERVER
345 ? "point the zone's NS records at public nameservers"
346 : "try again in a minute",
269347 };
270348 } finally {
271349 clearTimeout(timer);
350 // A lookup the timeout outran stops querying; one that settled is
351 // unaffected.
352 giveUp.abort();
272353 }
273354 }
355
356 const codeOf = (error: unknown): string =>
357 typeof error === "object" && error !== null && "code" in error
358 ? String((error as { code: unknown }).code)
359 : "";
360
361 /** The clause after "The DNS lookup for <name>". */
362 function failedWhy(code: string): string {
363 if (code === "ETIMEOUT") return "timed out";
364 if (code === NO_PUBLIC_NAMESERVER)
365 return "skipped the zone's own nameservers, which are only at private or local addresses";
366 if (code === AUTHORITY_FAILED)
367 return "failed at the zone's own nameservers";
368 return `failed (${code || "error"})`;
369 }
test/app-domains.test.ts +2 −2
@@ -144,7 +144,7 @@ describe("checkDomain: every outcome is a sentence", () => {
144144 },
145145 resolve4: (host: string) => {
146146 asked.push(`a ${host}`);
147 return Promise.resolve(["192.0.2.53"]);
147 return Promise.resolve(["198.51.100.53"]);
148148 },
149149 resolveTxtAt: (servers: string[], name: string) => {
150150 asked.push(`txt@${servers.join(",")} ${name}`);
@@ -163,7 +163,7 @@ describe("checkDomain: every outcome is a sentence", () => {
163163 "ns app.example.com",
164164 "ns example.com",
165165 "a ns1.example.net",
166 "txt@192.0.2.53 _forge-verify.app.example.com",
166 "txt@198.51.100.53 _forge-verify.app.example.com",
167167 ]);
168168 // A stale value from the box's resolver does not hide the authority's.
169169 const stale2 = withAuthority(
test/domain-nameservers.test.ts added +148
@@ -0,0 +1,148 @@
1 /**
2 * The authoritative step of a domain check asks only public nameservers
3 * (#15202). A zone's NS records are the person's to choose, so without the
4 * filter they could aim the forge's resolver at its own network — loopback,
5 * a private range, the metadata address — and read the outcome back from
6 * the sentence.
7 */
8
9 import { describe, expect, test } from "bun:test";
10 import {
11 askServers,
12 checkDomain,
13 lookup,
14 MAX_NAMESERVERS,
15 withAuthority,
16 type Authority,
17 type DomainResolver,
18 type ServerResolver,
19 } from "../src/apps/domains.ts";
20
21 const TOKEN = "abcdefghjkmnpqrstvwxyz01";
22 const HOST = "app.example.com";
23 const PROOF = `_forge-verify.${HOST}`;
24 const nx = () => Promise.reject(Object.assign(new Error("nx"), { code: "ENOTFOUND" }));
25
26 /** The box's own resolver: knows nothing yet. */
27 const empty: DomainResolver = { resolveTxt: nx, resolveCname: nx };
28
29 /** An authority whose zone's NS hosts resolve to `addresses`, recording every TXT question. */
30 function zoneAt(addresses: Record<string, string[]>) {
31 const asked: string[][] = [];
32 const authority: Authority = {
33 resolveNs: (zone) =>
34 zone === "example.com" ? Promise.resolve(Object.keys(addresses)) : nx(),
35 resolve4: (host) => Promise.resolve(addresses[host] ?? []),
36 resolveTxtAt: (servers) => {
37 asked.push(servers);
38 return Promise.resolve([[`forge-verify=${TOKEN}`]]);
39 },
40 };
41 return { asked, authority };
42 }
43
44 describe("the zone's own nameservers", () => {
45 test("loopback and private nameservers are never asked, and the sentence says so plainly", async () => {
46 const { asked, authority } = zoneAt({
47 "ns1.evil.test": ["127.0.0.1"],
48 "ns2.evil.test": ["10.0.0.1"],
49 });
50 const result = await checkDomain(HOST, TOKEN, "notes.apps.test", withAuthority(empty, authority));
51 expect(asked).toEqual([]);
52 expect(result).toEqual({
53 verified: false,
54 said: `The DNS lookup for ${PROOF} skipped the zone's own nameservers, which are only at private or local addresses; point the zone's NS records at public nameservers.`,
55 });
56 });
57
58 test("link-local, metadata, shared, multicast and unique-local addresses are dropped; public ones are kept", async () => {
59 const { asked, authority } = zoneAt({
60 "a.test": ["169.254.169.254", "198.51.100.1"],
61 "b.test": ["100.64.0.1", "192.168.1.1"],
62 "c.test": ["224.0.0.1", "fd00::53"],
63 "d.test": ["172.16.0.1", "fe80::1"],
64 });
65 const result = await checkDomain(HOST, TOKEN, "notes.apps.test", withAuthority(empty, authority));
66 expect(result.verified).toBe(true);
67 expect(asked).toEqual([["198.51.100.1"]]);
68 });
69
70 test("no more than four servers are asked", async () => {
71 const { asked, authority } = zoneAt({
72 "ns1.test": ["198.51.100.1", "198.51.100.2", "198.51.100.3"],
73 "ns2.test": ["198.51.100.4", "198.51.100.5", "198.51.100.6"],
74 });
75 await checkDomain(HOST, TOKEN, "notes.apps.test", withAuthority(empty, authority));
76 expect(asked.length).toBe(1);
77 expect(asked[0]?.length).toBe(MAX_NAMESERVERS);
78 expect(MAX_NAMESERVERS).toBe(4);
79 });
80
81 test("when the box's resolver already has the proof, private nameservers do not spoil it", async () => {
82 const { asked, authority } = zoneAt({ "ns.test": ["127.0.0.1"] });
83 const near: DomainResolver = {
84 resolveTxt: () => Promise.resolve([[`forge-verify=${TOKEN}`]]),
85 resolveCname: nx,
86 };
87 const result = await checkDomain(HOST, TOKEN, "notes.apps.test", withAuthority(near, authority));
88 expect(result.verified).toBe(true);
89 expect(asked).toEqual([]);
90 });
91
92 test("a failure at the zone's servers carries no raw resolver code into the sentence", async () => {
93 const { authority } = zoneAt({ "ns.test": ["198.51.100.1"] });
94 authority.resolveTxtAt = () =>
95 Promise.reject(Object.assign(new Error("refused"), { code: "ECONNREFUSED" }));
96 const result = await checkDomain(HOST, TOKEN, "notes.apps.test", withAuthority(empty, authority));
97 expect(result.verified).toBe(false);
98 expect(result.said).toBe(
99 `The DNS lookup for ${PROOF} failed at the zone's own nameservers; try again in a minute.`,
100 );
101 expect(result.said).not.toMatch(/E[A-Z]{3,}/);
102 });
103 });
104
105 describe("a lookup that gives up cancels its question", () => {
106 test("the signal handed to the lookup aborts when the time runs out", async () => {
107 let seen: AbortSignal | undefined;
108 const result = await lookup((signal) => {
109 seen = signal;
110 return new Promise<never>(() => {});
111 }, 5);
112 expect(result).toEqual({ kind: "failed", why: "timed out", next: "try again in a minute" });
113 expect(seen?.aborted).toBe(true);
114 });
115
116 test("withAuthority passes the signal to the zone's servers", async () => {
117 const { authority } = zoneAt({ "ns.test": ["198.51.100.1"] });
118 let seen: AbortSignal | undefined;
119 authority.resolveTxtAt = (_servers, _name, signal) => {
120 seen = signal;
121 return Promise.resolve([]);
122 };
123 const giveUp = new AbortController();
124 await withAuthority(empty, authority).resolveTxt(PROOF, giveUp.signal);
125 expect(seen).toBe(giveUp.signal);
126 });
127
128 test("the resolver asking the servers is cancelled on abort", async () => {
129 const calls: string[] = [];
130 let fail: (e: unknown) => void = () => {};
131 const fake: ServerResolver = {
132 setServers: (servers) => calls.push(`servers ${servers.join(",")}`),
133 resolveTxt: (name) => {
134 calls.push(`txt ${name}`);
135 return new Promise((_, reject) => (fail = reject));
136 },
137 cancel: () => {
138 calls.push("cancel");
139 fail(Object.assign(new Error("cancelled"), { code: "ECANCELLED" }));
140 },
141 };
142 const giveUp = new AbortController();
143 const asked = askServers(["198.51.100.1"], PROOF, giveUp.signal, () => fake);
144 giveUp.abort();
145 await expect(asked).rejects.toMatchObject({ code: "ECANCELLED" });
146 expect(calls).toEqual([`servers 198.51.100.1`, `txt ${PROOF}.`, "cancel"]);
147 });
148 });

↑↓ navigate ↵ open ⌘↵ its app esc close

Keyboard shortcuts

Docs