Skip to content

Commit 8cff9cb

Browse files
cliffhallclaude
andcommitted
fix(everything): keep bracketed IPv6 allowlist entries, allow public exceptions, bound the lookup
Copilot round 1 on #5295: match GZIP_ALLOWED_DOMAINS against the hostname as the URL spells it, so an [::1] entry still matches; allow the globally reachable exceptions inside the refused ranges, as the fetch server does; and race the DNS lookup against the fetch deadline so a stalled resolver cannot outlast GZIP_MAX_FETCH_TIME_MILLIS. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Signed-off-by: cliffhall <cliff@futurescale.com>
1 parent e18b009 commit 8cff9cb

3 files changed

Lines changed: 109 additions & 15 deletions

File tree

‎src/everything/__tests__/gzip-limits.test.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@ let port: number;
2727
beforeAll(async () => {
2828
vi.stubEnv("GZIP_MAX_FETCH_SIZE", "16");
2929
vi.stubEnv("GZIP_MAX_FETCH_TIME_MILLIS", "150");
30-
vi.stubEnv("GZIP_ALLOWED_DOMAINS", " Example.COM, localhost ,,");
30+
vi.stubEnv("GZIP_ALLOWED_DOMAINS", " Example.COM, localhost ,,[::1]");
3131
vi.stubEnv("GZIP_ALLOW_PRIVATE_IPS", "1");
3232
harness = await import("./harness.js");
3333

@@ -104,6 +104,12 @@ describe("gzip-file-as-resource limits", () => {
104104
});
105105
});
106106

