Files
Kelx/utils/remote-url-guard.test.js
2026-11-30 16:32:37 +00:00

389 lines
18 KiB
JavaScript

"use strict";
// Unit tests for utils/remote-url-guard.js — the canonical SSRF validator for
// remote URL fetches, shared by index.js (panel-side fetches) and nodes.js
// (the upload-url relay, which previously carried a weaker private copy that
// missed site-local fec0::/10, multicast ff00::/8, NAT64 64:ff9b::/96, the
// TEST-NETs and the 80/443 port allowlist).
//
// These tests pin the full acceptance contract at the unit level. Integration
// parity between the two consumers is pinned separately in
// tests/node-relay-cross-site-guard-parity.test.js.
//
// DNS-dependent branches are exercised by patching dns.promises.lookup (the
// module holds the same promises-API object), so no test touches the network.
//
// Note on IPv6 literals in URLs: WHATWG URL keeps brackets in .hostname
// ("[fd00::1]"). That used to make net.isIP() return 0 and send the bracketed
// literal into the DNS branch, failing every IPv6-literal URL closed with
// "DNS lookup failed" while the Go daemon accepted it. The guard now strips
// the brackets before classification (finding 5), so bracketed literals are
// validated like any other literal: private forms refused, public forms
// accepted with the bare form as resolvedIp (the dialable/pinned value) and
// the bracketed form as originalHostname (the Host-header value). Both
// behaviors are pinned below, alongside the form-independence contract of
// isPrivateIPv6: Node dials "::ffff:a00:1" as 10.0.0.1 exactly like
// "::ffff:10.0.0.1", so the byte-level classifier must treat every textual
// form alike.
const test = require("node:test");
const assert = require("node:assert");
const net = require("net");
const dns = require("dns").promises;
const guard = require("./remote-url-guard");
// ---- isPrivateIPv4 ---------------------------------------------------------
test("isPrivateIPv4 rejects every reserved range the guard documents", () => {
const privateAddrs = [
"0.0.0.0", "0.1.2.3", // 0/8
"10.0.0.1", "10.255.255.255", // RFC1918
"100.64.0.1", "100.127.255.254", // CGNAT
"127.0.0.1", "127.8.8.8", // loopback
"169.254.1.1", // link-local (cloud metadata)
"172.16.0.1", "172.31.255.255", // RFC1918
"192.168.1.1", // RFC1918
"192.0.2.1", // TEST-NET-1 (the relay copy missed this)
"198.18.0.1", "198.19.255.255", // benchmarking
"198.51.100.7", // TEST-NET-2 (the relay copy missed this)
"203.0.113.9", // TEST-NET-3 (the relay copy missed this)
"224.0.0.1", "239.255.255.255", // multicast
"240.0.0.1", "255.255.255.255", // reserved/broadcast
];
for (const ip of privateAddrs) {
assert.strictEqual(guard.isPrivateIPv4(ip), true, `${ip} must classify private`);
}
});
test("isPrivateIPv4 accepts public addresses and rejects unparseable input", () => {
for (const ip of ["8.8.8.8", "1.1.1.1", "93.184.216.34", "203.0.114.1", "198.20.0.1", "172.32.0.1", "100.128.0.1"]) {
assert.strictEqual(guard.isPrivateIPv4(ip), false, `${ip} must classify public`);
}
// Fail closed on garbage.
for (const bad of ["", "not-an-ip", "1.2.3", "1.2.3.4.5", "999.1.1.1", "1.2.3.-1"]) {
assert.strictEqual(guard.isPrivateIPv4(bad), true, `${JSON.stringify(bad)} must fail closed`);
}
});
// ---- isPrivateIPv6 ---------------------------------------------------------
test("isPrivateIPv6 rejects the ranges the uploader copy used to miss", () => {
// The three ranges nodes.js's deleted isUploaderPrivateIPv6 did not cover:
assert.strictEqual(guard.isPrivateIPv6("fec0::1"), true, "deprecated site-local fec0::/10");
assert.strictEqual(guard.isPrivateIPv6("feff::1"), true, "end of site-local fec0::/10");
assert.strictEqual(guard.isPrivateIPv6("ff02::1"), true, "multicast ff00::/8");
assert.strictEqual(guard.isPrivateIPv6("64:ff9b::7f00:1"), true, "NAT64 well-known prefix");
assert.strictEqual(guard.isPrivateIPv6("64:ff9b::192.0.2.1"), true, "NAT64 embedded IPv4");
});
test("isPrivateIPv6 classifies IPv4-mapped addresses in every textual form (finding 5)", () => {
// The old prefix matcher decoded only a dotted-quad tail: the hex form
// "::ffff:a00:1" fell through as "public" even though Node dials it as
// 10.0.0.1. The byte-level classifier must treat hex, dotted, mixed-case
// and fully-spelled forms identically.
const mappedPrivate = [
"::ffff:a00:1", // hex of 10.0.0.1
"::ffff:7f00:1", // hex of 127.0.0.1
"::ffff:a9fe:a9fe", // hex of 169.254.169.254 (cloud metadata)
"::FFFF:A00:1", // uppercase
"0:0:0:0:0:ffff:a00:1", // fully spelled, no compression
"::ffff:10.0.0.1", // dotted tail (the one form the old code caught)
"::ffff:169.254.169.254", // dotted metadata
];
for (const ip of mappedPrivate) {
assert.strictEqual(guard.isPrivateIPv6(ip), true, `${ip} must classify private`);
}
});
test("isPrivateIPv6 refuses the deprecated transition prefixes wholesale (daemon parity)", () => {
// Same decision as main.go isBlockedOutboundIPv6: 6to4 (RFC 7526), Teredo,
// IPv4-compatible ::/96 (RFC 4291), documentation 2001:db8::/32 and NAT64
// 64:ff9b::/32 are refused by prefix, without classifying attacker-chosen
// embedded bytes.
const blocked = [
"::a9fe:a9fe", // IPv4-compatible ::/96
"::0a00:0001", // IPv4-compatible form of 10.0.0.1
"2002:a9fe:a9fe::", // 6to4
"2001:0:a9fe:a9fe::", // Teredo
"2001:db8::1", // documentation
"64:ff9b:a9fe:a9fe::1", // NAT64 well-known
"64:ff9b:1::1", // NAT64 local-use /48
];
for (const ip of blocked) {
assert.strictEqual(guard.isPrivateIPv6(ip), true, `${ip} must classify private`);
}
// And the byte-level parser must not over-block: 2001:4444 is not Teredo
// (b[2] must matter), 64ff:ff9b is not NAT64 (the prefix is 64:ff9b), and
// mapped-public stays public.
for (const ip of ["2001:4444::1", "64ff:ff9b::1", "::ffff:8.8.8.8", "::ffff:203.0.114.1"]) {
assert.strictEqual(guard.isPrivateIPv6(ip), false, `${ip} must classify public`);
}
});
test("isPrivateIPv6 still rejects the long-covered ranges", () => {
const privateAddrs = [
"::", "::1", // unspecified + loopback
"fc00::1", "fd12:3456::1", // ULA fc00::/7
"fe80::1", "febf::1", // link-local fe80::/10
"::ffff:127.0.0.1", // IPv4-mapped loopback
"::ffff:10.1.2.3", // IPv4-mapped RFC1918
"::ffff:169.254.169.254", // IPv4-mapped metadata
];
for (const ip of privateAddrs) {
assert.strictEqual(guard.isPrivateIPv6(ip), true, `${ip} must classify private`);
}
});
test("isPrivateIPv6 accepts public and mapped-public addresses", () => {
for (const ip of ["2606:4700::1111", "2001:4860:4860::8888", "::ffff:8.8.8.8", "::ffff:203.0.114.1"]) {
assert.strictEqual(guard.isPrivateIPv6(ip), false, `${ip} must classify public`);
}
});
// ---- isPrivateAddress ------------------------------------------------------
test("isPrivateAddress fails closed on non-IP input", () => {
assert.strictEqual(guard.isPrivateAddress("example.com"), true);
assert.strictEqual(guard.isPrivateAddress(""), true);
assert.strictEqual(guard.isPrivateAddress(undefined), true);
});
// ---- helpers ----------------------------------------------------------------
// Patch dns.promises.lookup for the duration of one test. The guard module
// holds the same promises-API object this module requires, so the patch is
// visible to it. Restored in a finally block regardless of outcome.
function withDnsAnswers(hostname, answersOrError, fn) {
const original = dns.lookup;
let calledHost = null;
dns.lookup = (host, opts) => {
calledHost = host;
if (answersOrError instanceof Error) return Promise.reject(answersOrError);
return Promise.resolve(answersOrError);
};
return Promise.resolve()
.then(fn)
.finally(() => {
dns.lookup = original;
if (answersOrError instanceof Error) return;
// The guard must look up exactly the hostname it was given (no
// re-normalization that could dodge a hostname-targeted patch).
if (hostname !== null) assert.strictEqual(calledHost, hostname);
});
}
const pub = (address) => ({ address, family: net.isIP(address) });
// ---- assertSafeRemoteUrlWithResolvedIp --------------------------------------
test("accepts a public literal IP and returns it as resolvedIp", async () => {
const ok = await guard.assertSafeRemoteUrlWithResolvedIp("https://8.8.8.8/dns-query");
assert.strictEqual(ok.resolvedIp, "8.8.8.8");
assert.strictEqual(ok.originalHostname, "8.8.8.8");
assert.ok(ok.url instanceof URL);
assert.strictEqual(ok.url.protocol, "https:");
});
test("accepts default and explicit 80/443 ports", async () => {
for (const url of ["https://8.8.8.8/x", "https://8.8.8.8:443/x", "http://8.8.8.8/", "http://8.8.8.8:80/x"]) {
await assert.doesNotReject(() => guard.assertSafeRemoteUrlWithResolvedIp(url), `${url} must pass the port allowlist`);
}
});
test("rejects non-80/443 ports unless the escape hatch is engaged", async () => {
for (const port of [8080, 21, 22, 4444, 6379, 9090]) {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp(`http://8.8.8.8:${port}/x`),
/Only ports 80\/443 are allowed/,
`port ${port} must be rejected by default`
);
// The escape hatch override (mirrors REMOTE_FETCH_ALLOW_ANY_PORT=1) lets it through.
const ok = await guard.assertSafeRemoteUrlWithResolvedIp(`http://8.8.8.8:${port}/x`, { allowAnyPort: true });
assert.strictEqual(ok.url.port, String(port));
}
});
test("rejects non-http(s) protocols, credentials and localhost hosts", async () => {
const cases = [
["ftp://8.8.8.8/x", /Only http\(s\)/],
["file:///etc/passwd", /Only http\(s\)/],
["gopher://8.8.8.8", /Only http\(s\)/],
["https://user:pass@8.8.8.8/x", /Credentials/],
["https://admin@8.8.8.8/x", /Credentials/],
["http://localhost/x", /Localhost/],
["http://LOCALHOST/x", /Localhost/],
["http://sub.localhost/x", /Localhost/],
["http://machine.local/x", /Localhost/],
["http://", /Invalid URL/],
];
for (const [url, re] of cases) {
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp(url), re, `${url} must be rejected`);
}
});
test("rejects private literal IPv4 and IPv6-classified input", async () => {
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp("http://10.1.2.3/x"), /Private IP/);
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp("http://127.0.0.1/x"), /Private IP/);
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp("http://169.254.169.254/latest/meta-data/"), /Private IP/);
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp("http://192.0.2.5/x"), /Private IP/);
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp("http://0.0.0.0/x"), /Private IP/);
});
test("rejects malformed URLs", async () => {
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp("not a url at all"), /Invalid URL/);
await assert.rejects(() => guard.assertSafeRemoteUrlWithResolvedIp(""), /Invalid URL/);
});
test("hostname resolving to a public IP passes and pins that IP", async () => {
await withDnsAnswers("downloads.example.com", [pub("93.184.216.34"), pub("2606:4700::1111")], async () => {
const ok = await guard.assertSafeRemoteUrlWithResolvedIp("https://downloads.example.com/f.zip");
assert.strictEqual(ok.resolvedIp, "93.184.216.34");
assert.strictEqual(ok.originalHostname, "downloads.example.com");
});
});
test("hostname resolving to ANY private answer is rejected (reject-any-private rule)", async () => {
// One public + one private: rejected even though a public answer exists —
// a mixed round-robin must not smuggle an internal target through.
await withDnsAnswers("mixed.example.com", [pub("93.184.216.34"), pub("10.0.0.5")], async () => {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp("https://mixed.example.com/f.zip"),
/resolves to a private/
);
});
await withDnsAnswers("reversed.example.com", [pub("10.0.0.5"), pub("93.184.216.34")], async () => {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp("https://reversed.example.com/f.zip"),
/resolves to a private/
);
});
});
test("hostname resolving only to private answers is rejected", async () => {
await withDnsAnswers("internal.example.com", [pub("192.168.0.14"), pub("fd00::1")], async () => {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp("https://internal.example.com/"),
/resolves to a private/
);
});
});
test("the previously missed IPv6 ranges trip the hostname resolution check", async () => {
// fec0::/10 (site-local), ff00::/8 (multicast), 64:ff9b::/96 (NAT64) — the
// exact ranges the deleted nodes.js copy let through.
for (const [addr, label] of [["fec0::5", "site-local"], ["ff05::1", "multicast"], ["64:ff9b::a00:1", "NAT64"]]) {
await withDnsAnswers(`sneaky.example.com`, [pub(addr)], async () => {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp(`https://sneaky.example.com/`),
/resolves to a private/,
`${label} (${addr}) must be rejected when resolved`
);
});
}
});
test("a DNS answer in hex-mapped or IPv4-compatible form is rejected (finding 5)", async () => {
// A record set that answers "::ffff:a00:1" hands the dialer 10.0.0.1; the
// reject-any-private rule must see through the encoding.
for (const addr of ["::ffff:a00:1", "::ffff:10.0.0.1", "::a9fe:a9fe", "::ffff:a9fe:a9fe"]) {
await withDnsAnswers("mapped.example.com", [pub(addr)], async () => {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp("https://mapped.example.com/f.zip"),
/resolves to a private/,
`${addr} must be rejected when resolved`
);
});
}
});
test("DNS failure is rejected, not bypassed", async () => {
// Panel semantics, preserved verbatim: a failing lookup propagates its raw
// error (every caller wraps the validator in its own 400/502 handling);
// only an EMPTY answer set produces the canonical "DNS lookup failed".
await withDnsAnswers("broken.example.com", new Error("getaddrinfo EAI_AGAIN"), async () => {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp("https://broken.example.com/"),
/EAI_AGAIN/
);
});
await withDnsAnswers("empty.example.com", [], async () => {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp("https://empty.example.com/"),
/DNS lookup failed/
);
});
});
test("standalone remote URL validation bounds DNS and ignores a late public answer", async () => {
const original = dns.lookup;
let finishDns;
let timer;
dns.lookup = () => new Promise((resolve) => { finishDns = resolve; });
const pending = guard.assertSafeRemoteUrl("https://delayed.example.com/server.jar", { timeoutMs: 20 });
try {
const bounded = Promise.race([
pending,
new Promise((resolve, reject) => { timer = setTimeout(() => reject(new Error("test backstop: DNS caller never settled")), 500); }),
]);
await assert.rejects(bounded, /DNS lookup timed out/);
finishDns([pub("8.8.8.8")]);
await assert.rejects(pending, /DNS lookup timed out/, "late DNS must never return an accepted URL");
} finally {
clearTimeout(timer);
dns.lookup = original;
finishDns([pub("8.8.8.8")]);
}
});
// ---- assertSafeRemoteUrl wrapper --------------------------------------------
test("assertSafeRemoteUrl returns just the vetted URL and enforces the same policy", async () => {
const u = await guard.assertSafeRemoteUrl("https://8.8.8.8:443/file.tar.gz");
assert.ok(u instanceof URL);
// WHATWG URL strips the default port from .href — the value the relay
// forwards to the daemon is the normalized form.
assert.strictEqual(u.href, "https://8.8.8.8/file.tar.gz");
await assert.rejects(() => guard.assertSafeRemoteUrl("http://10.9.8.7/x"), /Private IP/);
await assert.rejects(() => guard.assertSafeRemoteUrl("http://8.8.8.8:8080/x"), /Only ports 80\/443/);
});
// ---- bracketed IPv6 URL literals (finding 5) --------------------------------
test("a private IPv6-literal URL is refused with the literal reason, not 'DNS lookup failed'", async () => {
// No network is touched: after bracket stripping these take the literal-IP
// branch. ("http://[169.254.169.254]/" is intentionally absent — WHATWG
// rejects a dotted quad inside brackets as an invalid host before the guard
// runs; the IPv4 equivalent is covered by the plain-literal tests above.)
const refused = [
"http://[::1]/",
"http://[::ffff:a9fe:a9fe]/", // metadata IP, hex-mapped form
"http://[::a9fe:a9fe]/", // IPv4-compatible form of the same
"http://[fc00::1]/",
"http://[fe80::1]/",
"http://[2001:db8::1]/",
"http://[2002:a9fe:a9fe::]/",
"http://[::ffff:10.0.0.1]/",
];
for (const url of refused) {
await assert.rejects(
() => guard.assertSafeRemoteUrlWithResolvedIp(url),
/Private IP is not allowed/,
`${url} must be refused as a private literal`
);
}
});
test("a public IPv6-literal URL is accepted: brackets stripped for pinning, kept for the Host header", async () => {
const ok = await guard.assertSafeRemoteUrlWithResolvedIp("http://[2606:4700:4700::1111]/path?query=1");
assert.strictEqual(ok.resolvedIp, "2606:4700:4700::1111", "resolvedIp must be the dialable bare form");
assert.strictEqual(ok.originalHostname, "[2606:4700:4700::1111]", "originalHostname must keep brackets (RFC 3986 Host header)");
assert.ok(ok.url instanceof URL);
});
test("an IPv4-literal URL pins exactly what it was given (no regression from the bracket work)", async () => {
const ok = await guard.assertSafeRemoteUrlWithResolvedIp("https://93.184.216.34/x");
assert.strictEqual(ok.resolvedIp, "93.184.216.34");
assert.strictEqual(ok.originalHostname, "93.184.216.34");
});