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

178 lines
8.2 KiB
JavaScript

"use strict";
// adpanel:trust-proxy-boot-warning — pins for the TRUST_PROXY=true boot
// advisory (index.js boot region). The advisory warns (never exits) when the
// operator set TRUST_PROXY to the literal "true": Express then trusts every
// hop, so any client can forge req.ip with an X-Forwarded-For header and every
// req.ip-keyed limiter bucket becomes per-request forgeable, while the
// auth-critical budgets survive on the peer-trust resolver (loopback +
// TRUSTED_PROXY_IPS). Contract locked here:
//
// (a) the warn condition fires ONLY on the literal "true" after
// trim+lowercase. Source-pin of the exact condition expression, plus
// behavior of the REAL expression under vm: "true" / padded or
// mixed-case variants fire; unset, "", "false", "1", "loopback" and an
// explicit CIDR ("10.0.0.0/8") stay silent — "false", hop counts and
// explicit IP/CIDR lists are trust-breadth choices left to operator
// judgment, never boot-time misconfigurations to flag.
// (b) the advisory sits OUTSIDE the `if (!SESSION_COOKIE_SECURE_EXPLICIT)`
// auto-mode block — POSITION assertion with a hard reason: that block
// is sliced and evaluated standalone by
// tests/remote-proxy-misconfig-warning.test.js (runBootBlock) in a vm
// sandbox with NO process binding, so a process.env read inside it
// would crash that vm slice with a ReferenceError. The TRUST_PROXY
// advisory needs process.env and must stay out.
// (c) warn-only, ZERO behavior change: exactly ONE app.set("trust proxy",
// ...) wiring exists (the untouched parse near the top of index.js) and
// the advisory block itself sets nothing — no second app.set, no env
// write, no exit.
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));
}
// ---------- (a) the warn condition: source pin + behavior ----------
const WARN_CONDITION = 'String(process.env.TRUST_PROXY || "").trim().toLowerCase() === "true"';
const WARN_BLOCK_MARKER = `if (${WARN_CONDITION}) {`;
const warnBlock = sliceBlock(indexSource, WARN_BLOCK_MARKER);
test("trust-proxy boot warning: source pin — the condition is exactly the trim+lowercase literal compare, once", () => {
// sliceBlock succeeded, so the block starts with the exact pinned
// expression; this asserts the marker is also UNIQUE (no second warn wired
// off a widened condition copy elsewhere).
assert.strictEqual(
indexSource.indexOf(WARN_BLOCK_MARKER), indexSource.lastIndexOf(WARN_BLOCK_MARKER),
"the TRUST_PROXY=true warn condition must appear exactly once in index.js"
);
assert.ok(
warnBlock.includes("console.warn("),
"the advisory is a console.warn — never a log, error or exit"
);
assert.ok(
!warnBlock.includes("process.exit"),
"warn-only: the advisory must never exit — permissive TRUST_PROXY values are operator choices"
);
// No breadth widening inside the block: no includes/startsWith/regex may
// soften the literal compare.
assert.ok(
!warnBlock.includes(".includes(") && !warnBlock.includes(".startsWith(") && !warnBlock.includes(".match("),
"the condition must stay the exact literal compare — no widening helpers in the warn block"
);
});
function evalWarnCondition(envValue) {
// Extract the REAL condition text from the sliced block and evaluate it in
// a vm sandbox whose process.env carries only TRUST_PROXY — the same
// technique tests/remote-proxy-misconfig-warning.test.js uses for its boot
// block. No reimplementation of the expression is possible: it is cut from
// index.js.
const condition = warnBlock.slice("if (".length, warnBlock.lastIndexOf(") {"));
const context = vm.createContext({
console: { warn: () => {}, log: () => {}, error: () => {} },
process: { env: envValue === undefined ? {} : { TRUST_PROXY: envValue } },
});
return vm.runInContext(`Boolean(${condition})`, context);
}
test("trust-proxy boot warning: behavior — exactly the literal \"true\" fires; every other value is silent", () => {
for (const firing of ["true", " TRUE ", "True", "\ttrue\n", "TRUE"]) {
assert.strictEqual(
evalWarnCondition(firing), true,
`${JSON.stringify(firing)} must fire the advisory (trim + lowercase, then literal compare)`
);
}
for (const silent of [undefined, "", "false", "FALSE", "1", "0", "loopback", "10.0.0.0/8", "true,false", "truest", "trust-all"]) {
assert.strictEqual(
evalWarnCondition(silent), false,
`${JSON.stringify(silent)} must stay silent: "false", hop counts and explicit IP/CIDR lists are trust-breadth choices, not boot-time misconfigurations`
);
}
});
// ---------- (b) position: OUTSIDE the auto-mode block ----------
const AUTO_BLOCK_MARKER = "if (!SESSION_COOKIE_SECURE_EXPLICIT) {";
const autoBlockStart = indexSource.indexOf(AUTO_BLOCK_MARKER);
assert.ok(autoBlockStart > -1, "the auto-mode block must exist");
const autoBlock = sliceBlock(indexSource, AUTO_BLOCK_MARKER);
const autoBlockEnd = autoBlockStart + autoBlock.length;
const WARN_TEXT = "TRUST_PROXY=true trusts EVERY hop";
test("trust-proxy boot warning: position — OUTSIDE the SESSION_COOKIE_SECURE auto-mode block", () => {
const warnStart = indexSource.indexOf(WARN_BLOCK_MARKER);
assert.ok(
warnStart >= autoBlockEnd,
"the TRUST_PROXY advisory must sit strictly AFTER the end of the auto-mode block — that block is vm-sliced without a process binding by tests/remote-proxy-misconfig-warning.test.js (runBootBlock), and a process.env read inside it would throw ReferenceError there"
);
assert.ok(
!autoBlock.includes(WARN_TEXT),
"the advisory text must not appear inside the auto-mode block"
);
assert.ok(
!autoBlock.includes("process.env.TRUST_PROXY"),
"the auto-mode block must stay free of the TRUST_PROXY read so its standalone vm slice keeps working"
);
// Deliberate placement, documented at the site (mirrors the house style of
// tagging the reason where the code carries it).
assert.ok(
indexSource.includes("adpanel:trust-proxy-boot-warning"),
"the advisory carries its own adpanel tag in index.js"
);
});
// ---------- (c) warn-only: the trust proxy wiring is untouched ----------
const WIRING_STATEMENT = 'app.set("trust proxy", TRUST_PROXY);';
test("trust-proxy boot warning: ZERO behavior change — exactly one app.set wiring, untouched by the advisory", () => {
const first = indexSource.indexOf(WIRING_STATEMENT);
assert.ok(first > -1, 'the app.set("trust proxy", TRUST_PROXY) wiring must exist');
assert.strictEqual(
indexSource.indexOf(WIRING_STATEMENT, first + 1), -1,
"exactly ONE app.set(\"trust proxy\") statement — the advisory must never add a second wiring"
);
assert.ok(
indexSource.includes('const TRUST_PROXY = process.env.TRUST_PROXY || "loopback";'),
"the TRUST_PROXY default (loopback) is unchanged"
);
assert.ok(
!warnBlock.includes("app.set"),
"the advisory block must not touch Express settings"
);
assert.ok(
!warnBlock.includes("process.env.TRUST_PROXY ="),
"the advisory must never write the env var — it observes the same value Express received"
);
// The wiring sits near the top of index.js, long before the advisory: the
// advisory observes, the parse decides.
assert.ok(first < indexSource.indexOf(WARN_BLOCK_MARKER),
'the app.set("trust proxy") parse precedes the boot advisory');
});