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

518 lines
22 KiB
JavaScript

"use strict";
// Tests for the node-address SSRF guard (utils/node-ssrf-guard.js),
// remediation for audit finding 3.3 (admin-gated SSRF via POST /api/nodes).
// Run: npm test (node --test utils/*.test.js)
//
// The suite proves:
// 1. IP classification blocks loopback / link-local / private / reserved /
// cloud metadata — including every IPv4-in-IPv6 smuggling form
// (mapped, deprecated-compatible, 6to4, teredo, nat64) — while public
// addresses and their boundary neighbors stay allowed.
// 2. Creation/update-time validation rejects reserved hostnames,
// unresolvable names and names resolving to internal addresses.
// 3. guardedNodeLookup re-validates RESOLVED addresses at connect time:
// getaddrinfo numeric shorthand ("2130706433" -> 127.0.0.1) and DNS
// rebinding cannot slip through; validated answers are cached safely.
// 4. The exact request pattern used by the nodes.js primitives
// (assertNodeUrlHostAllowed pre-flight + guarded lookup on lib.request)
// blocks literal loopback end-to-end and still delivers traffic for
// allowed addresses. nodes.js itself cannot be required here (it boots
// the app), so the replica below mirrors its wired call sites.
// 5. ADPANEL_ALLOW_PRIVATE_NODES=1 re-opens private targets explicitly.
const test = require("node:test");
const assert = require("node:assert");
const http = require("node:http");
const dns = require("node:dns");
const net = require("node:net");
const guard = require("./node-ssrf-guard");
// ─── helpers ────────────────────────────────────────────────────────────────
function stubDnsLookup(impl) {
const original = dns.lookup;
dns.lookup = impl;
return () => { dns.lookup = original; };
}
function lookupOnce(results) {
let calls = 0;
const impl = (host, options, cb) => {
if (typeof options === "function") { cb = options; options = {}; }
calls++;
if (results instanceof Error) return process.nextTick(() => cb(results));
return process.nextTick(() => cb(null, results.map(r => ({ address: r, family: net.isIP(r) }))));
};
impl.callCount = () => calls;
return impl;
}
// Faithful replica of the request pattern wired into every nodes.js outbound
// site (pre-flight + guarded lookup on lib.request).
function primitiveStyleRequest(fullUrl) {
return new Promise((resolve) => {
const guardError = guard.assertNodeUrlHostAllowed(fullUrl);
if (guardError) return resolve({ status: 0, error: guardError.code });
const lib = fullUrl.startsWith("https:") ? require("node:https") : http;
const req = lib.request(fullUrl, { method: "GET", lookup: guard.guardedNodeLookup }, (res) => {
res.resume();
resolve({ status: res.statusCode });
});
req.on("timeout", () => resolve({ status: 0, error: "timeout" }));
req.on("error", (err) => resolve({ status: 0, error: err.code }));
req.end();
});
}
// ─── 1. IPv4 / IPv6 classification ──────────────────────────────────────────
test("classification: blocked IPv4 ranges", () => {
const blocked = [
"127.0.0.1", "127.8.8.8", // loopback
"10.1.2.3", // private
"172.16.0.1", "172.31.255.255", // private
"192.168.1.1", // private
"169.254.169.254", "169.254.0.1", // link-local / cloud metadata
"0.0.0.0", "0.1.2.3", // this-network / unspecified
"100.64.0.1", "100.127.255.254", // CGNAT
"198.18.5.5", "198.19.255.255", // benchmarking
"192.0.2.1", "198.51.100.7", "203.0.113.9", // documentation
"224.0.0.1", "239.255.255.255", "255.255.255.255", "240.0.0.1", // multicast/reserved
];
for (const ip of blocked) {
assert.ok(guard.forbiddenNodeIpReason(ip), `${ip} must be classified as forbidden`);
}
});
test("classification: public IPv4 and boundary neighbors stay allowed", () => {
const allowed = [
"8.8.8.8", "1.1.1.1", "93.184.216.34",
"172.32.0.1", // first public /12 above 172.31
"100.128.0.1", // first address above 100.64/10
"198.20.0.1", // first address above 198.18/15
"169.255.0.1", // above link-local
"192.169.0.1", // next to 192.168
"223.255.255.1", // below multicast
];
for (const ip of allowed) {
assert.strictEqual(guard.forbiddenNodeIpReason(ip), null, `${ip} must stay dialable`);
}
});
test("classification: blocked IPv6 including embedded-IPv4 smuggling", () => {
const blocked = [
"::", "::1", // unspecified / loopback
"fe80::1", "febf::1", // link-local
"fec0::1", // deprecated site-local
"fc00::1", "fd12:3456::1", // unique local
"ff02::1", // multicast
"2001:db8::1", // documentation
"::ffff:10.0.0.1", "::ffff:127.0.0.1", "::ffff:169.254.169.254", // mapped
"::127.0.0.1", // deprecated compatible
"2002:7f00:1::", "2002:0a00:0001::", // 6to4 wrapping 127.0.0.1 / 10.0.0.1
"64:ff9b::7f00:1", "64:ff9b::192.0.2.33", // nat64 wrapping private
"2001:0000:4136:e378:8000:63bf:3fff:fdd2", // teredo wrapping 192.0.2.45
"2001:0::", // teredo prefix, obfuscated tail -> reserved v4
"[::1]", "[fe80::1]", // bracketed forms
"fe80::1%eth0", // zoned link-local
];
for (const ip of blocked) {
assert.ok(guard.forbiddenNodeIpReason(ip), `${ip} must be classified as forbidden`);
}
});
test("classification: public IPv6 (incl. mapped/6to4 of public v4) stays allowed", () => {
const allowed = [
"2606:4700::1111",
"2001:4860:4860::8888",
"::ffff:8.8.8.8", // mapped public
"2002:0808:0808::", // 6to4 wrapping 8.8.8.8
"2001:4444::1", // teredo prefix boundary not matched (2001:0001)
];
for (const ip of allowed) {
assert.strictEqual(guard.forbiddenNodeIpReason(ip), null, `${ip} must stay dialable`);
}
});
test("classification: unparseable input fails closed", () => {
assert.ok(guard.forbiddenNodeIpReason("not-an-ip"));
assert.ok(guard.forbiddenNodeIpReason(""));
});
// ─── 2. host extraction ─────────────────────────────────────────────────────
test("extractNodeAddressHost: accepted shapes", () => {
const cases = [
["node.example.com", "node.example.com"],
["node.example.com:8080", "node.example.com"],
["http://node.example.com:8080/health", "node.example.com"],
["HTTPS://NODE.Example.COM", "node.example.com"],
["203.0.113.5", "203.0.113.5"],
["203.0.113.5:9000", "203.0.113.5"],
["[::1]:8080", "::1"],
["fe80::1", "fe80::1"],
["http://[2606:4700::1111]:443/x", "2606:4700::1111"],
["node.example.com./", "node.example.com"], // FQDN root dot
];
for (const [raw, expected] of cases) {
const result = guard.extractNodeAddressHost(raw);
assert.ok(result.ok, `${raw} must extract`);
assert.strictEqual(result.host, expected, `${raw} -> ${expected}`);
}
});
test("extractNodeAddressHost: rejected shapes", () => {
const rejected = [
"",
" ",
"host with spaces",
"http://user:pass@node.example.com/", // embedded credentials
"ftp://node.example.com/", // non-http scheme
"javascript:alert(1)",
"[::1", // unterminated bracket
"host:abc", // non-numeric port
"1.2.3.4:99999", // port above 65535
"1.2.3.4:0", // port 0 is not dialable
"http://2606:4700::1111:8080", // unbracketed IPv6+port — invalid URL
"fe80::1%eth0", // zone ID
];
for (const raw of rejected) {
const result = guard.extractNodeAddressHost(raw);
assert.strictEqual(result.ok, false, `${JSON.stringify(raw)} must be rejected`);
}
});
test("extractNodeAddressHost: ambiguous junk survives extraction but is caught by validation", async () => {
// "host:1:2" has two colons — indistinguishable from a bare IPv6 at
// extraction time — but fails the hostname charset check downstream.
const result = await guard.validateNodeAddressInput("host:1:2");
assert.strictEqual(result.ok, false);
assert.match(result.error, /not valid in a hostname/);
});
// ─── 3. creation/update-time validation ─────────────────────────────────────
test("validateNodeAddressInput: private literals rejected with env guidance", async () => {
for (const addr of ["127.0.0.1", "169.254.169.254", "10.0.0.9", "[fd00::1]", "192.168.1.10:8080"]) {
const result = await guard.validateNodeAddressInput(addr);
assert.strictEqual(result.ok, false, `${addr} must be rejected`);
assert.match(result.error, /ADPANEL_ALLOW_PRIVATE_NODES/);
}
});
test("validateNodeAddressInput: public literals accepted", async () => {
for (const addr of ["8.8.8.8", "http://[2606:4700::1111]:8080"]) {
const result = await guard.validateNodeAddressInput(addr);
assert.strictEqual(result.ok, true, `${addr} must be accepted`);
}
});
test("validateNodeAddressInput: bare addresses that cannot dial as validated rejected", async () => {
// These extract to a valid host but would NOT dial as validated: the panel
// builds `${proto}://${address}:${daemonPort}` for bare addresses, so an
// embedded port yields host:port:<daemon port> (never a valid URL) and a
// path suffix silently dials the default port. Each must fail closed with
// the actionable Daemon Port guidance — before any DNS is consulted.
const restore = stubDnsLookup(() => { throw new Error("DNS must not be consulted"); });
try {
for (const addr of ["1.2.3.4:99999", "1.2.3.4/", "8.8.8.8:8080", "[2606:4700::1111]:8080", "node.example.com:8080"]) {
const result = await guard.validateNodeAddressInput(addr);
assert.strictEqual(result.ok, false, `${addr} must be rejected`);
}
// Out-of-range ports are caught one layer earlier, by the extraction
// range check — still fail-closed, with the port-range guidance.
const outOfRange = await guard.validateNodeAddressInput("1.2.3.4:99999");
assert.match(outOfRange.error, /between 1 and 65535/);
for (const addr of ["1.2.3.4/", "8.8.8.8:8080", "[2606:4700::1111]:8080", "node.example.com:8080"]) {
const result = await guard.validateNodeAddressInput(addr);
assert.match(result.error, /Daemon Port/, `${addr} must carry the Daemon Port guidance`);
}
} finally {
restore();
}
});
test("validateNodeAddressInput: dialable bare hosts and full URLs still accepted", async () => {
for (const addr of ["8.8.8.8", "http://8.8.8.8:8080", "[2606:4700::1111]", "2606:4700::1111"]) {
const result = await guard.validateNodeAddressInput(addr);
assert.strictEqual(result.ok, true, `${addr} must be accepted`);
}
});
test("validateNodeAddressInput: reserved hostnames rejected without DNS", async () => {
const restore = stubDnsLookup(() => { throw new Error("DNS must not be consulted"); });
try {
for (const addr of ["localhost", "localhost:8080", "my.node.localhost", "daemon.local", "metadata.google.internal", "node.internal", "metadata"]) {
const result = await guard.validateNodeAddressInput(addr);
assert.strictEqual(result.ok, false, `${addr} must be rejected`);
}
} finally {
restore();
}
});
test("validateNodeAddressInput: hostname resolving to a private address rejected", async () => {
const restore = stubDnsLookup(lookupOnce(["93.184.216.34", "10.0.0.5"]));
try {
const result = await guard.validateNodeAddressInput("rebind.example.com");
assert.strictEqual(result.ok, false);
assert.match(result.error, /10\.0\.0\.5/);
} finally {
restore();
}
});
test("validateNodeAddressInput: hostname resolving to public addresses accepted", async () => {
const impl = lookupOnce(["93.184.216.34", "2606:4700::1111"]);
const restore = stubDnsLookup(impl);
try {
const result = await guard.validateNodeAddressInput("node.example.com");
assert.strictEqual(result.ok, true);
assert.deepStrictEqual(result.addresses, ["93.184.216.34", "2606:4700::1111"]);
} finally {
restore();
}
});
test("validateNodeAddressInput: unresolvable hostname rejected with clear error", async () => {
const err = new Error("queryA ESERVFAIL");
err.code = "ESERVFAIL";
const restore = stubDnsLookup(lookupOnce(err));
try {
const result = await guard.validateNodeAddressInput("ghost.example.com");
assert.strictEqual(result.ok, false);
assert.match(result.error, /Cannot resolve node address/);
} finally {
restore();
}
});
test("validateNodeAddressInput: env opt-in re-opens private targets", async () => {
const restore = stubDnsLookup(lookupOnce(["192.168.1.10"]));
process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1";
try {
const result = await guard.validateNodeAddressInput("192.168.1.10");
assert.strictEqual(result.ok, true);
const lanName = await guard.validateNodeAddressInput("mydaemon.local");
assert.strictEqual(lanName.ok, true);
} finally {
delete process.env.ADPANEL_ALLOW_PRIVATE_NODES;
restore();
}
});
test("validateNodeAddressListInput: syntax gate with cap", () => {
assert.strictEqual(guard.validateNodeAddressListInput(["203.0.113.5", "node.example.com"]).ok, true);
const bad = guard.validateNodeAddressListInput(["good.example.com", "bad host"]);
assert.strictEqual(bad.ok, false);
assert.match(bad.error, /Additional address/);
const tooMany = guard.validateNodeAddressListInput(Array.from({ length: 33 }, (_, i) => `203.0.113.${i + 1}`));
assert.strictEqual(tooMany.ok, false);
});
// ─── 4. guarded lookup ───────────────────────────────────────────────────────
test("guardedNodeLookup: literal private refused, literal public delivered", () => {
guard.clearInternalCaches();
return new Promise((resolveAll) => {
guard.guardedNodeLookup("127.0.0.1", {}, (err) => {
assert.ok(err);
assert.strictEqual(err.code, "EADPANEL_SSRF_BLOCKED");
guard.guardedNodeLookup("8.8.8.8", {}, (err2, address, family) => {
assert.ifError(err2);
assert.strictEqual(address, "8.8.8.8");
assert.strictEqual(family, 4);
resolveAll();
});
});
});
});
test("guardedNodeLookup: resolved private address refused (rebinding defense)", () => {
guard.clearInternalCaches();
return new Promise((resolveAll) => {
const restore = stubDnsLookup(lookupOnce(["93.184.216.34", "192.168.0.1"]));
guard.guardedNodeLookup("rebind.example.com", {}, (err) => {
restore();
assert.ok(err);
assert.strictEqual(err.code, "EADPANEL_SSRF_BLOCKED");
resolveAll();
});
});
});
test("guardedNodeLookup: getaddrinfo numeric shorthand caught at resolve time", () => {
// The stub simulates exactly what glibc getaddrinfo does with "2130706433".
guard.clearInternalCaches();
return new Promise((resolveAll) => {
const restore = stubDnsLookup(lookupOnce(["127.0.0.1"]));
guard.guardedNodeLookup("2130706433", {}, (err) => {
restore();
assert.ok(err);
assert.strictEqual(err.code, "EADPANEL_SSRF_BLOCKED");
resolveAll();
});
});
});
test("guardedNodeLookup: validated answers cached per family", () => {
guard.clearInternalCaches();
return new Promise((resolveAll) => {
const impl = lookupOnce(["93.184.216.34", "2606:4700::1111"]);
const restore = stubDnsLookup(impl);
guard.guardedNodeLookup("cached.example.com", {}, (err1, addr1) => {
assert.ifError(err1);
assert.strictEqual(addr1, "93.184.216.34"); // verbatim order preserved
guard.guardedNodeLookup("cached.example.com", {}, (err2) => {
assert.ifError(err2);
guard.guardedNodeLookup("cached.example.com", { family: 6 }, (err3, addr3) => {
restore();
assert.ifError(err3);
assert.strictEqual(addr3, "2606:4700::1111");
assert.strictEqual(impl.callCount(), 2); // v4-family result cached, v6 fetched once
resolveAll();
});
});
});
});
});
test("guardedNodeLookup: options.all returns the validated answer array", () => {
guard.clearInternalCaches();
return new Promise((resolveAll) => {
const restore = stubDnsLookup(lookupOnce(["93.184.216.34"]));
guard.guardedNodeLookup("all.example.com", { all: true }, (err, answers) => {
restore();
assert.ifError(err);
assert.deepStrictEqual(answers, [{ address: "93.184.216.34", family: 4 }]);
resolveAll();
});
});
});
test("guardedNodeLookup: DNS failure propagates", () => {
guard.clearInternalCaches();
return new Promise((resolveAll) => {
const restore = stubDnsLookup((host, opts, cb) => process.nextTick(() => cb(new Error("queryA ENOTFOUND"))));
guard.guardedNodeLookup("ghost.example.com", {}, (err) => {
restore();
assert.ok(err);
assert.strictEqual(err.code, undefined);
resolveAll();
});
});
});
// ─── 5. pre-flight matrix ────────────────────────────────────────────────────
test("assertNodeUrlHostAllowed: blocks literal private hosts, allows public/hostnames", () => {
const blocked = [
"http://127.0.0.1:8080/health",
"https://127.0.0.1:8443/v1/info",
"http://169.254.169.254/latest/meta-data/",
"http://[::1]:8080/",
"http://[::ffff:10.0.0.1]:8080/",
"http://10.0.0.3:9000/x",
"http://2130706433:8080/", // WHATWG URL canonicalizes to 127.0.0.1
"http://0x7f000001:8080/", // hex shorthand -> canonicalized -> blocked
"http://127.1:8080/", // shorthand -> canonicalized -> blocked
];
for (const url of blocked) {
assert.ok(guard.assertNodeUrlHostAllowed(url), `${url} must be blocked by pre-flight`);
}
const allowed = [
"https://8.8.8.8:8080/",
"http://node.example.com:8080/v1/info",
"https://[2606:4700::1111]:443/",
];
// 2130706434 canonicalizes to 127.0.0.2 — still loopback, still blocked.
assert.ok(guard.assertNodeUrlHostAllowed("http://2130706434:8080/"), "127.0.0.2 must be blocked");
for (const url of allowed) {
assert.strictEqual(guard.assertNodeUrlHostAllowed(url), null, `${url} must be allowed`);
}
});
// ─── 6. end-to-end through the primitive pattern ────────────────────────────
test("integration: primitive pattern blocks loopback node, delivers allowed traffic", () => {
guard.clearInternalCaches();
return new Promise((resolveAll) => {
const server = http.createServer((req, res) => {
res.writeHead(200, { "content-type": "application/json" });
res.end(JSON.stringify({ ok: true, uuid: "test-uuid" }));
});
server.listen(0, "127.0.0.1", () => {
const port = server.address().port;
(async () => {
// 1) Literal loopback target — the exact pattern every nodes.js
// outbound site uses — must fail with the guard error code.
const blocked = await primitiveStyleRequest(`http://127.0.0.1:${port}/health`);
assert.strictEqual(blocked.status, 0);
assert.strictEqual(blocked.error, "EADPANEL_SSRF_BLOCKED");
// 2) WHATWG-canonicalized shorthand must also fail.
const shorthand = await primitiveStyleRequest(`http://0x7f000001:${port}/health`);
assert.strictEqual(shorthand.status, 0);
assert.strictEqual(shorthand.error, "EADPANEL_SSRF_BLOCKED");
// 3) Metadata endpoint shape must fail before any socket is opened.
const metadata = await primitiveStyleRequest("http://169.254.169.254/latest/meta-data/");
assert.strictEqual(metadata.status, 0);
assert.strictEqual(metadata.error, "EADPANEL_SSRF_BLOCKED");
// 4) With the env opt-in the same loopback target connects — this
// proves the guarded lookup path (used for hostnames) delivers a
// working connection when the deployment allows private nodes.
process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1";
try {
guard.clearInternalCaches();
const allowed = await primitiveStyleRequest(`http://127.0.0.1:${port}/health`);
assert.strictEqual(allowed.status, 200);
assert.strictEqual(allowed.json, undefined); // no json parsing in replica
} finally {
delete process.env.ADPANEL_ALLOW_PRIVATE_NODES;
}
server.close();
resolveAll();
})().catch((err) => {
server.close();
resolveAll(Promise.reject(err));
});
});
});
});
test("integration: redirect responses are surfaced as-is (no silent following)", () => {
guard.clearInternalCaches();
return new Promise((resolveAll) => {
const server = http.createServer((req, res) => {
res.writeHead(302, { location: "http://169.254.169.254/latest/meta-data/" });
res.end();
});
server.listen(0, "127.0.0.1", () => {
const port = server.address().port;
(async () => {
process.env.ADPANEL_ALLOW_PRIVATE_NODES = "1";
try {
guard.clearInternalCaches();
const res = await primitiveStyleRequest(`http://127.0.0.1:${port}/redirect`);
// Node core http never follows redirects: the 302 is surfaced to
// the caller, which treats non-2xx as unreachable.
assert.strictEqual(res.status, 302);
} finally {
delete process.env.ADPANEL_ALLOW_PRIVATE_NODES;
}
server.close();
resolveAll();
})().catch((err) => {
server.close();
resolveAll(Promise.reject(err));
});
});
});
});