"use strict"; // adpanel:port-mismatch-advisor — unit tests for the diagnosable-rejection // module. The advisor fires ONLY on the one-sided brick shape of the explicit // -port CSRF rule (adpanel:csrf-port-awareness): an Origin carrying an // explicit non-default port while the serving port evidence is null. The // throttle mirrors _logCsrfExtraAllowedUse (index.js): per-key suppression // within the window, a global budget per window, and a key map capped with // clear-on-overflow — all driven by the injected clock, never by timers. // Wiring into the three rejection points (the CSRF middleware's 403 branch, // isSocketOriginAllowed and the cross-site read guard's rejection branch — // the guard receives the advisor via dependency injection; nodes.js binds // the guard without the dep) is pinned in tests/csrf-port-awareness.test.js. const test = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const { createPortMismatchAdvisor } = require("./origin-port-advisor"); // Controllable clock: the throttle windows are all anchored to `now()`. The // default start mirrors a real Date.now() magnitude so the `|| 0` default in // the per-key map reads as "long ago", exactly as it does in production. function makeClock(startMs = 1_000_000_000_000) { let t = startMs; return { now: () => t, advance(ms) { t += ms; }, }; } // ---- The fire condition — ONLY the one-sided brick shape ---------------------- test("advice fires only on the one-sided brick shape: explicit non-default origin port, null serving port", () => { const { advice } = createPortMismatchAdvisor(); const msg = advice({ originHeader: "https://panel.example.com:8443", servingPort: null }); assert.ok(typeof msg === "string" && msg.length > 0, "the brick shape must produce a diagnosis"); assert.ok(msg.length <= 200, "the diagnosis must fit securityLog's 200-char message budget in full"); assert.ok(msg.includes("panel.example.com:8443"), "the diagnosis names the origin host:port"); assert.ok( msg.includes("explicit port, serving Host none"), "the diagnosis states the one-sided brick shape" ); assert.ok( msg.includes("set PANEL_PUBLIC_URL to the exact browser scheme+host+port"), "the diagnosis gives the PANEL_PUBLIC_URL remedy verbatim" ); assert.ok( msg.includes("proxy_set_header X-Forwarded-Host $http_host;"), "the diagnosis gives the X-Forwarded-Host remedy verbatim, with the nginx line" ); }); // securityLog (index.js) slices the message at 200 chars BEFORE appending // " | IP | Path" — an over-long message is cut mid-diagnosis and BOTH // remedies are silently discarded. The message must therefore fit that // budget IN FULL even for an adversarial hostname: the attacker-controlled // host:port echo is capped, the static remedy text is budgeted around it. test("the full diagnosis plus BOTH remedies fit the 200-char securityLog budget even for a pathological hostname", () => { const { advice } = createPortMismatchAdvisor(); const pathological = advice({ originHeader: `https://${"a".repeat(200)}:8443`, servingPort: null }); assert.ok(pathological, "the brick shape fires regardless of host length"); // <= 199, not <= 200: the echo cap is 24 chars + ellipsis = 25, so the // true worst case is 199 — one char of margin under securityLog's // 200-char slice. A bare <= 200 bound passes a cap of 25 (or any 2-char // static-text growth) with the worst case sitting EXACTLY at the slice: // zero margin, the next header byte eats a remedy. Pinned tight so the // cap-25 mutation fails. assert.ok( pathological.length <= 199, `worst-case message must keep one char of margin under the 200-char securityLog slice (cap 24 + ellipsis => worst case 199; got ${pathological.length})` ); assert.ok( pathological.includes(`${"a".repeat(24)}…`), "an over-long host:port echo is capped at 24 chars with an ellipsis" ); assert.ok( pathological.includes("set PANEL_PUBLIC_URL to the exact browser scheme+host+port") && pathological.includes("proxy_set_header X-Forwarded-Host $http_host;"), "the echo cap must never eat either remedy" ); // The cap cuts in whole code points: an astral host on the schemeless- // fallback path (parseOriginHostPort's non-URL fallback keeps raw code // points a URL parse would punycode away) must never leave a lone // surrogate half in the log line — and the code-point cap must not grow // the echo past the UTF-16 budget either (an astral code point is 2 // units, so a bare 24-code-point cap would push this message past the // 200-char slice and lose BOTH remedies). const astral = advice({ originHeader: `a${"😀".repeat(12)}:8443`, servingPort: null }); assert.ok(astral, "the astral schemeless-fallback origin still fires"); assert.doesNotMatch( astral, /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? { const { advice } = createPortMismatchAdvisor(); // Both explicit — equal or different, the serving side answered, so the // operator's proxy config is visible and there is no brick to diagnose // (the different-explicit pair is a plain misroute, not this shape). assert.strictEqual(advice({ originHeader: "https://panel.example.com:8443", servingPort: "8443" }), null); assert.strictEqual(advice({ originHeader: "https://panel.example.com:8443", servingPort: "3000" }), null); // Serving-explicit vs portless origin: the mirror one-sided shape — // rejected by the shared rule too, but the evidence says the SERVING side // carries the odd port, not the browser, so this message would misname it. assert.strictEqual(advice({ originHeader: "https://panel.example.com", servingPort: "8443" }), null); // Both portless (default-port and NAT deployments) — nothing rejected. assert.strictEqual(advice({ originHeader: "https://panel.example.com", servingPort: null }), null); // Scheme-default ports normalize to absent on BOTH sides — a proxy writing // ":443" onto a header must not manufacture a diagnosis either. assert.strictEqual(advice({ originHeader: "https://panel.example.com:443", servingPort: null }), null); // Unparseable / no-evidence origins: nothing to name. assert.strictEqual(advice({ originHeader: "", servingPort: null }), null); assert.strictEqual(advice({ originHeader: "null", servingPort: null }), null); assert.strictEqual(advice({ originHeader: "chrome-extension://abcdef", servingPort: null }), null); assert.strictEqual(advice({ originHeader: "example.com:9999", servingPort: null }), null); // Missing inputs entirely (a caller bug must not crash a rejection path). assert.strictEqual(advice({}), null); assert.strictEqual(advice(), null); }); // ---- Throttle: per-key suppression, global budget, map cap -------------------- test("the same key is suppressed within the window and re-fires after it rolls over", () => { const clock = makeClock(); const { advice } = createPortMismatchAdvisor({ now: clock.now, intervalMs: 60 * 60 * 1000 }); const input = { originHeader: "https://panel.example.com:8443", servingPort: null }; const first = advice(input); assert.ok(first, "first sighting of a key emits"); assert.strictEqual(advice(input), null, "same key inside the window is suppressed"); assert.strictEqual(advice(input), null, "suppression repeats without state churn"); clock.advance(60 * 60 * 1000); assert.ok(advice(input), "the same key emits again once the window has rolled over"); }); test("distinct keys each emit, until the global budget for the window is exhausted", () => { const clock = makeClock(); const { advice } = createPortMismatchAdvisor({ now: clock.now, budgetMax: 3 }); const shape = (host) => ({ originHeader: `https://${host}:8443`, servingPort: null }); assert.ok(advice(shape("a.example.com")), "key 1 emits"); assert.ok(advice(shape("b.example.com")), "key 2 emits"); assert.ok(advice(shape("c.example.com")), "key 3 emits"); assert.strictEqual(advice(shape("d.example.com")), null, "the budget caps emissions within the window"); // Budget exhaustion must not consume per-key state: an already-seen key // stays suppressed when the window rolls, and a fresh key fires again. clock.advance(60 * 60 * 1000); assert.ok(advice(shape("d.example.com")), "a fresh window re-arms the budget"); }); test("the key map is capped with clear-on-overflow (attacker-cycled origins cannot grow it unbounded)", () => { const clock = makeClock(); const { advice } = createPortMismatchAdvisor({ now: clock.now, mapMax: 2, budgetMax: 100 }); const shape = (host) => ({ originHeader: `https://${host}:8443`, servingPort: null }); assert.ok(advice(shape("a.example.com"))); assert.ok(advice(shape("b.example.com"))); // The map is full; the next distinct key must clear it (dropping a: and b:) // rather than grow — the emission itself is the point, the memory is not. assert.ok(advice(shape("c.example.com"))); // The cleared keys lost their per-key timestamps, so they re-fire. assert.ok(advice(shape("a.example.com"))); }); test("a rejected emission (budget) does not plant per-key state that outlives the window", () => { // Budget-exhausted calls return before the per-key map is touched — the // throttle arms exactly like _logCsrfExtraAllowedUse, budget gate first. const clock = makeClock(); const { advice } = createPortMismatchAdvisor({ now: clock.now, budgetMax: 1, intervalMs: 1000 }); const shape = (host) => ({ originHeader: `https://${host}:8443`, servingPort: null }); assert.ok(advice(shape("a.example.com"))); assert.strictEqual(advice(shape("b.example.com")), null, "budget exhausted"); clock.advance(1000); assert.ok(advice(shape("b.example.com")), "b was never recorded, so it fires on the fresh window"); }); // ---- DI-cleanliness ------------------------------------------------------------ test("the advisor module is DI-clean: no require of index.js/db.js, one shared parse primitive", () => { const src = fs.readFileSync(path.join(__dirname, "origin-port-advisor.js"), "utf8"); assert.ok(!/require\((["'`])\.\.\/index\.js\1\)/.test(src) && !/require\((["'`])\.\.\/index\1\)/.test(src), "the advisor must never require the index.js monolith"); assert.ok(!/require\((["'`])[./]*db(\.js)?\1\)/.test(src), "the advisor must never require db.js"); assert.ok(!/require\((["'`])\.\.\/nodes(\.js)?\1\)/.test(src), "the advisor must never require the nodes.js monolith"); // One-true-home: the fire condition parses the origin through the shared // parseOriginHostPort, never a second copy of the parse. assert.ok(src.includes('require("./origin-host")') && src.includes("parseOriginHostPort"), "the fire condition must reuse the shared parse primitive from utils/origin-host.js"); assert.ok(!src.includes("new URL("), "the advisor must not parse headers with its own URL logic — parseOriginHostPort owns that"); // Call-driven throttle: no timers may exist in the module. assert.ok(!/setInterval|setTimeout|unref\(/.test(src), "the throttle is call-driven — no timers"); });