Files
HealthLog/src/lib/safe-fetch-dispatcher.ts
T
Marc-André Bombeck 324df70071 fix(egress): vet all addresses and version-lock the pinned fetch
The connect-time SSRF pin returned only the first vetted address and
attached an undici@8 Agent to Node's built-in fetch. Two failures:

- A host whose first DNS record is an unreachable IPv6 (no IPv6 route on
  the container / LAN / Tailscale) failed the connect instantly, because
  the single-address pin discarded the working IPv4 record behind it and
  Happy Eyeballs never ran.
- Node's global fetch is backed by its own pinned undici copy; handing it
  an Agent built from the project's undici throws UND_ERR_INVALID_ARG on
  a dispatch-handler interface mismatch.

Hand undici the full vetted survivor set and enable autoSelectFamily so
it runs RFC 8305 Happy Eyeballs across the already-vetted IPs (rebinding
stays closed: every dialable IP passed isPublicIp in the same lookup).
Drive the pinned path through undici's own fetch so the dispatcher and
the fetch engine share one undici version.

Add an end-to-end regression that drives a real localhost-bound server
through the pinned path (not a mocked fetch, which hid the coupling),
covering the IPv6-to-IPv4 fallback, streaming, timeout, and abort.
2026-06-28 15:18:03 +02:00

129 lines
4.8 KiB
TypeScript

import dns from "node:dns";
import { Agent } from "undici";
import { isPublicIp } from "@/lib/validations/notifications";
/**
* Custom `undici.Agent` that resolves the request hostname literally,
* vets every returned address against `isPublicIp`, and pins the
* connection to the vetted survivor set.
*
* This closes the DNS-rebinding gap that `isPublicUrl` cannot reach
* (issue #217). The input-time check accepts a hostname that resolves
* to a public address; the resolver is then free to flip the record to
* `169.254.169.254` (cloud metadata) or `10.0.0.x` (operator admin
* panel) by the time the connection dials. With a TTL of 0 the attack
* is reliable.
*
* Mechanism:
*
* 1. Override `connect.lookup` with a wrapper that always runs
* `dns.lookup({ all: true })` so we see every address the resolver
* would have returned.
* 2. Filter that list through `isPublicIp` — same allowlist
* `isPublicUrl` enforces, applied to a literal IP address rather
* than the input string.
* 3. Hand undici the FULL vetted survivor set, not just the first
* address. The `Agent` runs with `autoSelectFamily`, so undici's
* connector calls this lookup with `all: true` and then performs
* RFC 8305 Happy Eyeballs across the survivors. Returning only the
* first address — historically `allowed[0]` — defeated that: a host
* whose first record is an unreachable IPv6 (common on a no-IPv6
* container / LAN / Tailscale path, e.g. `claude.ai` from a v4-only
* box) failed the connect instantly even though a working IPv4
* record was right behind it. Every IP undici may dial was vetted in
* THIS lookup, so DNS rebinding stays closed while v4/v6 fallback
* works.
* 4. If no address passes, fail closed with `dns.NOTFOUND` so the
* dispatch surfaces as a normal connect error rather than a silent
* bypass.
*
* Wired into `safeFetch` only when `opts.requirePublicHost` is true.
* The outbound paths that accept a user-supplied host all use that flag.
*/
function pinnedLookup(
hostname: string,
options: dns.LookupOptions,
callback: (
err: NodeJS.ErrnoException | null,
address: string | dns.LookupAddress[],
family?: number,
) => void,
): void {
// Always ask for every address so the filter sees the full set;
// discarding alternates a low-TTL attacker could swap in is exactly
// the point of the pin.
const opts: dns.LookupAllOptions = {
family: options.family ?? 0,
hints: options.hints,
verbatim: options.verbatim,
all: true,
};
dns.lookup(hostname, opts, (err, addresses) => {
if (err) {
callback(err, "");
return;
}
const allowed = addresses.filter((a) => isPublicIp(a.address));
if (allowed.length === 0) {
const refused: NodeJS.ErrnoException = new Error(
`safeFetch refused private resolved address for ${hostname}`,
);
refused.code = "ENOTFOUND";
callback(refused, "");
return;
}
if (options.all) {
// Caller asked for the array shape — pass through EVERY survivor so
// undici's Happy-Eyeballs loop can fall back across families. With
// `autoSelectFamily` enabled (below) the connector always takes
// this branch.
callback(null, allowed);
return;
}
// Single-address contract (no `autoSelectFamily`, or a caller that
// explicitly asked for one address): hand back the first survivor.
const picked = allowed[0];
callback(null, picked.address, picked.family);
});
}
/**
* Lazily-instantiated singleton. `undici.Agent` keeps an internal pool
* per origin, so reusing one instance across calls preserves the keep-
* alive benefit while still pinning each new connection through the
* vetted lookup.
*/
let cached: Agent | null = null;
export function getPinnedPublicDispatcher(): Agent {
if (cached) return cached;
cached = new Agent({
connect: {
lookup: pinnedLookup,
// RFC 8305 Happy Eyeballs across the vetted survivor set. Without
// this undici pins the single first address and dies when that is
// an unreachable IPv6 record on a v4-only host. With it, undici
// calls `pinnedLookup` with `all: true` and races the vetted v4/v6
// candidates, taking the first that connects.
autoSelectFamily: true,
// How long to wait for one family before trying the next. 250 ms is
// the documented sane default — long enough not to thrash on a slow
// RTT, short enough that a black-holed family falls back quickly.
autoSelectFamilyAttemptTimeout: 250,
},
});
return cached;
}
/**
* Test helper. The dispatcher is module-state; tests that mock
* `dns.lookup` need to clear the cached instance so the next call
* binds the mock.
*/
export function _resetPinnedDispatcherForTests(): void {
cached?.destroy().catch(() => {});
cached = null;
}