Files
Kelx/tests/csrf-localhost-scoping.test.js
2026-11-30 16:32:37 +00:00

294 lines
14 KiB
JavaScript

"use strict";
// adpanel:csrf-localhost-scoping — regression tests for the loopback alias
// scoping fix shared by BOTH cross-origin trust decisions:
//
// - utils/cross-site-read-guard.js buildAllowedHosts (the shared CSRF-read
// guard), and
// - index.js sameOriginProtection (the panel-wide CSRF write check).
//
// The hole: both granted the localhost/127.0.0.1/::1 allowlist aliases to ANY
// request whose Origin/Referer host was loopback, regardless of where the
// panel itself is served. Because hostAllowed ignores ports, a hostile page
// served by any other local process (Origin http://localhost:9999) passed the
// guard and the CSRF write check while riding the victim's SameSite=Lax
// session cookie — realistic on desktop deployments where the admin browses
// other local web apps. The fix gates the alias grant on the panel's OWN host
// being loopback too; on a non-loopback deployment a loopback-origin page is
// never the panel and must fall through to the normal allowlist like any
// other foreign host.
//
// adpanel:csrf-port-awareness (utils/origin-host.js csrfPortMismatch, mirrored
// by index.js sameOriginProtection and this guard) closes the same-host-
// different-port variant on BOTH deployment shapes: a sibling process page on
// another port is now rejected even against a loopback-served panel, so the
// loopback-panel tests below pin the alias grant with a same-port loopback
// ALIAS origin (127.0.0.1 vs localhost) instead of the sibling-port page the
// original fix predated the port rule with.
//
// Two layers, matching this repo's conventions (see
// tests/node-relay-cross-site-guard-parity.test.js):
// - Functional: the REAL guard middleware (utils/cross-site-read-guard.js —
// a plain (req, res, next) function reading only req.headers) is driven
// with fake req/res objects under a controlled trust context
// (setCrossOriginTrustContext). index.js cannot be required in-process
// (it boots servers on require), so its side is pinned at source level.
// - Source-level: BOTH copies must gate the alias-add on the panel's own
// host, asserted against the comment-stripped source of each file so
// future drift on either side trips a test.
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 {
rejectCrossSiteRead,
setCrossOriginTrustContext,
} = require("../utils/cross-site-read-guard");
// 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) {
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" };
// ---- Functional: the real guard scopes the loopback aliases ------------------
test("public panel: cross-site-attested Origin from another local process is rejected (the closed hole)", () => {
setCrossOriginTrustContext({ panelPublicHost: "panel.example.com" });
const out = runGuard({
host: "panel.example.com",
"sec-fetch-site": "cross-site",
origin: "http://localhost:9999",
cookie: "connect.sid=victim-session",
});
assert.strictEqual(out.nextCalled, false, "a loopback-origin page on a public panel must NOT pass the read guard");
assert.strictEqual(out.statusCode, 403);
assert.deepStrictEqual(out.body, GUARD_403);
});
test("public panel: loopback Origin without Fetch Metadata is rejected (old-browser shape)", () => {
setCrossOriginTrustContext({ panelPublicHost: "panel.example.com" });
const out = runGuard({
host: "panel.example.com",
origin: "http://localhost:9999",
cookie: "connect.sid=victim-session",
});
assert.strictEqual(out.nextCalled, false, "branch 4 holds the evidence host to the allowlist — no aliases for loopback evidence on a public panel");
assert.strictEqual(out.statusCode, 403);
assert.deepStrictEqual(out.body, GUARD_403);
});
test("public panel: cookieless loopback Origin is rejected like any other foreign evidence host (pinned post-fix behavior)", () => {
// Pinned AS the guard behaves after the scoping fix: branch 4 rejects on
// the evidence host regardless of cookies (same treatment the parity test
// pins for https://evil.example) — the fix makes loopback evidence on a
// non-loopback panel foreign like everything else; no new cookieless
// exemption was invented.
setCrossOriginTrustContext({ panelPublicHost: "panel.example.com" });
const out = runGuard({
host: "panel.example.com",
origin: "http://localhost:9999",
});
assert.strictEqual(out.nextCalled, false);
assert.strictEqual(out.statusCode, 403);
assert.deepStrictEqual(out.body, GUARD_403);
});
test("loopback panel: same-port loopback alias origin is allowed (aliases granted when the panel itself is loopback)", () => {
// Conscious update for adpanel:csrf-port-awareness: this test originally
// used Origin http://localhost:9999 — a sibling PROCESS on a different
// port — as its alias-grant evidence, because host matching was port-blind.
// The shared explicit-port rule (csrfPortMismatch in utils/origin-host.js)
// now rejects exactly that shape even on a loopback panel, so the alias
// grant's own purpose — a loopback ALIAS of the panel (127.0.0.1 vs
// localhost) on the SAME port — is pinned with a same-port origin instead.
// The sibling-port rejection is pinned right below and covered in depth in
// tests/csrf-port-awareness.test.js.
setCrossOriginTrustContext({ panelPublicHost: "localhost" });
const out = runGuard({
host: "localhost:3000",
"sec-fetch-site": "cross-site",
origin: "http://127.0.0.1:3000",
cookie: "connect.sid=victim-session",
});
assert.strictEqual(out.nextCalled, true, "a loopback-served panel keeps the desktop localhost grant for same-port loopback aliases");
});
test("loopback panel: sibling process on a different port is rejected by the explicit-port rule", () => {
// The loopback residual the port rule closes: even on a loopback-served
// panel, where the alias grant below WOULD host-match localhost:9999, the
// csrfPortMismatch check (which runs ahead of the host branches) rejects
// the cookie-bearing sibling process page.
setCrossOriginTrustContext({ panelPublicHost: "localhost" });
const out = runGuard({
host: "localhost:3000",
"sec-fetch-site": "cross-site",
origin: "http://localhost:9999",
cookie: "connect.sid=victim-session",
});
assert.strictEqual(out.nextCalled, false, "a sibling process page on another port must not ride the session even on a loopback panel");
assert.strictEqual(out.statusCode, 403);
assert.deepStrictEqual(out.body, GUARD_403);
});
test("loopback panel: cookieless loopback Origin is allowed", () => {
setCrossOriginTrustContext({ panelPublicHost: "localhost" });
const out = runGuard({
host: "localhost:3000",
origin: "http://localhost:9999",
});
assert.strictEqual(out.nextCalled, true);
});
// ---- Functional: the trusted-forwarded-host arm of the scoping gate ---------
// The gate opens through THREE panel-host inputs (Host header, trusted
// X-Forwarded-Host, PANEL_PUBLIC_URL host); the tests above cover the Host
// header and PANEL_PUBLIC_URL arms. Behind a trusted proxy the panel's own
// host is the X-Forwarded-Host the injected resolver endorses, so these two
// drive that arm behaviorally (buildAllowedHosts calls the resolver with the
// request and match-lowercases what it returns).
test("public panel: trusted loopback X-Forwarded-Host opens the gate for a loopback-origin page", () => {
// Conscious update for adpanel:csrf-port-awareness: the origin here was
// originally http://localhost:9999 — a sibling PROCESS on another port,
// chosen when host matching was port-blind. The shared explicit-port rule
// (csrfPortMismatch in utils/origin-host.js) now rejects that one-sided
// shape (explicit origin port vs a portless serving host) ahead of the
// alias grant, so the XFH arm of the scoping gate is pinned with a
// same-port loopback origin — the grant's actual purpose, mirroring the
// Host-arm update at the top of this file.
setCrossOriginTrustContext({
panelPublicHost: "panel.example.com",
resolveTrustedForwardedHost: () => "localhost:3000",
});
const out = runGuard({
host: "panel.example.com",
origin: "http://localhost:3000",
cookie: "connect.sid=victim-session",
});
assert.strictEqual(out.nextCalled, true, "the panel's own serving host (trusted X-Forwarded-Host) is loopback, so the alias grant opens and the same-port localhost-origin page passes");
});
test("public panel: trusted non-loopback X-Forwarded-Host keeps the gate closed for a loopback-origin page", () => {
setCrossOriginTrustContext({
panelPublicHost: "panel.example.com",
resolveTrustedForwardedHost: () => "proxy.internal.example",
});
const out = runGuard({
host: "panel.example.com",
origin: "http://localhost:9999",
cookie: "connect.sid=victim-session",
});
assert.strictEqual(out.nextCalled, false, "no loopback arm anywhere on a public panel — the aliases must not be granted");
assert.strictEqual(out.statusCode, 403);
assert.deepStrictEqual(out.body, GUARD_403);
});
test("public panel: same-host Origin is still allowed (regression)", () => {
setCrossOriginTrustContext({ panelPublicHost: "panel.example.com" });
const out = runGuard({
host: "panel.example.com",
origin: "https://panel.example.com",
cookie: "connect.sid=victim-session",
});
assert.strictEqual(out.nextCalled, true, "the panel's own host must keep passing — the scoping fix only narrows loopback evidence");
});
// ---- Source-level: BOTH copies gate the alias grant on the panel's own host --
const ROOT = path.join(__dirname, "..");
// Strip full-line comments so prose cannot satisfy the assertions (same
// technique as tests/node-relay-cross-site-guard-parity.test.js).
function stripFullLineComments(src) {
return src
.split("\n")
.filter((line) => !/^\s*\/\//.test(line))
.join("\n");
}
// The window of source between the gate's `if (` and the END of the alias
// block — the condition that decides whether the loopback aliases are
// granted, plus every alias add it guards.
function aliasGrantWindow(src, aliasNeedle, label) {
const at = src.indexOf(aliasNeedle);
assert.notStrictEqual(at, -1, `expected the loopback alias grant (${aliasNeedle}) in ${label}`);
const ifAt = src.lastIndexOf("if (", at);
assert.notStrictEqual(ifAt, -1, `expected the alias grant to sit behind an if ( in ${label}`);
const lastAddAt = src.indexOf('add("::1")', at);
const end = lastAddAt !== -1 ? lastAddAt + 'add("::1")'.length : at + aliasNeedle.length;
return src.slice(ifAt, end);
}
test("buildAllowedHosts gates the loopback alias grant on the panel's own host (source pin)", () => {
const src = stripFullLineComments(
fs.readFileSync(path.join(ROOT, "utils", "cross-site-read-guard.js"), "utf8")
);
const window = aliasGrantWindow(src, 'allowed.add("localhost")', "cross-site-read-guard.js");
assert.match(window, /isLocalHost\(originHost\) \|\| isLocalHost\(refererHost\)/,
"the evidence-side condition must stay");
assert.match(window, /isLocalHost\(hostHeader\)/,
"the alias grant must be gated on the panel's serving Host header being loopback");
assert.match(window, /isLocalHost\(forwardedHost\)/,
"the alias grant must be gated on the trusted X-Forwarded-Host being loopback");
assert.match(window, /isLocalHost\(_panelPublicHost\)/,
"the alias grant must be gated on the PANEL_PUBLIC_URL host being loopback");
});
test("sameOriginProtection gates the loopback alias grant on the panel's own host (source pin)", () => {
const src = stripFullLineComments(fs.readFileSync(path.join(ROOT, "index.js"), "utf8"));
const window = aliasGrantWindow(src, 'allowedHosts.add("localhost")', "index.js");
assert.match(window, /isLocalHost\(originHost\) \|\| isLocalHost\(refererHost\)/,
"the evidence-side condition must stay");
assert.match(window, /isLocalHost\(requestHost\)/,
"the alias grant must be gated on the panel's request host being loopback");
assert.match(window, /isLocalHost\(forwardedHost\)/,
"the alias grant must be gated on the trusted X-Forwarded-Host being loopback");
assert.match(window, /isLocalHost\(hostHeader\)/,
"the alias grant must be gated on the serving Host header being loopback");
assert.match(window, /isLocalHost\(_CSRF_PANEL_PUBLIC_HOST\)/,
"the alias grant must be gated on the PANEL_PUBLIC_URL host being loopback");
});
test("both trust decisions scope the loopback aliases on the SAME evidence-side condition (cross-surface parity pin)", () => {
// Mirrors the parity pinning of tests/node-relay-cross-site-guard-parity.test.js:
// the read guard and the CSRF write middleware must decide loopback trust
// from the same inputs — if one side drops the gate or the evidence
// condition, reads and writes would disagree about what localhost means.
const guardSrc = stripFullLineComments(
fs.readFileSync(path.join(ROOT, "utils", "cross-site-read-guard.js"), "utf8")
);
const indexSrc = stripFullLineComments(fs.readFileSync(path.join(ROOT, "index.js"), "utf8"));
const guardWindow = aliasGrantWindow(guardSrc, 'allowed.add("localhost")', "cross-site-read-guard.js");
const indexWindow = aliasGrantWindow(indexSrc, 'allowedHosts.add("localhost")', "index.js");
for (const needle of [
"isLocalHost(originHost) || isLocalHost(refererHost)",
'add("localhost")',
'add("127.0.0.1")',
'add("::1")',
]) {
assert.ok(guardWindow.includes(needle), `cross-site-read-guard.js alias window must contain ${needle}`);
assert.ok(indexWindow.includes(needle), `index.js alias window must contain ${needle}`);
}
});