"use strict"; // adpanel:csrf-port-awareness — regression tests for the explicit-port rule // shared by the cross-origin trust decisions: // // - index.js sameOriginProtection (the panel-wide CSRF write check), // - utils/cross-site-read-guard.js rejectCrossSiteRead (the shared CSRF-read // guard), and // - index.js isSocketOriginAllowed (the Socket.IO handshake origin check — // a same-SITE sibling page's WS handshake carries the SameSite=Lax // cookies, so an accepted socket speaks with the admin's whole session). // // The hole: every surface host-matches port-blind (hostAllowed / bare-host // equality semantics — hosts are compared WITHOUT scheme/port/path), so an // Origin from the SAME host on a DIFFERENT port — another service on this // machine, or a sibling loopback process — matched requestHost and passed // while riding the victim's SameSite=Lax session cookie (SameSite ignores // ports; sec-fetch-site "same-site" is deliberately not trusted by any // surface). // // The fix: ONE shared rejection decision, csrfPortMismatch in // utils/origin-host.js (the ONE home for header-host parsing, so the rule and // its escapes cannot drift between the two surfaces). A cookie-bearing // request is rejected when the evidence origin's port and the serving host's // port are not EQUAL — differing explicit ports, and (the one-sided gap the // rule closes) an explicit non-default port on exactly one side while the // other carries no port evidence. Deliberate boundaries, each pinned below: // - cookie-less requests keep today's no-cookie posture (no ambient // authority — nothing to ride); // - a browser-attested same-origin fetch wins (that attestation includes // the port); // - CSRF_ALLOWED_HOSTS trust stays port-blind (the parser normalizes // entries to bare hostnames — operator trust is the operator's knob); // - the PANEL_PUBLIC_URL host+port escape covers Host-rewriting proxies // (the documented proxy-rewrite escape, extended for ports); // - both-portless (default-port and NAT/port-forward deployments) and // both-explicit-equal requests keep passing; one-sided explicit ports // REJECT, because browsers always send the explicit port in BOTH Origin // and Host when it is non-default, so one-sided is either a same-host // sibling service (the attack) or a rewriting proxy (served by the // PANEL_PUBLIC_URL escape — the documented remedy); // - the loopback alias grant (adpanel:csrf-localhost-scoping) stays // host-level and cannot bypass the rule. // // Three layers, matching this repo's conventions (see // tests/csrf-localhost-scoping.test.js): // - Unit: the port-preserving primitives and the shared decision in // utils/origin-host.js (pure functions, required directly). // - Functional: the REAL guard middleware driven with fake req/res objects // under a controlled trust context, and the REAL socket origin check // extracted from index.js source and evaluated in a vm sandbox (index.js // cannot be required in-process — it boots servers on require — but the // handshake check is a small self-contained block whose dependencies are // exactly the utils/origin-host functions index.js itself binds). // - Source-level: index.js must derive ports from the same headers it // derives hosts from, route the decision through the shared // csrfPortMismatch, run it BEFORE the loopback alias grant, and inject // the PANEL_PUBLIC_URL port into the guard's trust context. // NODES_CORS_ORIGINS is parsed at module load — it must be set BEFORE the // guard module is required for the exact-origin exemption test below. process.env.NODES_CORS_ORIGINS = "https://app.example.com:8443"; const test = require("node:test"); const { afterEach, after } = require("node:test"); const assert = require("node:assert"); const fs = require("node:fs"); const path = require("node:path"); const vm = require("node:vm"); const { extractHostnameFromHeader, parseOriginHost, normalizeHostLower, parseOriginHostPort, extractHeaderHostPort, explicitPortsDiffer, csrfPortMismatch, } = require("../utils/origin-host"); const { rejectCrossSiteRead, setCrossOriginTrustContext, } = require("../utils/cross-site-read-guard"); const { createPortMismatchAdvisor } = require("../utils/origin-port-advisor"); // The guard module holds the trust context in module state; every test sets // its own context and afterEach restores the standalone defaults so this file // never leaks a widened (or narrowed) context into another suite. afterEach(() => setCrossOriginTrustContext({})); after(() => setCrossOriginTrustContext({})); // ---- Harness ----------------------------------------------------------------- function runGuard(headers, ctx) { setCrossOriginTrustContext(ctx || {}); const req = { headers }; const res = { statusCode: 0, body: null, status(code) { this.statusCode = code; return this; }, json(payload) { this.body = payload; return this; }, }; let nextCalled = false; rejectCrossSiteRead(req, res, () => { nextCalled = true; }); return { nextCalled, statusCode: res.statusCode, body: res.body }; } const GUARD_403 = { error: "cross-site request blocked" }; // ---- Unit: the port-preserving primitives (utils/origin-host.js) ------------- test("parseOriginHostPort keeps explicit ports and normalizes scheme defaults away", () => { assert.deepStrictEqual(parseOriginHostPort("http://192.0.2.10:9999"), { host: "192.0.2.10", port: "9999" }); assert.deepStrictEqual(parseOriginHostPort("https://Panel.Example.com:8443"), { host: "panel.example.com", port: "8443" }); // A browser never sends the scheme's default port explicitly in Origin. assert.deepStrictEqual(parseOriginHostPort("http://panel.example.com:80"), { host: "panel.example.com", port: null }); assert.deepStrictEqual(parseOriginHostPort("https://panel.example.com:443"), { host: "panel.example.com", port: null }); assert.deepStrictEqual(parseOriginHostPort("https://panel.example.com"), { host: "panel.example.com", port: null }); // Explicit NON-default for the scheme stays (https on 80 is not a default). assert.deepStrictEqual(parseOriginHostPort("https://panel.example.com:80"), { host: "panel.example.com", port: "80" }); assert.deepStrictEqual(parseOriginHostPort("http://[::1]:3000"), { host: "::1", port: "3000" }); assert.deepStrictEqual(parseOriginHostPort("http://[::1]"), { host: "::1", port: null }); }); test("parseOriginHostPort yields null for everything that is no usable evidence", () => { assert.strictEqual(parseOriginHostPort(""), null); assert.strictEqual(parseOriginHostPort("null"), null); assert.strictEqual(parseOriginHostPort("undefined"), null); // Opaque / non-http(s) schemes: no port evidence (the host matchers never // see these hosts in the allowlist either). assert.strictEqual(parseOriginHostPort("chrome-extension://abcdef"), null); assert.strictEqual(parseOriginHostPort("ftp://files.example.com:21"), null); // Hostname-style fallback (URL parse threw) mirrors parseOriginHost: // evidence pair only when parseOriginHost itself would see a host. // "192.0.2.10:9999" cannot parse as a URL (schemes cannot start with a // digit), so it reaches the fallback and yields a pair. assert.deepStrictEqual(parseOriginHostPort("192.0.2.10:9999"), { host: "192.0.2.10", port: "9999" }); // "example.com:9999" DOES parse as a URL — with scheme "example.com" and no // host — so parseOriginHost sees no host here and no pair may exist. assert.strictEqual(parseOriginHostPort("example.com:9999"), null); assert.strictEqual(parseOriginHostPort("::1"), null, "a bare unbracketed IPv6 literal yields no host in parseOriginHost, so no pair here either"); }); test("extractHeaderHostPort is bracket-aware, takes the first entry, and normalizes header defaults", () => { assert.deepStrictEqual(extractHeaderHostPort("panel.example.com:8443"), { host: "panel.example.com", port: "8443" }); assert.deepStrictEqual(extractHeaderHostPort("panel.example.com"), { host: "panel.example.com", port: null }); // Header values carry no scheme, so BOTH well-known defaults count as // explicit-port-absent (a proxy writing ":80"/":443" must not manufacture // a mismatch against a default-port Origin). assert.deepStrictEqual(extractHeaderHostPort("panel.example.com:80"), { host: "panel.example.com", port: null }); assert.deepStrictEqual(extractHeaderHostPort("panel.example.com:443"), { host: "panel.example.com", port: null }); assert.deepStrictEqual(extractHeaderHostPort("[::1]:3000"), { host: "::1", port: "3000" }); assert.deepStrictEqual(extractHeaderHostPort("[::1]"), { host: "::1", port: null }); // X-Forwarded-Host list: first entry (callers pass an ALREADY-trusted // single entry from getTrustedForwardedHost for the serving port). assert.deepStrictEqual(extractHeaderHostPort("a.example.com, b.example.com:9"), { host: "a.example.com", port: null }); assert.strictEqual(extractHeaderHostPort(""), null); assert.strictEqual(extractHeaderHostPort(undefined), null); // Bare unbracketed IPv6: no usable port evidence. assert.deepStrictEqual(extractHeaderHostPort("::1"), { host: "::1", port: null }); }); test("explicitPortsDiffer rejects only when both sides carry an explicit port (the both-explicit vocabulary; the shared decision is stricter)", () => { assert.strictEqual(explicitPortsDiffer("9999", "3000"), true); assert.strictEqual(explicitPortsDiffer("3000", "3000"), false); assert.strictEqual(explicitPortsDiffer(null, "3000"), false); assert.strictEqual(explicitPortsDiffer("3000", null), false); assert.strictEqual(explicitPortsDiffer(null, null), false); }); // ---- Unit: the ONE shared decision -------------------------------------------- test("csrfPortMismatch: mismatched explicit ports with cookies reject; every escape passes", () => { const base = { originPair: { host: "192.0.2.10", port: "9999" }, servingPort: "3000", hasCookie: true, sameOriginFetch: false, portBlindTrust: false, publicHost: "", publicPort: null, }; assert.strictEqual(csrfPortMismatch(base), true, "the residual: same host, different explicit port, cookie-bearing"); // Cookie-less: no ambient authority — same posture as the no-evidence paths. assert.strictEqual(csrfPortMismatch({ ...base, hasCookie: false }), false); // Browser-attested same-origin fetch (includes the port) wins. assert.strictEqual(csrfPortMismatch({ ...base, sameOriginFetch: true }), false); // Operator trust stays port-blind (CSRF_ALLOWED_HOSTS / exact CORS origin). assert.strictEqual(csrfPortMismatch({ ...base, portBlindTrust: true }), false); // PANEL_PUBLIC_URL host+port escape: exact match passes even when the Host // header disagrees; a different port on the same public host does not. assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: "8443" }, publicHost: "panel.example.com", publicPort: "8443", }), false); assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: "9999" }, publicHost: "panel.example.com", publicPort: "8443", }), true); // One-sided: an explicit port on exactly one side with no port evidence on // the other is a mismatch now (the closed gap — dedicated test below). assert.strictEqual(csrfPortMismatch({ ...base, servingPort: null }), true); assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "x", port: null } }), true); // No evidence pair at all: inert. assert.strictEqual(csrfPortMismatch({ ...base, originPair: null }), false); assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "", port: "9999" } }), false); // The escape is inert without a configured public host. assert.strictEqual(csrfPortMismatch({ ...base, publicHost: "", publicPort: null }), true); }); test("csrfPortMismatch: one-sided explicit port is a mismatch; both-portless and equal-explicit pass", () => { const base = { hasCookie: true, sameOriginFetch: false, portBlindTrust: false, publicHost: "", publicPort: null, }; // The closed gap: panel reached on https://panel.example.com (Host header // portless), sibling page on https://panel.example.com:8443 — reject. assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: "8443" }, servingPort: null, }), true, "explicit origin port vs portless serving Host"); // Mirror shape: portless Origin against an explicit serving port. assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: null }, servingPort: "8443", }), true, "portless origin vs explicit serving Host"); // Both portless: default-port and NAT/port-forward deployments keep working. assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: null }, servingPort: null, }), false); // Both explicit and equal: pass. assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: "8443" }, servingPort: "8443", }), false); // Both explicit and different: reject (unchanged). assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: "8443" }, servingPort: "3000", }), true); // Accepted edge (documented, deliberately not fixed): plain HTTP on port // 443 — the browser sends the non-default-for-scheme port explicitly in // Origin while the scheme-less header side normalizes ":443" to absent, so // the one-sided rule reads it as a sibling port. A misconfiguration; the // remedy is the PANEL_PUBLIC_URL escape, pinned right below. assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: "443" }, servingPort: null, }), true, "http-on-443 misconfiguration behind a rewriting proxy is rejected"); // The PANEL_PUBLIC_URL escape still rescues the legitimate rewriting proxy: // one-sided origin vs portless serving Host, exact public host+port match. assert.strictEqual(csrfPortMismatch({ ...base, originPair: { host: "panel.example.com", port: "8443" }, servingPort: null, publicHost: "panel.example.com", publicPort: "8443", }), false); }); // ---- Functional: the real guard enforces the shared rule ---------------------- test("guard: cookie-bearing read from the same host on a different explicit port is rejected", () => { const out = runGuard({ host: "192.0.2.10:3000", origin: "http://192.0.2.10:9999", cookie: "connect.sid=victim-session", }); assert.strictEqual(out.nextCalled, false, "a sibling service's page must not ride the SameSite=Lax session cookie"); assert.strictEqual(out.statusCode, 403); assert.deepStrictEqual(out.body, GUARD_403); }); test("guard: equal explicit ports still pass (same host, same port)", () => { const out = runGuard({ host: "192.0.2.10:3000", origin: "http://192.0.2.10:3000", cookie: "connect.sid=victim-session", }); assert.strictEqual(out.nextCalled, true); }); test("guard: Referer-only evidence is held to the same explicit-port standard", () => { const out = runGuard({ host: "192.0.2.10:3000", referer: "http://192.0.2.10:9999/attack.html", cookie: "connect.sid=victim-session", }); assert.strictEqual(out.nextCalled, false, "the evidence port comes from the SAME header the host came from (Referer here)"); assert.strictEqual(out.statusCode, 403); assert.deepStrictEqual(out.body, GUARD_403); }); test("guard: one-sided explicit port is rejected; both-portless and header-default shapes pass", () => { // The closed gap: an explicit-port Origin against a portless serving Host // header — a sibling HTTPS service on the same hostname riding the // SameSite=Lax session cookie. const oneSided = runGuard({ host: "panel.example.com", origin: "https://panel.example.com:8443", cookie: "connect.sid=victim-session", }); assert.strictEqual(oneSided.nextCalled, false, "a same-host sibling page on an explicit port must not ride the cookie against a portless Host"); assert.strictEqual(oneSided.statusCode, 403); assert.deepStrictEqual(oneSided.body, GUARD_403); // Serving Host header carries a default port explicitly (proxy rewrite), // Origin does not (browser never sends it): both normalize to absent — // portless on both sides keeps passing. assert.strictEqual(runGuard({ host: "panel.example.com:443", origin: "https://panel.example.com", cookie: "connect.sid=victim-session", }).nextCalled, true); // Neither side has a port: the pre-existing same-host behavior. assert.strictEqual(runGuard({ host: "panel.example.com", origin: "https://panel.example.com", cookie: "connect.sid=victim-session", }).nextCalled, true); }); test("guard: a cookie-less mismatched-port request keeps today's no-cookie posture", () => { // No ambient authority — nothing to ride. The guard passes it into the // ordinary branches and the auth gate, exactly as the no-evidence path // treats anonymous requests. const out = runGuard({ host: "192.0.2.10:3000", origin: "http://192.0.2.10:9999", }); assert.strictEqual(out.nextCalled, true); }); test("guard: browser-attested same-origin fetch wins over a contradictory port", () => { // sec-fetch-site same-origin includes the port (fetch spec); the host // branches already let this attestation win. const out = runGuard({ host: "192.0.2.10:3000", origin: "http://192.0.2.10:9999", "sec-fetch-site": "same-origin", cookie: "connect.sid=victim-session", }); assert.strictEqual(out.nextCalled, true); }); test("guard: loopback sibling process on a different port is rejected; same-port alias passes", () => { // The loopback variant of the residual: a panel served on localhost:3000 // and a sibling local process's page on localhost:9999 — the host matchers // see "localhost" on both sides and the loopback alias grant // (adpanel:csrf-localhost-scoping) would open, but the port rule runs ahead // of it. const sibling = runGuard({ host: "localhost:3000", origin: "http://localhost:9999", cookie: "connect.sid=victim-session", }); assert.strictEqual(sibling.nextCalled, false, "the alias grant must not bypass the explicit-port rule"); assert.strictEqual(sibling.statusCode, 403); assert.deepStrictEqual(sibling.body, GUARD_403); // A TRUE same-port loopback origin (the desktop localhost alias grant's // actual purpose) still passes. assert.strictEqual(runGuard({ host: "localhost:3000", origin: "http://127.0.0.1:3000", cookie: "connect.sid=victim-session", }).nextCalled, true); }); test("guard: CSRF_ALLOWED_HOSTS trust stays port-blind", () => { // The allowlist parser normalizes entries to bare hostnames — an operator // endorsing a host endorses every port on it. The entry must keep passing // a mismatched-port request (and the audit posture of the middleware is // unchanged; see the source pins below). const out = runGuard({ host: "panel.example.com:3000", origin: "https://panel.example.com:9999", cookie: "connect.sid=victim-session", }, { extraAllowedHosts: ["panel.example.com"] }); assert.strictEqual(out.nextCalled, true, "operator trust must not silently become port-aware"); // Without the entry the same request is a plain host mismatch (and the // port rule rejects it before the host branches). const blocked = runGuard({ host: "panel.example.com:3000", origin: "https://panel.example.com:9999", cookie: "connect.sid=victim-session", }); assert.strictEqual(blocked.nextCalled, false); assert.strictEqual(blocked.statusCode, 403); assert.deepStrictEqual(blocked.body, GUARD_403); }); test("guard: PANEL_PUBLIC_URL host+port escape passes a Host-rewriting proxy", () => { // Proxy serves https://panel.example.com:8443 publicly but rewrites Host to // internal:3000; the legit same-origin page sends Origin // https://panel.example.com:8443. Without the escape this setup would be // newly bricked by the port rule. const ctx = { panelPublicHost: "panel.example.com", panelPublicPort: "8443" }; assert.strictEqual(runGuard({ host: "internal:3000", origin: "https://panel.example.com:8443", cookie: "connect.sid=victim-session", }, ctx).nextCalled, true, "the documented proxy-rewrite escape, extended for ports"); // The trusted X-Forwarded-Host arm of the serving-port derivation: the // resolver returns the already-trusted single entry, and its explicit port // is the serving port. assert.strictEqual(runGuard({ host: "internal:3000", origin: "https://panel.example.com:8443", cookie: "connect.sid=victim-session", }, { panelPublicHost: "other.example.com", resolveTrustedForwardedHost: () => "panel.example.com:8443", }).nextCalled, true, "serving port follows the trusted forwarded host"); assert.strictEqual(runGuard({ host: "internal:3000", origin: "https://panel.example.com:9999", cookie: "connect.sid=victim-session", }, { resolveTrustedForwardedHost: () => "panel.example.com:8443", }).statusCode, 403, "a different port on the forwarded host is still a mismatch"); // The escape must not open for a different port on the public host. const wrongPort = runGuard({ host: "internal:3000", origin: "https://panel.example.com:9999", cookie: "connect.sid=victim-session", }, ctx); assert.strictEqual(wrongPort.nextCalled, false); assert.strictEqual(wrongPort.statusCode, 403); assert.deepStrictEqual(wrongPort.body, GUARD_403); }); test("guard: an exact NODES_CORS_ORIGINS origin stays port-blind; a sibling port does not inherit it", () => { // The operator endorsed the full scheme+host+port string, so the endorsed // client keeps working behind a Host-rewriting proxy exactly as before the // port rule existed (the CORS layer echoes ACAO for that exact origin). const ctx = { resolveTrustedForwardedHost: () => "internal:3000" }; assert.strictEqual(runGuard({ host: "internal:3000", origin: "https://app.example.com:8443", cookie: "connect.sid=victim-session", }, ctx).nextCalled, true, "exact CORS origin match is port-blind trust"); // A forged Origin that merely shares the host does NOT exact-match — it // stays port-checked (and host-checked). const sibling = runGuard({ host: "internal:3000", origin: "https://app.example.com:9999", cookie: "connect.sid=victim-session", }, ctx); assert.strictEqual(sibling.nextCalled, false); assert.strictEqual(sibling.statusCode, 403); assert.deepStrictEqual(sibling.body, GUARD_403); }); // ---- Functional: the REAL socket origin check (extracted from index.js) ---- // index.js cannot be required in-process (it boots servers on require), but // the handshake origin check is a small self-contained block: the // PANEL_PUBLIC_URL consts, the SOCKET_ALLOWED_ORIGINS const derived from its // env var, normalizeHostForSocket and isSocketOriginAllowed. The blocks are // sliced from the REAL index.js at test time and evaluated in a vm sandbox // wired to the SAME utils/origin-host functions index.js binds at module top, // so behavior pinned here cannot drift from what ships. The two scripts share // one context: the second sees the first's top-level consts through the // realm's global lexical environment (the same technique // tests/node-api-gate-case-bypass.test.js uses). const RAW_INDEX_SOURCE = fs.readFileSync(path.join(__dirname, "..", "index.js"), "utf8"); function extractPublicUrlConsts(src) { const start = src.indexOf("const _CSRF_PANEL_PUBLIC_HOST"); assert.ok(start >= 0, "expected the _CSRF_PANEL_PUBLIC_HOST const in index.js"); const portAt = src.indexOf("const _CSRF_PANEL_PUBLIC_PORT", start); assert.ok(portAt >= 0, "expected the _CSRF_PANEL_PUBLIC_PORT const in index.js"); const end = src.indexOf("})();", portAt); assert.ok(end >= 0, "expected the _CSRF_PANEL_PUBLIC_PORT IIFE to close"); return src.slice(start, end + "})();".length); } function extractSocketOriginBlock(src) { const start = src.indexOf("const SOCKET_ALLOWED_ORIGINS"); assert.ok(start >= 0, "expected the SOCKET_ALLOWED_ORIGINS const in index.js"); const end = src.indexOf("function getSocketIp", start); assert.ok(end >= 0, "expected function getSocketIp after isSocketOriginAllowed"); return src.slice(start, end); } // Fresh sandbox per scenario: both extracted const groups read their env vars // at evaluation time (exactly as index.js does at require time), so each // scenario sets SOCKET_ALLOW_ORIGINS / PANEL_PUBLIC_URL before evaluation and // the env is restored afterwards. // // adpanel:port-mismatch-advisor — the sliced block now also references two // index.js symbols defined OUTSIDE the sliced regions: securityLog and the // _PORT_MISMATCH_ADVISOR const (which lives near the CSRF consts, above the // socket block, so it is a sandbox stub, not a slice). The stub DELEGATES to // the REAL module: loadSocketOriginCheck builds a fresh createPortMismatch- // Advisor() per scenario (empty throttle state per scenario, exactly like // index.js's module-level instance at boot) and wraps it so every call is // recorded while the REAL advice() decides the return — the real fire // condition and throttle therefore guard this wiring, and a fire-condition // drift in utils/origin-port-advisor.js fails this suite, not just its own // unit tests (the stub must never re-encode the fire condition). The // recordings are attached to the returned function as .advisorCalls / // .securityLogCalls so the pre-existing one-argument scenario calls keep // working unchanged (they mean "no forwarded evidence" — the default // forwardedRaw of the new arity). function loadSocketOriginCheck(envOverrides) { const keys = ["SOCKET_ALLOW_ORIGINS", "PANEL_PUBLIC_URL"]; const saved = keys.map((k) => [k, process.env[k]]); try { for (const k of keys) { if (envOverrides[k] === undefined) delete process.env[k]; else process.env[k] = envOverrides[k]; } const advisorCalls = []; const securityLogCalls = []; const realAdvisor = createPortMismatchAdvisor(); const sandbox = { process, URL, console, extractHostnameFromHeader, parseOriginHost, normalizeHostLower, parseOriginHostPort, extractHeaderHostPort, csrfPortMismatch, securityLog: (msg, req) => { securityLogCalls.push({ msg, req }); }, _PORT_MISMATCH_ADVISOR: { advice: (input) => { advisorCalls.push(input); return realAdvisor.advice(input); }, }, }; vm.createContext(sandbox); vm.runInContext(extractPublicUrlConsts(RAW_INDEX_SOURCE), sandbox); vm.runInContext(extractSocketOriginBlock(RAW_INDEX_SOURCE), sandbox); assert.strictEqual(typeof sandbox.isSocketOriginAllowed, "function", "isSocketOriginAllowed was not defined by the extracted block"); const check = sandbox.isSocketOriginAllowed; check.advisorCalls = advisorCalls; check.securityLogCalls = securityLogCalls; return check; } finally { for (const [k, v] of saved) { if (v === undefined) delete process.env[k]; else process.env[k] = v; } } } test("socket: sibling-port handshake with a cookie is rejected; same-port still accepted", () => { const check = loadSocketOriginCheck({}); // The residual on this surface: the page at the sibling port is same-SITE // with the panel, so the WS handshake carries the SameSite=Lax session // cookie and the socket channel would ride the admin's session. assert.strictEqual(check({ origin: "http://localhost:9999", host: "localhost:3000", cookie: "connect.sid=victim-session", }), false, "a sibling process's page must not open the socket channel on the victim's session"); // Same host, same explicit port: accepted before the rule and after. assert.strictEqual(check({ origin: "http://localhost:3000", host: "localhost:3000", cookie: "connect.sid=victim-session", }), true); }); test("socket: one-sided explicit port is rejected; both-portless, no-origin and opaque postures unchanged", () => { const check = loadSocketOriginCheck({}); // The closed gap on the socket surface: an explicit-port Origin against a // port-less serving Host — a sibling service's page whose WS handshake // would ride the SameSite=Lax cookie. assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "panel.example.com", cookie: "connect.sid=x", }), false, "explicit-port Origin vs portless serving Host must reject"); // Mirror shape: portless Origin against an explicit serving Host port. assert.strictEqual(check({ origin: "https://panel.example.com", host: "panel.example.com:8443", cookie: "connect.sid=x", }), false, "portless Origin vs explicit serving Host port must reject"); // No ports at all: the pre-existing same-host behavior (default-port and // NAT/port-forward deployments). assert.strictEqual(check({ origin: "https://panel.example.com", host: "panel.example.com", cookie: "connect.sid=x", }), true); // Non-browser clients send no Origin: allowed (then authenticated) as before. assert.strictEqual(check({ host: "panel.example.com:3000", cookie: "connect.sid=x" }), true); // Opaque origin: rejected exactly as before (no usable host evidence). assert.strictEqual(check({ origin: "chrome-extension://abcdef", host: "panel.example.com:3000", cookie: "connect.sid=x", }), false); }); test("socket: a trusted X-Forwarded-Host entry supplies the serving port behind a port-stripping proxy", () => { // adpanel:socket-forwarded-host — the Phase-2 shape: the browser sends // Origin https://panel.example.com:8443 (explicit non-default port) while // the proxy strips the port off the Host header — every serving-port // evidence source used to be portless, so the request was indistinguishable // from the sibling-port attack and got bricked. With the proxy forwarding // X-Forwarded-Host WITH the port (the trust screening stays at the call // site — the sandbox check receives the ALREADY-trusted entry, mirroring // the middleware's forwardedRaw), the serving port answers 8443 and the // handshake passes: the rewriting-proxy deployment now works on BOTH // surfaces with the same standard proxy line. const check = loadSocketOriginCheck({}); assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "panel.example.com", cookie: "connect.sid=x", }, "panel.example.com:8443"), true, "the rewriting-proxy deployment now passes on the socket surface"); // The forwarded entry feeds ONLY the port comparison: // - a portless forwarded entry carries no serving-port evidence (still a // mismatch — the forwarded HOST never manufactures a pass); // - a different port on the forwarded host is still a mismatch; // - absent forwardedRaw keeps the Host-only posture exactly as before // (the pre-Phase-2 one-sided rejection, unchanged). assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "panel.example.com", cookie: "connect.sid=x", }, "panel.example.com"), false, "a portless forwarded entry carries no serving-port evidence"); assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "panel.example.com", cookie: "connect.sid=x", }, "panel.example.com:9999"), false, "a different port on the forwarded host is still a mismatch"); assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "panel.example.com", cookie: "connect.sid=x", }), false, "absent forwardedRaw keeps the Host-only posture (unchanged)"); // The forwarded entry must NOT leak into the host-equality grant: the // middleware's requestHost = forwardedHost || hostHeader grant shape is // deliberately not imported — XFH is port evidence only, and a foreign // handshake Host header stays rejected even with a perfectly matching // forwarded entry. assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "internal:3000", cookie: "connect.sid=x", }, "panel.example.com:8443"), false, "host equality still compares the handshake Host header"); // The advisor recorded every port-rule rejection with the values the // rejection actually saw — in call order: the portless forwarded entry, // the different forwarded port, and the absent forwardedRaw (the passing // and host-equality-failing shapes never reach it). assert.deepStrictEqual( check.advisorCalls.map((c) => [c.originHeader, c.servingPort]), [ ["https://panel.example.com:8443", null], ["https://panel.example.com:8443", "9999"], ["https://panel.example.com:8443", null], ], "the advisor saw the origin header and the serving port behind each rejection" ); // The wired securityLog fired exactly where the brick shape (explicit // origin port, null serving port) holds — not for the explicit // different-port mismatch, and never for a passing shape. The REAL // advisor decides: two of the three rejections above are the brick shape, // but both carry the same origin host:port, so the advisor's throttle // (one emission per key per window) withholds the second — the VERDICTS // above are unaffected either way (advice is logging, never the gate). assert.strictEqual(check.securityLogCalls.length, 1, "securityLog fired only for the brick shape (null serving port), and the real advisor's throttle emitted once for the repeated key"); for (const { msg, req } of check.securityLogCalls) { assert.ok(typeof msg === "string" && msg.includes("panel.example.com:8443"), "the real advisor's diagnosis (naming the offending host:port) flowed through securityLog"); assert.strictEqual(req, null, "the sandbox passes no request object"); } }); test("socket: a forwarded entry whose host normalizes away must not mint serving-port evidence", () => { // adpanel:socket-forwarded-host — the serving gate is the SHARED // normalizeHostLower (the middleware's and the read guard's normalizer), // not raw truthiness and not the surface's own normalizeHostForSocket: // that extract-based normalizer is TRUTHY on the placeholder classes // ("null"/"undefined", dot-only "....") that normalizeHostLower empties, // so a trusted proxy forwarding such an entry would take garbage // "evidence" where the HTTP surfaces fall back to Host. Every garbage // class below must land exactly where the HTTP surfaces land: fall back // to the Host header and let the explicit-port rule decide on THAT // evidence. const check = loadSocketOriginCheck({}); // Shape 1 — the Phase-2 brick: explicit-port Origin vs portless Host. The // hostless ":8443" entry is the sharpest class here (raw truthiness would // extract port "8443" out of the garbage and mint the evidence the Origin // needed, PASSING where HTTP 403s); the placeholder classes carry no port // but must still not be taken as evidence. for (const garbage of [":8443", "null", "undefined", "...."]) { assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "panel.example.com", cookie: "connect.sid=x", }, garbage), false, `the garbage forwarded entry ${JSON.stringify(garbage)} must not mint serving-port evidence — the Host fallback answers, still a mismatch, still rejected`); } // Shape 2 — the divergence the SHARED gate closes: portless Origin vs an // explicit-port Host header. The middleware 403s this shape (its // normalizeHostLower gate ignores the garbage entry and falls back to the // port-carrying Host), and the socket must reject identically: under the // old normalizeHostForSocket gate every class below was truthy, minted // portless serving evidence that MASKED the Host's explicit port, and // PASSED the handshake where the HTTP surface 403s. for (const garbage of ["null", "undefined", "...."]) { assert.strictEqual(check({ origin: "https://panel.example.com", host: "panel.example.com:8443", cookie: "connect.sid=x", }, garbage), false, `the garbage forwarded entry ${JSON.stringify(garbage)} must not mask the explicit Host port — the Host fallback answers, still a mismatch, still rejected`); } // The advisor saw the serving port the derivation ACTUALLY used — the Host // fallback's evidence, never the garbage entries': null against the // portless Host of shape 1, the Host's own "8443" against the // port-carrying Host of shape 2 (the shape-2 entries prove the Host // fallback answered — had the gate taken the garbage, the serving port // would have been null AND the verdict a pass). A rejection built on // evidence the HTTP surface would not accept is exactly the drift the // shared gate closes. assert.deepStrictEqual( check.advisorCalls.map((c) => [c.originHeader, c.servingPort]), [ ["https://panel.example.com:8443", null], ["https://panel.example.com:8443", null], ["https://panel.example.com:8443", null], ["https://panel.example.com:8443", null], ["https://panel.example.com", "8443"], ["https://panel.example.com", "8443"], ["https://panel.example.com", "8443"], ], "the serving port came from the Host fallback — null against the portless Host, the Host's own 8443 against the port-carrying Host — never from the garbage entries" ); }); test("socket: the operator allowlist stays port-blind; non-members keep the stricter posture", () => { const check = loadSocketOriginCheck({ SOCKET_ALLOW_ORIGINS: "panel.example.com" }); assert.strictEqual(check({ origin: "https://panel.example.com:9999", host: "panel.example.com:3000", cookie: "connect.sid=x", }), true, "operator trust must not silently become port-aware"); // With an allowlist configured, the host-equality grant is replaced // entirely: a same-host origin that is not a member stays rejected, ports // matching or not. const strict = loadSocketOriginCheck({ SOCKET_ALLOW_ORIGINS: "other.example.com" }); assert.strictEqual(strict({ origin: "https://panel.example.com:3000", host: "panel.example.com:3000", cookie: "connect.sid=x", }), false); }); test("socket: PANEL_PUBLIC_URL host+port escape withholds the port rejection, nothing more", () => { const check = loadSocketOriginCheck({ PANEL_PUBLIC_URL: "https://panel.example.com:8443" }); assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "panel.example.com:3000", cookie: "connect.sid=x", }), true, "the documented Host-rewriting-proxy escape, extended for ports"); // A different port on the public host is still a mismatch. assert.strictEqual(check({ origin: "https://panel.example.com:9999", host: "panel.example.com:3000", cookie: "connect.sid=x", }), false); // The escape only withholds the PORT rejection — the base host-equality // grant is untouched (a foreign serving host is still rejected; the socket // surface, unlike the middleware, never granted the public host). assert.strictEqual(check({ origin: "https://panel.example.com:8443", host: "internal:3000", cookie: "connect.sid=x", }), false); }); test("socket: a cookie-less mismatched-port handshake keeps the middleware's anonymous posture", () => { // The function itself holds the shared decision's cookie-less boundary (no // ambient authority — nothing to ride, the same posture the no-evidence // paths take); the io.use middleware rejects cookie-less handshakes before // the origin check ever runs ("Authentication required"), so the anonymous // path is unchanged end to end. The ordering is pinned at source level // below. const check = loadSocketOriginCheck({}); assert.strictEqual(check({ origin: "http://localhost:9999", host: "localhost:3000", }), true); }); // ---- Source-level: index.js routes the middleware through the shared rule ---- const ROOT = path.join(__dirname, ".."); // Strip full-line comments so prose cannot satisfy the assertions (same // technique as tests/csrf-localhost-scoping.test.js). function stripFullLineComments(src) { return src .split("\n") .filter((line) => !/^\s*\/\//.test(line)) .join("\n"); } const indexSrc = stripFullLineComments(fs.readFileSync(path.join(ROOT, "index.js"), "utf8")); const guardSrc = stripFullLineComments(fs.readFileSync(path.join(ROOT, "utils", "cross-site-read-guard.js"), "utf8")); const originHostSrc = stripFullLineComments(fs.readFileSync(path.join(ROOT, "utils", "origin-host.js"), "utf8")); function middlewareWindow() { const start = indexSrc.indexOf("async function sameOriginProtection"); assert.notStrictEqual(start, -1, "expected sameOriginProtection in index.js"); const end = indexSrc.indexOf("app.use(sameOriginProtection);", start); assert.notStrictEqual(end, -1, "expected the sameOriginProtection mount in index.js"); return indexSrc.slice(start, end); } test("sameOriginProtection decides the explicit-port rule through the shared csrfPortMismatch", () => { const win = middlewareWindow(); assert.ok(win.includes("csrfPortMismatch({"), "the middleware must route the port decision through utils/origin-host.js csrfPortMismatch"); assert.ok(win.includes("parseOriginHostPort(rawOrigin)"), "the evidence port must come from the Origin header when the host did"); assert.ok(win.includes("parseOriginHostPort(rawReferer)"), "the evidence port must fall back to Referer exactly when the host evidence does"); assert.ok(win.includes("extractHeaderHostPort(forwardedRaw)"), "the serving port must follow the trusted X-Forwarded-Host entry getTrustedForwardedHost endorses"); assert.ok(win.includes("extractHeaderHostPort(req.headers.host || \"\")"), "the serving port must fall back to the Host header when no trusted proxy answered"); assert.ok(win.includes("hasCookie: Boolean(req.headers.cookie)"), "the rejection must be cookie-bearing only — the no-cookie posture is pinned"); assert.ok(win.includes("sameOriginFetch,"), "the browser-attested same-origin escape must be handed to the shared rule"); assert.ok(win.includes("portBlindTrust: hostAllowed(headerHost, _CSRF_EXTRA_ALLOWED_SET)"), "CSRF_ALLOWED_HOSTS trust must stay port-blind"); assert.ok(win.includes("publicHost: _CSRF_PANEL_PUBLIC_HOST") && win.includes("publicPort: _CSRF_PANEL_PUBLIC_PORT"), "the PANEL_PUBLIC_URL escape must be handed to the shared rule"); assert.ok(win.includes('res.status(403).send("CSRF blocked")'), "the port rejection must carry the middleware's own CSRF blocked body"); // adpanel:port-mismatch-advisor — the 403 branch must diagnose the brick // shape with the SAME evidence the rejection used (the origin header that // produced originPortPair), through the one shared advisor instance. assert.ok(win.includes("_PORT_MISMATCH_ADVISOR.advice({"), "the 403 branch must consult the port-mismatch advisor before responding"); assert.ok(win.includes("originHeader: originHost ? rawOrigin : rawReferer"), "the advisor must see the origin header that produced originPortPair — rawOrigin when originHost evidence exists, else rawReferer"); assert.ok(win.includes("if (advice) securityLog(advice, req)"), "the returned advice must flow through securityLog"); }); test("the explicit-port check runs BEFORE and independently of the loopback alias grant", () => { const win = middlewareWindow(); const portAt = win.indexOf("csrfPortMismatch({"); const aliasAt = win.indexOf('allowedHosts.add("localhost")'); assert.notStrictEqual(portAt, -1, "expected the port check in the middleware window"); assert.notStrictEqual(aliasAt, -1, "expected the loopback alias grant in the middleware window"); assert.ok(portAt < aliasAt, "the alias grant is host-level only — the port rule must decide first so a sibling process page cannot alias-match"); }); test("index.js derives the public URL port once and injects it into the guard's trust context", () => { assert.ok(indexSrc.includes("const _CSRF_PANEL_PUBLIC_PORT = (() =>"), "expected the _CSRF_PANEL_PUBLIC_PORT constant next to _CSRF_PANEL_PUBLIC_HOST"); assert.ok(indexSrc.includes("panelPublicPort: _CSRF_PANEL_PUBLIC_PORT"), "index.js must inject the public URL port into crossSiteReadGuard.setCrossOriginTrustContext"); }); test("the shared rule lives ONLY in utils/origin-host.js — no surface carries a copy", () => { assert.ok(originHostSrc.includes("function csrfPortMismatch"), "utils/origin-host.js is the ONE home of the explicit-port decision"); assert.ok(!indexSrc.includes("function csrfPortMismatch"), "index.js must not define a local csrfPortMismatch — route through utils/origin-host.js"); assert.ok(!guardSrc.includes("function csrfPortMismatch"), "cross-site-read-guard.js must not define a local csrfPortMismatch — route through utils/origin-host.js"); // Both surfaces must actually call it (presence AND use, not just an import). assert.ok(indexSrc.includes("csrfPortMismatch({"), "index.js middleware must call the shared rule"); assert.ok(guardSrc.includes("csrfPortMismatch({"), "the read guard must call the shared rule"); }); test("the read guard derives ports from the same headers as the middleware and honors the CORS exact-origin exemption", () => { const start = guardSrc.indexOf("function rejectCrossSiteRead"); assert.notStrictEqual(start, -1, "expected rejectCrossSiteRead in the guard"); const win = guardSrc.slice(start, guardSrc.indexOf("function createApiReadGate", start)); assert.ok(win.includes("parseOriginHostPort(rawOrigin)") && win.includes("parseOriginHostPort(rawReferer)"), "the guard must derive the evidence port from the SAME header the host came from"); assert.ok(win.includes("extractHeaderHostPort(forwardedRaw)") && win.includes("extractHeaderHostPort(headers.host || \"\")"), "the guard's serving port must follow trusted forwarded host, else the Host header — the middleware's exact precedence"); assert.ok(win.includes("CORS_READ_ALLOWED_ORIGINS.has(rawOrigin)"), "an exact NODES_CORS_ORIGINS origin match must count as port-blind trust in the guard"); assert.ok(win.includes("publicPort: _panelPublicPort"), "the guard must hand the injected public port to the shared rule"); }); // ---- Source-level: the Socket.IO handshake surface ---------------------------- function socketOriginWindow() { const start = indexSrc.indexOf("function normalizeHostForSocket"); assert.notStrictEqual(start, -1, "expected normalizeHostForSocket in index.js"); const end = indexSrc.indexOf("function getSocketIp", start); assert.notStrictEqual(end, -1, "expected function getSocketIp after isSocketOriginAllowed"); return indexSrc.slice(start, end); } test("isSocketOriginAllowed decides the explicit-port rule through the shared csrfPortMismatch", () => { const win = socketOriginWindow(); assert.ok(win.includes("csrfPortMismatch({"), "the socket origin check must route the port decision through utils/origin-host.js csrfPortMismatch"); assert.ok(win.includes("parseOriginHostPort(originHeader)"), "the evidence port must come from the SAME Origin header the host came from"); // adpanel:socket-forwarded-host — the serving derivation mirrors the // middleware's exactly: the forwarded entry is GATED on the SHARED // normalizeHostLower (utils/origin-host.js) — the same normalizer the // middleware's forwardedHost gate and the read guard's gate apply, so all // three surfaces normalize one way and cannot drift. The surface's own // extract-based normalizeHostForSocket is deliberately NOT the gate: it is // truthy on the placeholder classes normalizeHostLower empties // ("null"/"undefined", dot-only "...."), so those entries would mint // portless evidence that masks an explicit Host port and pass a handshake // the HTTP surface 403s. The fallback is the handshake Host header (the // header the host-equality grant compares). Both the gate and the fallback // are pinned so neither the normalization, the XFH preference, nor the // Host fallback can be dropped. assert.ok(win.includes('normalizeHostLower(forwardedRaw) ? extractHeaderHostPort(forwardedRaw) : extractHeaderHostPort(headers?.host || "")'), "the serving port must gate the trust-screened X-Forwarded-Host entry on the shared normalizeHostLower (the middleware's and the read guard's normalizer — no evidence from a host that normalizes away, placeholder classes included) and fall back to the handshake Host header"); assert.ok(win.includes("hasCookie: Boolean(headers?.cookie)"), "the rejection must be cookie-bearing only — the rule only bites where cookies ride"); assert.ok(win.includes("publicHost: _CSRF_PANEL_PUBLIC_HOST") && win.includes("publicPort: _CSRF_PANEL_PUBLIC_PORT"), "the PANEL_PUBLIC_URL escape must be handed to the shared rule"); // adpanel:port-mismatch-advisor — the silent rejection must route the // one-sided brick shape through the advisor and log the returned advice; // the wire error itself must stay untouched. assert.ok(win.includes("_PORT_MISMATCH_ADVISOR.advice({ originHeader, servingPort: servingPair ? servingPair.port : null })"), "the rejection branch must consult the advisor with the values the rejection saw"); assert.ok(win.includes("if (advice) securityLog(advice, req)"), "the returned advice must flow through securityLog"); assert.ok(!win.includes("sec-fetch-site"), "no browser-attested same-origin signal exists on a handshake — none may be invented"); assert.ok(!win.includes("function csrfPortMismatch"), "the socket surface must not define a local copy of the decision"); }); test("the socket port check runs after the operator allowlist and before the host-equality grant", () => { const win = socketOriginWindow(); const allowlistAt = win.indexOf("if (allowlist.length) return allowlist.includes(originHost);"); const portAt = win.indexOf("csrfPortMismatch({"); const equalityAt = win.indexOf("return originHost === requestHost;"); assert.notStrictEqual(allowlistAt, -1, "expected the operator allowlist pass"); assert.notStrictEqual(portAt, -1, "expected the port check"); assert.notStrictEqual(equalityAt, -1, "expected the host-equality grant"); assert.ok(portAt > allowlistAt, "the allowlist keeps its port-blind operator-trust pass (the portBlindTrust escape)"); assert.ok(portAt < equalityAt, "the port rejection must precede the host-equality grant so a sibling port cannot ride it"); }); test("the handshake middleware rejects cookie-less sockets before the origin check", () => { // Anonymous posture: a cookie-less handshake is rejected at the auth gate // ("Authentication required") — the same bucket foreign origins land in — // so the port rule never has to judge an anonymous handshake. const start = indexSrc.indexOf("io.use((socket, next) => {"); assert.notStrictEqual(start, -1, "expected the socket handshake middleware"); const win = indexSrc.slice(start, start + 1200); const cookieGateAt = win.indexOf("if (!cookieHeader)"); const originAt = win.indexOf("isSocketOriginAllowed"); assert.notStrictEqual(cookieGateAt, -1, "expected the cookie gate"); assert.notStrictEqual(originAt, -1, "expected the origin check"); assert.ok(cookieGateAt < originAt, "cookie-less handshakes must hit the auth gate before the origin check"); }); test("the handshake middleware resolves serving-port trust at the call site and fails open to Host-only evidence", () => { // adpanel:socket-forwarded-host — the trust split mirrors the middleware: // the io.use call site (which owns the handshake request) resolves the // screened forwarded entry, isSocketOriginAllowed receives it as evidence. // Resolution must fail OPEN (try/catch to Host-only evidence — the // pre-Phase-2 posture) so a resolution error can neither brick the // handshake nor crash the middleware. const start = indexSrc.indexOf("io.use((socket, next) => {"); assert.notStrictEqual(start, -1, "expected the socket handshake middleware"); const end = indexSrc.indexOf("sessionMiddleware(socket.request", start); assert.notStrictEqual(end, -1, "expected the session middleware handoff after the origin check"); const win = indexSrc.slice(start, end); assert.ok(win.includes("getTrustedForwardedHost(socket.request)"), "serving-port trust must be resolved at the call site via getTrustedForwardedHost, which screens on the direct peer being a trusted proxy"); assert.match(win, /try\s*\{\s*socketForwardedRaw = getTrustedForwardedHost\(socket\.request\) \|\| "";\s*\}\s*catch/, "the forwarded-host resolution must fail open (try/catch) to Host-only evidence"); assert.ok(win.includes("isSocketOriginAllowed(socket.handshake?.headers || {}, socketForwardedRaw, socket.request)"), "the origin check must receive the handshake headers, the screened forwarded entry and the handshake request"); });