107+
it("matches a listed IPv6 literal with its brackets", async () => {
108+
expect(await gzip(`http://[::1]:${port}/file`)).toMatchObject({
109+
type: "resource_link",
110+
});
111+
});
112+
107113
it("refuses a host that only ends with a listed domain's name", async () => {
108114
const lookalike = "https://notexample.com/x";
109115
expect(await gzipText(lookalike)).toBe(

‎src/everything/__tests__/gzip-private-addresses.test.ts‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,8 @@
77
* and `fetch` are stubbed for one name, `public.example`; every other name
88
* and URL goes to the real resolver and the real `fetch`. The opt-in
99
* (`GZIP_ALLOW_PRIVATE_IPS`) is exercised by the other gzip suites, whose
10-
* fixtures are on loopback.
10+
* fixtures are on loopback. The fetch deadline is shortened, before the
11+
* server loads, to show that it bounds a lookup that never answers.
1112
*/
1213
import { createServer as createHttpServer, type Server } from "node:http";
1314
import { once } from "node:events";
@@ -22,14 +23,26 @@ import {
2223
} from "vitest";
2324
import { connect, contentOf, textOf, type Session } from "./harness.js";
2425

26+
vi.hoisted(() => {
27+
vi.stubEnv("GZIP_MAX_FETCH_TIME_MILLIS", "500");
28+
});
29+
2530
vi.mock("node:dns/promises", async (importOriginal) => {
2631
const actual = await importOriginal<typeof import("node:dns/promises")>();
32+
const stubbed: Record<string, { address: string; family: number }> = {
33+
"public.example": { address: "93.184.215.14", family: 4 },
34+
"anycast.example": { address: "192.0.0.9", family: 4 }, // inside 192.0.0.0/24
35+
"anycast6.example": { address: "2001:3::1", family: 6 }, // inside 2001::/23
36+
};
2737
return {
2838
...actual,
29-
lookup: (hostname: string, options: { all: true }) =>
30-
hostname === "public.example"
31-
? Promise.resolve([{ address: "93.184.215.14", family: 4 }])
32-
: actual.lookup(hostname, options),
39+
lookup: (hostname: string, options: { all: true }) => {
40+
if (hostname === "stalled.example") return new Promise(() => {});
41+
const answer = stubbed[hostname];
42+
return answer
43+
? Promise.resolve([answer])
44+
: actual.lookup(hostname, options);
45+
},
3346
};
3447
});
3548

@@ -51,7 +64,7 @@ beforeAll(async () => {
5164

5265
const realFetch = globalThis.fetch;
5366
vi.stubGlobal("fetch", (input: URL, init?: RequestInit) => {
54-
if (input.hostname !== "public.example") return realFetch(input, init);
67+
if (!input.hostname.endsWith(".example")) return realFetch(input, init);
5568
if (input.pathname === "/to-loopback") {
5669
return Promise.resolve(
5770
new Response(null, {
@@ -66,6 +79,7 @@ beforeAll(async () => {
6679

6780
afterAll(async () => {
6881
vi.unstubAllGlobals();
82+
vi.unstubAllEnvs();
6983
http.closeAllConnections();
7084
await new Promise((resolve) => http.close(resolve));
7185
});
@@ -143,6 +157,25 @@ describe("gzip-file-as-resource private addresses (#5130)", () => {
143157
});
144158
});
145159

160+
it.each([
161+
["IPv4", "anycast.example"],
162+
["IPv6", "anycast6.example"],
163+
])(
164+
"fetches from a globally reachable %s exception inside a refused range",
165+
async (_family, host) => {
166+
expect(await gzip(`http://${host}/file`)).toMatchObject({
167+
type: "resource_link",
168+
});
169+
},
170+
);
171+
172+
it("bounds the address lookup by GZIP_MAX_FETCH_TIME_MILLIS", async () => {
173+
const url = "http://stalled.example/file";
174+
expect(textOf(await gzip(url))).toBe(
175+
`Fetching ${url} took more than 500 ms and was aborted.`,
176+
);
177+
});
178+
146179
it("refuses a redirect from a public origin to a loopback address", async () => {
147180
const hop = `http://127.0.0.1:${port}/secret`;
148181
expect(textOf(await gzip("http://public.example/to-loopback"))).toBe(

‎src/everything/tools/gzip-file-as-resource.ts‎

Lines changed: 63 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -104,6 +104,53 @@ for (const [network, prefix] of [
104104
NON_PUBLIC_ADDRESSES.addSubnet(network, prefix, "ipv6");
105105
}
106106

107+
// Globally reachable assignments inside those ranges (anycast services and
108+
// the like), allowed as the fetch server allows its _PUBLIC_EXCEPTIONS.
109+
const PUBLIC_EXCEPTIONS = new BlockList();
110+
PUBLIC_EXCEPTIONS.addAddress("192.0.0.9", "ipv4");
111+
PUBLIC_EXCEPTIONS.addAddress("192.0.0.10", "ipv4");
112+
for (const [network, prefix] of [
113+
["2001:1::1", 128],
114+
["2001:1::2", 128],
115+
["2001:3::", 32],
116+
["2001:4:112::", 48],
117+
["2001:20::", 28],
118+
["2001:30::", 28],
119+
] as const) {
120+
PUBLIC_EXCEPTIONS.addSubnet(network, prefix, "ipv6");
121+
}
122+
123+
/** True when `address` is not a public destination. */
124+
function isNonPublic(address: string, family: number): boolean {
125+
const type = family === 6 ? "ipv6" : "ipv4";
126+
return (
127+
!PUBLIC_EXCEPTIONS.check(address, type) &&
128+
NON_PUBLIC_ADDRESSES.check(address, type)
129+
);
130+
}
131+
132+
/**
133+
* Settles as `promise` does, or rejects with the signal's reason as soon as it
134+
* aborts, so that the fetch deadline also bounds work that takes no signal
135+
* (the DNS lookup).
136+
*/
137+
async function raceAbort<T>(
138+
promise: Promise<T>,
139+
signal: AbortSignal,
140+
): Promise<T> {
141+
signal.throwIfAborted();
142+
let onAbort = () => {};
143+
const aborted = new Promise<never>((_, reject) => {
144+
onAbort = () => reject(signal.reason);
145+
signal.addEventListener("abort", onAbort, { once: true });
146+
});
147+
try {
148+
return await Promise.race([promise, aborted]);
149+
} finally {
150+
signal.removeEventListener("abort", onAbort);
151+
}
152+
}
153+
107154
// Tool input schema
108155
const GZipFileAsResourceSchema = z.object({
109156
name: z
@@ -221,9 +268,13 @@ export const registerGZipFileAsResourceTool = (
221268
* checked address for the connection, which this demo server does not do.
222269
*
223270
* @param {URL} url The URL about to be requested.
271+
* @param {AbortSignal} signal The fetch's deadline, which bounds the lookup too.
224272
* @throws {Error} If the request is refused, or the host cannot be resolved.
225273
*/
226-
async function assertPermittedTarget(url: URL): Promise<void> {
274+
async function assertPermittedTarget(
275+
url: URL,
276+
signal: AbortSignal,
277+
): Promise<void> {
227278
const refuse = (reason: string) =>
228279
new Error(`Error processing file ${url}: ${reason}`);
229280
if (url.protocol === "data:") return; // carries its own bytes
@@ -232,17 +283,21 @@ async function assertPermittedTarget(url: URL): Promise<void> {
232283
`Unsupported URL protocol for ${url}. Only http, https, and data URLs are supported.`,
233284
);
234285
}
235-
// An IPv6 literal's hostname keeps its brackets: [::1]
236-
const host = url.hostname.replace(/^\[(.*)\]$/, "$1");
286+
// Names are matched as the URL spells them, an IPv6 literal with its
287+
// brackets ([::1]), as they always have been
288+
const domain = url.hostname;
237289
if (
238290
GZIP_ALLOWED_DOMAINS.length > 0 &&
239-
!GZIP_ALLOWED_DOMAINS.some((d) => host === d || host.endsWith(`.${d}`))
291+
!GZIP_ALLOWED_DOMAINS.some((d) => domain === d || domain.endsWith(`.${d}`))
240292
) {
241-
throw refuse(`Domain ${host} is not in the allowed domains list.`);
293+
throw refuse(`Domain ${domain} is not in the allowed domains list.`);
242294
}
243295
if (GZIP_ALLOW_PRIVATE_IPS) return;
244-
for (const { address, family } of await lookup(host, { all: true })) {
245-
if (NON_PUBLIC_ADDRESSES.check(address, family === 6 ? "ipv6" : "ipv4")) {
296+
// The resolver takes an IPv6 literal without its brackets
297+
const host = domain.replace(/^\[(.*)\]$/, "$1");
298+
const addresses = await raceAbort(lookup(host, { all: true }), signal);
299+
for (const { address, family } of addresses) {
300+
if (isNonPublic(address, family)) {
246301
throw refuse(
247302
`${host} resolves to ${address}, which is not a public address. Set GZIP_ALLOW_PRIVATE_IPS=1 to allow private, loopback and link-local addresses.`,
248303
);
@@ -266,7 +321,7 @@ async function fetchPermitted(
266321
): Promise<Response> {
267322
let target = url;
268323
for (let redirects = 0; ; redirects++) {
269-
await assertPermittedTarget(target);
324+
await assertPermittedTarget(target, signal);
270325
const response = await fetch(target, { signal, redirect: "manual" });
271326
const location = response.headers.get("location");
272327
if (!REDIRECT_STATUSES.has(response.status) || location === null) {

0 commit comments

Comments
 (0)