Files
Kelx/tests/trusted-proxy-ip.test.js
T
2026-11-30 16:32:37 +00:00

243 lines
11 KiB
JavaScript

"use strict";
// Tests for utils/trusted-proxy-ip.js — the shared trusted-proxy-aware
// client-IP extraction that nodes.js's getRequestIp delegates to (mirroring
// index.js's private copy; see the module header for the sync contract).
//
// The trusted-proxy set is INJECTED per lookup via the `trustedProxyIps`
// option, so these tests depend neither on the repo's security.json nor on
// the ambient TRUSTED_PROXY_IPS environment. The env-derived production
// default is pinned separately: TRUSTED_PROXY_IPS is overwritten below
// BEFORE the module is required (it reads the env once at require time,
// exactly like index.js), and node --test runs each file in its own process,
// so the override cannot leak.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
process.env.TRUSTED_PROXY_IPS = "198.51.100.7";
const {
normalizeIp,
isTrustedProxyIp,
parseForwardedIpList,
getDirectRemoteIp,
getTrustedForwardedFor,
getRequestIp,
} = require("../utils/trusted-proxy-ip");
const ROOT = path.join(__dirname, "..");
const NODES_JS = fs.readFileSync(path.join(ROOT, "nodes.js"), "utf8");
function makeReq({ xff, remoteAddress } = {}) {
return {
headers: xff === undefined ? {} : { "x-forwarded-for": xff },
connection: { remoteAddress: remoteAddress === undefined ? undefined : remoteAddress },
socket: { remoteAddress: remoteAddress === undefined ? undefined : remoteAddress },
};
}
// ---------------------------------------------------------------------------
// Unit helpers
// ---------------------------------------------------------------------------
test("normalizeIp strips the ::ffff: IPv6-mapped prefix and trims", () => {
assert.equal(normalizeIp("::ffff:203.0.113.5"), "203.0.113.5");
assert.equal(normalizeIp(" 2001:db8::1 "), "2001:db8::1");
assert.equal(normalizeIp(""), "");
assert.equal(normalizeIp(undefined), "");
});
test("isTrustedProxyIp: loopback always trusted, injected set honored, empty/unknown peer refused", () => {
const options = { trustedProxyIps: ["10.0.0.2", "10.0.0.3"] };
assert.equal(isTrustedProxyIp("127.0.0.1"), true);
assert.equal(isTrustedProxyIp("::1"), true);
assert.equal(isTrustedProxyIp("::ffff:127.0.0.1"), true, "mapped loopback is normalized to loopback");
assert.equal(isTrustedProxyIp("10.0.0.2", options), true);
assert.equal(isTrustedProxyIp("10.0.0.3", options), true);
assert.equal(isTrustedProxyIp("10.0.0.4", options), false);
assert.equal(isTrustedProxyIp("10.0.0.2"), false, "not in the env-derived default set");
assert.equal(isTrustedProxyIp("", options), false);
assert.equal(isTrustedProxyIp(undefined, options), false);
});
test("parseForwardedIpList splits, normalizes and drops non-IP entries", () => {
assert.deepEqual(
parseForwardedIpList("::ffff:203.0.113.5, bogus, 2001:db8::1"),
["203.0.113.5", "2001:db8::1"]
);
assert.deepEqual(parseForwardedIpList(["127.0.0.1", " 9.9.9.9 "]), ["127.0.0.1", "9.9.9.9"]);
assert.deepEqual(parseForwardedIpList(undefined), []);
assert.deepEqual(parseForwardedIpList(""), []);
});
test("getDirectRemoteIp reads and normalizes the socket address", () => {
assert.equal(getDirectRemoteIp(makeReq({ remoteAddress: "::ffff:203.0.113.9" })), "203.0.113.9");
assert.equal(getDirectRemoteIp({}), "");
assert.equal(getDirectRemoteIp(makeReq({ remoteAddress: null })), "", "UNIX socket has no address");
});
// ---------------------------------------------------------------------------
// getRequestIp / getTrustedForwardedFor end-to-end
// ---------------------------------------------------------------------------
test("X-Forwarded-For is ignored when the direct peer is not a trusted proxy", () => {
const options = { trustedProxyIps: [] };
assert.equal(
getRequestIp(makeReq({ xff: "1.2.3.4", remoteAddress: "203.0.113.9" }), options),
"203.0.113.9"
);
});
test("a client-supplied fake XFF prefix does not win for a direct (untrusted) client", () => {
const options = { trustedProxyIps: ["9.9.9.9"] };
// Attacker connects directly but plants a chain ending in a "trusted" IP.
assert.equal(
getRequestIp(makeReq({ xff: "6.6.6.6, 9.9.9.9", remoteAddress: "203.0.113.9" }), options),
"203.0.113.9"
);
});
test("with a single trusted proxy the client IP is picked walking the chain backwards", () => {
const options = { trustedProxyIps: ["10.0.0.2"] };
const req = makeReq({ xff: "198.51.100.23, 10.0.0.2", remoteAddress: "10.0.0.2" });
assert.equal(getRequestIp(req, options), "198.51.100.23");
assert.equal(getTrustedForwardedFor(req, options), "198.51.100.23");
});
test("a client-supplied XFF prefix loses to the first untrusted hop behind trusted proxies", () => {
// Client 198.51.100.23 (forging "6.6.6.6" into XFF) -> proxy 10.0.0.3 ->
// proxy 10.0.0.2 -> panel. The backward walk stops at the real client, not
// at the leftmost forged value.
const options = { trustedProxyIps: ["10.0.0.2", "10.0.0.3"] };
const req = makeReq({
xff: "6.6.6.6, 198.51.100.23, 10.0.0.3",
remoteAddress: "10.0.0.2",
});
assert.equal(getRequestIp(req, options), "198.51.100.23");
});
test("multiple XFF entries across multiple trusted proxies resolve to the first untrusted hop", () => {
const options = { trustedProxyIps: ["10.0.0.2", "10.0.0.3", "10.0.0.4"] };
// Forged "6.6.6.6" prefix, real client 198.51.100.23, then two trusted
// middle proxies and the trusted direct peer — the backward walk skips the
// whole trusted tail and stops at the real client.
const req = makeReq({
xff: "6.6.6.6, 198.51.100.23, 10.0.0.4, 10.0.0.3",
remoteAddress: "10.0.0.2",
});
assert.equal(getRequestIp(req, options), "198.51.100.23");
// A foreign proxy inside the chain truncates the walk there: anything to
// its left (closer to the client) is untrustworthy by construction.
const truncated = makeReq({
xff: "198.51.100.23, 10.0.0.9, 10.0.0.4, 10.0.0.3",
remoteAddress: "10.0.0.2",
});
assert.equal(getRequestIp(truncated, options), "10.0.0.9");
});
test("an all-trusted chain falls back to the leftmost forwarded entry (index.js parity)", () => {
const options = { trustedProxyIps: ["10.0.0.2", "10.0.0.3"] };
const req = makeReq({ xff: "10.0.0.9, 10.0.0.3", remoteAddress: "10.0.0.2" });
assert.equal(getRequestIp(req, options), "10.0.0.9");
});
test("absent X-Forwarded-For falls back to the direct peer address", () => {
const options = { trustedProxyIps: ["10.0.0.2"] };
assert.equal(
getRequestIp(makeReq({ remoteAddress: "10.0.0.2" }), options),
"10.0.0.2"
);
});
test("non-IP X-Forwarded-For entries are dropped from the chain", () => {
const req = makeReq({ xff: "not-an-ip, 198.51.100.23", remoteAddress: "127.0.0.1" });
assert.equal(getRequestIp(req), "198.51.100.23");
});
test("array-valued and padded X-Forwarded-For headers are handled", () => {
// Array header (Express can surface repeated headers as an array) with
// padding; the middle hop is the env-pinned trusted proxy, so the walk
// reaches the real client.
const req = makeReq({ remoteAddress: "127.0.0.1" });
req.headers["x-forwarded-for"] = [" 198.51.100.23 , 198.51.100.7 "];
assert.equal(getRequestIp(req), "198.51.100.23");
});
test("IPv6-mapped IPv4 is normalized on the socket and header side", () => {
// A mapped loopback peer is still trusted...
assert.equal(
getRequestIp(makeReq({ xff: "198.51.100.23", remoteAddress: "::ffff:127.0.0.1" })),
"198.51.100.23"
);
// ...and a mapped forwarded hop is returned in normalized form.
assert.equal(
getRequestIp(makeReq({ xff: "::ffff:198.51.100.23, 127.0.0.1", remoteAddress: "127.0.0.1" })),
"198.51.100.23"
);
});
test("no socket address (UNIX socket) yields 'unknown', never an XFF value", () => {
assert.equal(getRequestIp(makeReq({ xff: "6.6.6.6", remoteAddress: null })), "unknown");
assert.equal(getRequestIp({ headers: {} }), "unknown");
});
// ---------------------------------------------------------------------------
// Production default loader (TRUSTED_PROXY_IPS env, pinned above)
// ---------------------------------------------------------------------------
test("TRUSTED_PROXY_IPS env entries are trusted by default; other peers are not", () => {
assert.equal(
getRequestIp(makeReq({ xff: "198.51.100.23", remoteAddress: "198.51.100.7" })),
"198.51.100.23",
"env-listed proxy: XFF honored"
);
assert.equal(
getRequestIp(makeReq({ xff: "198.51.100.23", remoteAddress: "198.51.100.8" })),
"198.51.100.8",
"non-listed peer: XFF ignored, socket address wins"
);
});
// ---------------------------------------------------------------------------
// Source pins: nodes.js wiring (radix fix + delegation + flush hardening)
// ---------------------------------------------------------------------------
test("nodes.js parses ACTIVITY_LOG_MAX_SERVERS with radix 10 ('5000' -> 5000)", () => {
assert.equal(parseInt("5000", 10), 5000, "the corrected radix must parse '5000' as 5000");
assert.equal(parseInt("5000", 15), 16875, "the old base-15 typo mangled '5000' (regression guard)");
assert.match(
NODES_JS,
/const ACTIVITY_LOG_MAX_SERVERS = parseInt\(process\.env\.ACTIVITY_LOG_MAX_SERVERS \|\| "", 10\) \|\| 5000;/,
"the radix must stay 10"
);
});
test("nodes.js getRequestIp delegates to the shared trusted-proxy util and keeps the sync comment", () => {
assert.match(
NODES_JS,
/} = require\("\.\/utils\/trusted-proxy-ip"\);/,
"nodes.js must require utils/trusted-proxy-ip.js"
);
const fn = NODES_JS.match(/function getRequestIp\(req\) \{[\s\S]*?\n\}/);
assert.ok(fn, "getRequestIp must exist in nodes.js");
assert.match(fn[0], /getTrustedForwardedFor\(req\)/);
assert.match(fn[0], /getDirectRemoteIp\(req\)/);
assert.match(fn[0], /"unknown"/);
assert.doesNotMatch(fn[0], /x-forwarded-for/i, "getRequestIp must not parse XFF itself");
assert.doesNotMatch(fn[0], /req\.ip/, "req.ip must not be consulted (it can be XFF-derived)");
assert.match(NODES_JS, /MUST BE KEPT IN SYNC|MUST be KEPT IN SYNC|keep utils\/trusted-proxy-ip\.js.*in sync|kept in sync/i,
"the sync-with-index.js comment must mark the mirror");
});
test("nodes.js flushActivityLogs keeps the requeue/backoff/in-flight machinery", () => {
assert.match(NODES_JS, /activityLogInFlightFlushes/, "per-server in-flight flush guard");
assert.match(NODES_JS, /requeueFailedActivityLogEntries/, "failed batches must be re-buffered");
assert.match(NODES_JS, /armActivityLogRetryTimer/, "retries must be re-armed with backoff");
assert.match(NODES_JS, /ACTIVITY_LOG_MAX_WRITE_RETRY_INTERVAL_MS/, "backoff must be capped");
assert.match(NODES_JS, /module\.exports\.flushActivityLogs = flushActivityLogs;/,
"flush must stay exported for index.js's activity reader");
});