Files
Kelx/tests/remote-proxy-misconfig-warning.test.js
2026-11-30 16:32:37 +00:00

362 lines
21 KiB
JavaScript

"use strict";
// adpanel:remote-proxy-misconfig-warning — pins for the two WARN-ONLY
// advisories covering the remote-TLS-proxy misconfiguration class.
//
// The audit finding: with TRUST_PROXY at its default ("loopback") and TLS
// terminated at a REMOTE proxy, the panel mechanically (a) collapses every
// client into ONE login-throttle bucket — getRequestIp/getTrustedForwardedFor
// ignore X-Forwarded-For when the direct socket peer is not trusted
// (loopback/TRUSTED_PROXY_IPS), so the proxy's own address becomes the
// request IP for every client (the login request limiter and the per-source
// failure throttle both key on it) — and (b) ships session cookies without
// the Secure attribute — the auto predicate
// (cookieSecureForRequest / express-session secure:"auto") sees a plain-HTTP
// request at the node, because req.secure is false for a non-loopback peer.
// No boot warning covered the auto-mode case.
//
// Contract locked here:
// - WARN-ONLY: the trust resolution, the cookie flags and the throttle
// keying are untouched. The runtime helper must never mutate req, the
// session, cookies or limiter state.
// - Runtime half: ONE function (warnRemoteProxyMisconfigOnce), ONE call
// site (the per-request Secure-sync middleware — the cookieSecureForRequest
// choke point mounted app-wide BEFORE the /login routes), guard-first
// one-per-process flag (the rememberLoginRedisWarningPrinted pattern),
// firing on the precise observable "request claims https via
// X-Forwarded-Proto AND the direct peer is NOT trusted AND
// SESSION_COOKIE_SECURE is not explicitly true". The message names BOTH
// consequences (one shared login-throttle bucket; cookies without Secure)
// and BOTH remedies (TRUST_PROXY/TRUSTED_PROXY_IPS;
// SESSION_COOKIE_SECURE=true) and is phrased as a configuration hint —
// an attacker can forge XFP from a direct connection.
// - Amendment (adpanel:remote-proxy-trust-gate) — conscious structural-pin
// update for the mandated refactor: the signature condition (XFP https
// claim + untrusted direct peer) moved VERBATIM into
// isRemoteProxyTrustViolationRequest in index.js, the ONE home now shared
// with the OPT-IN enforcement gate (REMOTE_PROXY_REQUIRE_TRUST, default
// off — the warn-only posture here is untouched). The warn DELEGATES to
// the predicate; behavior, message and one-time latch are unchanged, and
// the condition may exist exactly ONCE across index.js + the gate module.
// - Boot half: the advisory console.warn lives INSIDE the existing
// `if (!SESSION_COOKIE_SECURE_EXPLICIT)` auto-mode block — it fires only
// when SESSION_COOKIE_SECURE is not explicitly true, i.e. never when the
// operator pinned it; it is a warn, never an exit (loopback/local
// deployments are correct as-is).
// - The boot advisory and the runtime warn are the ONLY two new warning
// sites; no second copy of either may appear.
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const INDEX_JS = path.join(__dirname, "..", "index.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
function endIndexOfBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker ${startMarker} not found`);
const bodyStart = source.indexOf("{", start);
let depth = 0;
for (let i = bodyStart; i < source.length; i += 1) {
if (source[i] === "{") depth += 1;
else if (source[i] === "}") {
depth -= 1;
if (depth === 0) return i + 1;
}
}
assert.fail(`unbalanced braces after marker ${startMarker}`);
}
function sliceBlock(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker ${startMarker} not found`);
return source.slice(start, endIndexOfBlock(source, startMarker));
}
// ---------- the runtime warn helper: source pins ----------
const RUNTIME_FN_MARKER = "function warnRemoteProxyMisconfigOnce(req)";
const runtimeFn = sliceBlock(indexSource, RUNTIME_FN_MARKER);
test("runtime warn: one helper, one module flag — the one-time pattern, not forked", () => {
assert.strictEqual(indexSource.indexOf(RUNTIME_FN_MARKER), indexSource.lastIndexOf(RUNTIME_FN_MARKER),
"warnRemoteProxyMisconfigOnce must be defined exactly once");
const flagDecl = "let remoteProxyMisconfigWarningPrinted = false;";
assert.strictEqual(indexSource.indexOf(flagDecl), indexSource.lastIndexOf(flagDecl),
"the one-time flag must be declared exactly once");
// Guard-first: after the first warn every call costs one flag read.
const guard = "if (remoteProxyMisconfigWarningPrinted) return;";
const bodyStart = runtimeFn.indexOf("{", runtimeFn.indexOf(RUNTIME_FN_MARKER));
const firstCode = runtimeFn.slice(bodyStart + 1).replace(/^\s+/, "");
assert.ok(firstCode.startsWith(guard),
"the flag guard must be the FIRST statement of the function");
});
test("runtime warn: fires only on claims-https + untrusted peer + not-explicitly-true, in that order", () => {
// Amendment (adpanel:remote-proxy-trust-gate): the signature condition
// moved VERBATIM into the shared predicate, and the warn DELEGATES. The
// pinned order now spans helper + predicate — the same chain, one home:
// the warn runs gate -> predicate-call -> flag -> warn, and the predicate
// runs xfp -> https-compare -> peer-read -> trust-check.
const gateAt = runtimeFn.indexOf("SESSION_COOKIE_SECURE_EXPLICIT && SESSION_COOKIE_SECURE");
const delegateAt = runtimeFn.indexOf("isRemoteProxyTrustViolationRequest(req)");
const setFlagAt = runtimeFn.indexOf("remoteProxyMisconfigWarningPrinted = true;");
const warnAt = runtimeFn.indexOf("console.warn(");
for (const [name, at] of [["secure-gate", gateAt], ["predicate-delegate", delegateAt], ["flag-set", setFlagAt], ["warn", warnAt]]) {
assert.ok(at > -1, `${name} step must exist in the helper`);
}
assert.ok(gateAt < delegateAt && delegateAt < setFlagAt && setFlagAt < warnAt,
"the warn must run gate -> predicate -> flag -> warn");
// The signature chain itself is pinned INSIDE its one-true-home predicate.
const predicateFn = sliceBlock(indexSource, "function isRemoteProxyTrustViolationRequest(req)");
const xfpAt = predicateFn.indexOf('req.headers && req.headers["x-forwarded-proto"]');
const claimedAt = predicateFn.indexOf('claimedProto !== "https"');
const peerAt = predicateFn.indexOf("getDirectRemoteIp(req)");
const trustedAt = predicateFn.indexOf("isTrustedProxyIp(directPeer)");
for (const [name, at] of [["xfp-read", xfpAt], ["https-compare", claimedAt], ["peer-read", peerAt], ["trust-check", trustedAt]]) {
assert.ok(at > -1, `${name} step must exist in the shared predicate`);
}
assert.ok(xfpAt < claimedAt && claimedAt < peerAt && peerAt < trustedAt,
"the condition chain must run xfp -> peer -> trust inside the predicate");
// No second copy: the old inline condition may not remain in the helper.
for (const token of ['req.headers && req.headers["x-forwarded-proto"]', 'claimedProto !== "https"', "getDirectRemoteIp(req)", "isTrustedProxyIp(directPeer)"]) {
assert.strictEqual(runtimeFn.includes(token), false,
`the old inline condition token must not remain in the warn helper: ${token}`);
}
// Flag set BEFORE the warn: a warn thrown/interleaved can never reprint.
assert.ok(runtimeFn.indexOf("console.warn(", warnAt + 1) === -1, "exactly ONE console.warn in the helper");
assert.ok(runtimeFn.includes("console.error(") === false, "no console.error in the helper (warn-only advisory)");
});
test("runtime warn: WARN-ONLY — never mutates the request, cookies, session or limiters", () => {
for (const forbidden of ["req.session", "cookie.secure", "Set-Cookie", "setHeader", "res.", "clearCookie", "increment", "decrement", "resetKey", "next("]) {
assert.strictEqual(runtimeFn.includes(forbidden), false,
`the warn helper must not contain "${forbidden}" — warn-only, no side effects`);
}
});
test("runtime warn: message names BOTH consequences and BOTH remedies, as a configuration hint", () => {
const warnText = runtimeFn.slice(runtimeFn.indexOf("console.warn(")).replace(/\s+/g, " ");
assert.ok(warnText.includes("[config]"), "the warn carries the [config] prefix");
assert.ok(warnText.includes("configuration hint"), "phrased as a hint (XFP is forgeable from a direct connection)");
assert.ok(warnText.includes("login-throttle bucket"), "consequence (a): the shared throttle bucket");
assert.ok(warnText.includes("without the Secure attribute"), "consequence (b): cookies ship non-Secure");
assert.ok(warnText.includes("TRUST_PROXY") && warnText.includes("TRUSTED_PROXY_IPS"), "remedy (a): add the proxy IP to trust");
assert.ok(warnText.includes("SESSION_COOKIE_SECURE=true"), "remedy (b): pin the Secure flag");
});
test("runtime warn: exactly ONE call site — the Secure-sync middleware, mounted BEFORE the /login routes", () => {
const callMarker = "warnRemoteProxyMisconfigOnce(req);";
const firstCall = indexSource.indexOf(callMarker);
assert.ok(firstCall > -1, "the call site must exist");
assert.strictEqual(indexSource.indexOf(callMarker, firstCall + 1), -1,
"exactly one call site — never a second wiring");
// The call rides the per-request Secure-sync middleware (the one
// cookieSecureForRequest caller that runs for EVERY request), which sits
// after app.use(sessionMiddleware) and before app.get("/login") /
// app.post("/login") — index.js executes app.use registrations top-to-bottom.
const sessionMiddlewareAt = indexSource.indexOf("app.use(sessionMiddleware);");
const getLoginAt = indexSource.indexOf('app.get("/login"');
const postLoginAt = indexSource.indexOf('app.post("/login"');
assert.ok(sessionMiddlewareAt > -1 && getLoginAt > -1 && postLoginAt > -1);
assert.ok(firstCall > sessionMiddlewareAt, "mounted after the session middleware");
assert.ok(firstCall < getLoginAt && firstCall < postLoginAt,
"mounted before both /login routes — the warn runs on the login surface");
// The host middleware's original behavior is intact (surgical addition).
const middleware = sliceBlock(indexSource, "app.use((req, res, next) => {\n // adpanel:remote-proxy-misconfig-warning");
assert.ok(middleware.includes("req.session.cookie.secure !== true && cookieSecureForRequest(req) === true"),
"the Upgrade-only Secure-sync condition is unchanged");
assert.ok(middleware.includes("next();"), "the middleware still chains");
});
// ---------- the boot advisory: source pins ----------
const AUTO_BLOCK_MARKER = "if (!SESSION_COOKIE_SECURE_EXPLICIT) {";
const autoBlock = sliceBlock(indexSource, AUTO_BLOCK_MARKER);
const BOOT_ADVISORY_TEXT = "[config] SESSION_COOKIE_SECURE is auto: if TLS terminates at a REMOTE proxy (not loopback), add its IP to TRUSTED_PROXY_IPS";
test("boot advisory: lives INSIDE the auto-mode block — fires only when SESSION_COOKIE_SECURE is not explicitly true", () => {
assert.ok(autoBlock.includes('console.warn("' + BOOT_ADVISORY_TEXT),
"the advisory console.warn must sit inside the existing !SESSION_COOKIE_SECURE_EXPLICIT block");
// The whole block is gated on auto mode, so the advisory cannot fire when
// the operator pinned SESSION_COOKIE_SECURE (true OR false): auto mode only.
assert.ok(!autoBlock.includes("SESSION_COOKIE_SECURE=true)") || autoBlock.indexOf("SESSION_COOKIE_SECURE=true)") < autoBlock.indexOf("console.warn"),
"no extra gating may break the auto-mode-only placement");
// It is an advisory: no exit, no throw, in the block.
assert.ok(!autoBlock.includes("process.exit"), "the advisory must never exit — loopback deployments are correct as-is");
});
test("boot advisory: message names the remote-proxy condition, all remedies and both consequences", () => {
const advisory = autoBlock.slice(autoBlock.indexOf(BOOT_ADVISORY_TEXT));
assert.ok(advisory.includes("REMOTE proxy (not loopback)"), "names the precise deployment that is broken");
assert.ok(advisory.includes("TRUSTED_PROXY_IPS") && advisory.includes("TRUST_PROXY") && advisory.includes("SESSION_COOKIE_SECURE=true"),
"all remedies: TRUSTED_PROXY_IPS (the complete shared-bucket fix), TRUST_PROXY (the cookie-half complement), SESSION_COOKIE_SECURE=true (the pin)");
assert.ok(advisory.includes("without Secure") && advisory.includes("one throttle bucket"), "both consequences");
});
test("boot advisory: exactly ONE copy — and the runtime warn remains the only other site", () => {
assert.strictEqual(indexSource.indexOf(BOOT_ADVISORY_TEXT), indexSource.lastIndexOf(BOOT_ADVISORY_TEXT),
"the boot advisory text must appear exactly once");
const bootTag = "// adpanel:remote-proxy-misconfig-warning — boot advisory";
assert.strictEqual(indexSource.indexOf(bootTag), indexSource.lastIndexOf(bootTag),
"the boot advisory carries its own adpanel comment exactly once");
// The topic is tagged at exactly three sites: the boot advisory, the
// runtime helper and its single middleware call site — no fourth copy.
assert.strictEqual(indexSource.split("adpanel:remote-proxy-misconfig-warning").length - 1, 3,
"exactly three tagged sites: boot block, runtime helper, middleware call");
});
// ---------- WARN-ONLY: nothing behavioral changed ----------
test("no behavioral change: trust resolution, cookie predicate and TRUST_PROXY default are untouched", () => {
// XFF stays ignored for untrusted peers — the collapse itself is unchanged.
assert.ok(indexSource.includes("function getTrustedForwardedFor(req) {\n const direct = getDirectRemoteIp(req);\n if (!isTrustedProxyIp(direct)) return \"\";"),
"getTrustedForwardedFor still ignores XFF for untrusted peers (unchanged)");
// The auto Secure predicate is unchanged (still mirrors express-session).
const cookieFn = sliceBlock(indexSource, "function cookieSecureForRequest(req)");
assert.ok(cookieFn.includes("if (SESSION_COOKIE_SECURE_EXPLICIT) return SESSION_COOKIE_SECURE;"));
assert.ok(cookieFn.includes("(req.connection && req.connection.encrypted) || req.secure === true"),
"the express-session secure:auto mirror is unchanged");
// The warn helper is NOT wired into the cookie predicate itself (its one
// call site is the middleware, pinned above).
assert.ok(!cookieFn.includes("warnRemoteProxyMisconfigOnce"),
"cookieSecureForRequest stays pure");
assert.ok(indexSource.includes('process.env.TRUST_PROXY || "loopback"'),
"the TRUST_PROXY default is unchanged");
});
// ---------- behavior: the REAL runtime helper under vm ----------
function buildRuntimeSandbox({ trustedProxyIpsEnv = "", secureExplicit = false, secureValue = false }) {
const helpers = indexSource.slice(
indexSource.indexOf("const TRUSTED_PROXY_IPS = new Set("),
endIndexOfBlock(indexSource, "function getLastForwardedValue(value, normalizer")
);
// Amendment (adpanel:remote-proxy-trust-gate): the warn delegates its
// signature condition to isRemoteProxyTrustViolationRequest, so the REAL
// runtime under test is predicate + latch + helper together.
const runtime = [
sliceBlock(indexSource, "function isRemoteProxyTrustViolationRequest(req)"),
sliceBlock(indexSource, "let remoteProxyMisconfigWarningPrinted = false;"),
].join("\n");
const warnings = [];
const context = vm.createContext({
net: require("node:net"),
console: { warn: (...a) => warnings.push(a.join(" ")), log: () => {}, error: () => {} },
process: { env: { TRUSTED_PROXY_IPS: trustedProxyIpsEnv } },
});
const script = [
`const SESSION_COOKIE_SECURE_EXPLICIT = ${JSON.stringify(secureExplicit)};`,
`const SESSION_COOKIE_SECURE = ${JSON.stringify(secureValue)};`,
helpers,
runtime,
"warnRemoteProxyMisconfigOnce",
].join("\n");
const fn = vm.runInContext(script, context);
return { fn, warnings };
}
function remoteProxyReq(xfp) {
return {
secure: false,
connection: { remoteAddress: "203.0.113.7" },
socket: { remoteAddress: "203.0.113.7" },
headers: xfp === undefined ? {} : { "x-forwarded-proto": xfp },
};
}
test("behavior: XFP https from an untrusted peer in auto mode — exactly ONE warn, then silence", () => {
const { fn, warnings } = buildRuntimeSandbox({});
fn(remoteProxyReq("https"));
assert.strictEqual(warnings.length, 1, "the first claiming request warns once");
fn(remoteProxyReq("https"));
fn(remoteProxyReq("https"));
assert.strictEqual(warnings.length, 1, "the one-time flag suppresses every later warn");
assert.ok(warnings[0].includes("login-throttle bucket") && warnings[0].includes("SESSION_COOKIE_SECURE=true"),
"the single warn carries both consequences and both remedies");
});
test("behavior: shipped local-nginx deployment (loopback peer) — no warn", () => {
const { fn, warnings } = buildRuntimeSandbox({});
fn({ connection: { remoteAddress: "127.0.0.1" }, socket: { remoteAddress: "127.0.0.1" }, headers: { "x-forwarded-proto": "https" } });
assert.strictEqual(warnings.length, 0, "the loopback proxy IS trusted — no hint");
fn({ connection: { remoteAddress: "::1" }, socket: { remoteAddress: "::1" }, headers: { "x-forwarded-proto": "https" } });
assert.strictEqual(warnings.length, 0, "IPv6 loopback is trusted too");
});
test("behavior: peer listed in TRUSTED_PROXY_IPS — no warn", () => {
const { fn, warnings } = buildRuntimeSandbox({ trustedProxyIpsEnv: "10.8.0.5, 192.0.2.9" });
fn({ connection: { remoteAddress: "10.8.0.5" }, socket: { remoteAddress: "10.8.0.5" }, headers: { "x-forwarded-proto": "https" } });
assert.strictEqual(warnings.length, 0, "an operator-trusted proxy is not a misconfiguration");
});
test("behavior: no https claim — no warn (plain HTTP clients are correct as-is)", () => {
const { fn, warnings } = buildRuntimeSandbox({});
fn(remoteProxyReq(undefined));
fn(remoteProxyReq("http"));
fn(remoteProxyReq("HTTP"));
fn(remoteProxyReq("https,http")); // LAST hop wins, matching getTrustedForwardedProto
assert.strictEqual(warnings.length, 0, "no https claim, no hint");
fn(remoteProxyReq("http,https"));
assert.strictEqual(warnings.length, 1, "a chain whose last hop claims https does warn");
});
test("behavior: SESSION_COOKIE_SECURE explicitly true — silent; explicitly false — still warns", () => {
const pinned = buildRuntimeSandbox({ secureExplicit: true, secureValue: true });
pinned.fn(remoteProxyReq("https"));
assert.strictEqual(pinned.warnings.length, 0, "the operator pinned the cookie half — both remedies are understood");
const disabled = buildRuntimeSandbox({ secureExplicit: true, secureValue: false });
disabled.fn(remoteProxyReq("https"));
assert.strictEqual(disabled.warnings.length, 1, "not-explicitly-true keeps the hint (the throttle collapse is live)");
});
test("behavior: IPv6-mapped IPv4 peer is normalized before the trust check", () => {
const { fn, warnings } = buildRuntimeSandbox({});
fn({ connection: { remoteAddress: "::ffff:203.0.113.7" }, socket: { remoteAddress: "::ffff:203.0.113.7" }, headers: { "x-forwarded-proto": "https" } });
assert.strictEqual(warnings.length, 1, "::ffff:-mapped remote proxy is still untrusted");
});
test("behavior: no socket address (e.g. UNIX socket) — no warn", () => {
const { fn, warnings } = buildRuntimeSandbox({});
fn({ connection: {}, socket: {}, headers: { "x-forwarded-proto": "https" } });
assert.strictEqual(warnings.length, 0, "an unresolvable peer must not produce the config hint");
});
test("behavior: forged XFP from a direct attacker connection — one hint, phrased as such", () => {
const { fn, warnings } = buildRuntimeSandbox({});
fn({ connection: { remoteAddress: "198.51.100.9" }, socket: { remoteAddress: "198.51.100.9" }, headers: { "x-forwarded-proto": "https" } });
assert.strictEqual(warnings.length, 1, "the observable is the same; the hint wording covers the false positive");
assert.ok(warnings[0].includes("configuration hint"), "the message does not assert certainty");
});
// ---------- behavior: the REAL boot advisory block under vm ----------
function runBootBlock(secureExplicit) {
const block = sliceBlock(indexSource, AUTO_BLOCK_MARKER);
const warnings = [];
const context = vm.createContext({
console: { warn: (...a) => warnings.push(a.join(" ")), log: () => {}, error: () => {} },
});
vm.runInContext([
`const SESSION_COOKIE_SECURE_EXPLICIT = ${JSON.stringify(secureExplicit)};`,
`const SESSION_COOKIE_SECURE = ${secureExplicit};`, // parseBoolean of a non-empty env value
block,
].join("\n"), context);
return warnings;
}
test("behavior: boot advisory fires once in auto mode, never when explicitly pinned", () => {
const auto = runBootBlock(false);
assert.strictEqual(auto.length, 1, "auto mode: exactly one boot advisory");
assert.ok(auto[0].includes("REMOTE proxy (not loopback)") && auto[0].includes("one throttle bucket"),
"the boot advisory carries the dictated wording");
assert.deepStrictEqual(runBootBlock(true), [], "explicitly pinned (true): silent");
});