605 lines
29 KiB
JavaScript
605 lines
29 KiB
JavaScript
"use strict";
|
|
|
|
// Regression tests for the cross-site read guard + shared SSRF validator
|
|
// alignment between the panel's own file routes and the nodes.js remote-mode
|
|
// relays.
|
|
//
|
|
// Two gaps were closed here:
|
|
//
|
|
// 1. The relay GETs /api/nodes/server/:name/{entries,file,download} served
|
|
// node files without the cross-site read guard the panel's own read routes
|
|
// (index.js /api/servers/:name/files/{list,read,stream,download}) always
|
|
// applied. Read-only and same-origin-only by contract, so the guard is a
|
|
// hardening/consistency fix, not an exfiltration patch — but the relay is
|
|
// the one surface where the panel's CSRF-read pattern was not applied.
|
|
//
|
|
// 2. nodes.js carried a weaker private copy of the panel's remote-URL SSRF
|
|
// validator (uploaderAssertSafeRemoteUrl): its IPv6 classifier missed
|
|
// site-local fec0::/10, multicast ff00::/8 and NAT64 64:ff9b::/96, its IPv4
|
|
// classifier missed the TEST-NETs, and it had no 80/443 port allowlist. The
|
|
// daemon re-validates URL/ports/resolved IPs at connect time, so this was
|
|
// not exploitable — but both consumers now share ONE implementation
|
|
// (utils/remote-url-guard.js) per this codebase's shared-sanitizer
|
|
// convention, so the sides cannot drift again.
|
|
//
|
|
// Two layers of tests, matching this repo's conventions:
|
|
// - Functional: the REAL nodes.js app is mounted on a loopback HTTP server
|
|
// (same technique as utils/node-bootstrap.integration.test.js) and the
|
|
// seven relays are probed. The guard runs ahead of checkServerAccess, so
|
|
// a cross-site request must answer 403 with the guard's own error body
|
|
// WITHOUT reaching authentication, while same-origin/headerless requests
|
|
// must fall through to each route's real access-gate response — proving
|
|
// the guard gates exactly and only cross-site reads. A second integration
|
|
// block pins the Origin/Referer fallback the guard applies when
|
|
// Sec-Fetch-Site is absent (the old-browser hole): foreign evidence → the
|
|
// guard's 403, same-origin or cookieless-null evidence → the auth gate.
|
|
// A third block pins the closed evidence-less-cookie residual: a
|
|
// cookie-bearing request with no evidence at all → the guard's 403 (the
|
|
// shape a hostile old-browser page or a Referer-stripping same-site
|
|
// sibling produces), while browser-attested "none" navigations and
|
|
// same-host-Origin scripted clients still reach the auth gate.
|
|
// - Source-level: index.js cannot be required in-process (it boots servers
|
|
// on require), so the panel/relay wiring is asserted against the source
|
|
// of both files (same technique as node-relay-timeout-parity.test.js),
|
|
// pinning BOTH sides so future drift on either side trips a test.
|
|
//
|
|
// adpanel:csrf-port-awareness adds a fourth block: the explicit-port rule
|
|
// (same-host-different-port origins riding SameSite=Lax cookies) is ONE
|
|
// shared decision — csrfPortMismatch in utils/origin-host.js — used by BOTH
|
|
// index.js sameOriginProtection and the shared read guard, and the relay
|
|
// enforces it behaviorally (a sibling-port cookie-bearing read is the guard's
|
|
// 403; the same-port and cookie-less shapes reach the auth gate).
|
|
|
|
const test = require("node:test");
|
|
const { after } = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const path = require("node:path");
|
|
const http = require("node:http");
|
|
|
|
if (!process.env.SESSION_SECRET || process.env.SESSION_SECRET.length < 32) {
|
|
process.env.SESSION_SECRET = "adpanel-node-relay-guard-parity-test-secret-0123456789";
|
|
}
|
|
|
|
// ---- Exit-code honesty -------------------------------------------------------
|
|
// Requiring nodes.js starts the mysql2 pool (and nodes.js's batch timers),
|
|
// which keep the event loop alive after the suite finishes — the process must
|
|
// be exited forcibly. The exit code tallies REAL failures: node:test marks a
|
|
// test failed when its callback rejects, so every test registers through
|
|
// pinnedTest(), which counts the rejection before rethrowing (node:test still
|
|
// reports the failure normally). A self-managed "passed" flag cannot do this:
|
|
// with more than one integration test, a flag set by the first masks a failure
|
|
// in the second behind exit 0, and process.exit() truncates buffered TAP on
|
|
// pipes — both masking modes were demonstrated by adversarial review
|
|
// (2026-10-17, see SECURITY-FIXES.md).
|
|
let failedTests = 0;
|
|
function pinnedTest(name, fn) {
|
|
return test(name, async (t) => {
|
|
try {
|
|
await fn(t);
|
|
} catch (err) {
|
|
failedTests += 1;
|
|
throw err;
|
|
}
|
|
});
|
|
}
|
|
after(async () => {
|
|
// Give the TAP reporter time to flush before the forced exit so the last
|
|
// results — including any failure — are visible in the output.
|
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
process.exit(failedTests > 0 ? 1 : 0);
|
|
});
|
|
|
|
// ---- Source-level parity assertions (both files, comment-stripped) ----------
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const NODES_JS = path.join(ROOT, "nodes.js");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
|
|
// Strip full-line comments so prose mentioning route names or identifiers
|
|
// cannot satisfy the assertions (same technique as
|
|
// node-relay-timeout-parity.test.js).
|
|
function stripFullLineComments(src) {
|
|
return src
|
|
.split("\n")
|
|
.filter((line) => !/^\s*\/\//.test(line))
|
|
.join("\n");
|
|
}
|
|
|
|
const nodesSrc = stripFullLineComments(fs.readFileSync(NODES_JS, "utf8"));
|
|
const indexSrc = stripFullLineComments(fs.readFileSync(INDEX_JS, "utf8"));
|
|
|
|
// Parity table: relay route ↔ the panel-side twins that already carried the
|
|
// guard. Keep both lists in sync with the code — a new file/console/data read
|
|
// route on either surface belongs here too. The panel surface also guards
|
|
// /api/servers/:name/console-history (console command content), /planner,
|
|
// /scheduler/:serverName/tasks, /server/:name/activity, /servers/:name/
|
|
// permissions (which mints action tokens on GET, so a hostile page must not
|
|
// drive repeated mints) and /api/server-info/:name (the panel-side twin of
|
|
// the relay's /info: per-server connection metadata) — per-server reads
|
|
// gated by session + server access, the same data class; index.js cannot be
|
|
// mounted in-process, so panel-side routes are pinned at source level only.
|
|
// /api/nodes/:id/config.yml is deliberately NOT in the relay list: it
|
|
// authenticates node agents via the X-Node-Bootstrap header / Bearer node
|
|
// token (cookieless by design), so the browser-attestation guard has no
|
|
// session authority to protect there.
|
|
const PANEL_GUARDED_ROUTES = [
|
|
"/api/servers/:name/files/list",
|
|
"/api/servers/:name/files/read",
|
|
"/api/servers/:name/files/stream",
|
|
"/api/servers/:name/files/download",
|
|
"/api/servers/:name/console-history",
|
|
"/api/servers/:name/planner",
|
|
"/api/servers/:name/permissions",
|
|
"/api/scheduler/:serverName/tasks",
|
|
"/api/server/:name/activity",
|
|
"/api/server-info/:name",
|
|
];
|
|
const RELAY_GUARDED_ROUTES = [
|
|
"/api/nodes/server/:name/entries",
|
|
"/api/nodes/server/:name/file",
|
|
"/api/nodes/server/:name/download",
|
|
"/api/nodes/server/:name/info",
|
|
"/api/nodes/server/:name/eula",
|
|
"/api/nodes/server/:name/backups",
|
|
"/api/nodes/server/:name/logs",
|
|
];
|
|
|
|
// Guarded reads living in their own router files (mounted into the panel app
|
|
// by index.js). Needles are matched against whitespace-normalized source
|
|
// because these mounts span multiple lines. /bootstrap is per-USER rather
|
|
// than per-server, but it embeds action tokens on GET — the same
|
|
// repeated-mint rationale that guards /api/servers/:name/permissions.
|
|
const ROUTER_GUARDED_ROUTES = [
|
|
{
|
|
file: path.join(ROOT, "routes", "dashboard-assistant.js"),
|
|
route: "/bootstrap (admin bootstrap embeds action tokens)",
|
|
needle: 'router.get("/bootstrap", rejectCrossSiteRead,',
|
|
},
|
|
];
|
|
|
|
for (const route of PANEL_GUARDED_ROUTES) {
|
|
pinnedTest(`index.js panel route ${route} keeps the cross-site read guard`, () => {
|
|
const needle = `app.get("${route}", rejectCrossSiteRead,`;
|
|
assert.ok(
|
|
indexSrc.includes(needle),
|
|
`expected ${needle} in index.js — the panel's own file-read routes must keep the guard`
|
|
);
|
|
});
|
|
}
|
|
|
|
for (const route of RELAY_GUARDED_ROUTES) {
|
|
pinnedTest(`nodes.js relay route ${route} carries the cross-site read guard`, () => {
|
|
const needle = `app.get("${route}", rejectCrossSiteRead,`;
|
|
assert.ok(
|
|
nodesSrc.includes(needle),
|
|
`expected ${needle} in nodes.js — the remote-mode relays must reject exactly what the panel's own file routes reject`
|
|
);
|
|
});
|
|
}
|
|
|
|
for (const entry of ROUTER_GUARDED_ROUTES) {
|
|
pinnedTest(`router route ${entry.route} carries the cross-site read guard`, () => {
|
|
const src = stripFullLineComments(fs.readFileSync(entry.file, "utf8")).replace(/\s+/g, " ");
|
|
assert.ok(
|
|
src.includes(entry.needle),
|
|
`expected ${entry.needle} in ${entry.file} — router file reads must reject exactly what the panel's own file routes reject`
|
|
);
|
|
// Anti-drift: the router file must consume the ONE shared implementation.
|
|
assert.ok(
|
|
src.includes('require("../utils/cross-site-read-guard")'),
|
|
`${entry.file} must require ../utils/cross-site-read-guard`
|
|
);
|
|
assert.ok(
|
|
!src.includes("function rejectCrossSiteRead"),
|
|
`${entry.file} must not define a local rejectCrossSiteRead — require the shared util`
|
|
);
|
|
});
|
|
}
|
|
|
|
pinnedTest("the guard is ONE shared implementation, required by both surfaces", () => {
|
|
assert.ok(
|
|
indexSrc.includes('require("./utils/cross-site-read-guard")'),
|
|
"index.js must require utils/cross-site-read-guard.js"
|
|
);
|
|
assert.ok(
|
|
nodesSrc.includes('require("./utils/cross-site-read-guard")'),
|
|
"nodes.js must require utils/cross-site-read-guard.js"
|
|
);
|
|
// Anti-drift: no surface may re-introduce a local function copy.
|
|
assert.ok(
|
|
!indexSrc.includes("function rejectCrossSiteRead"),
|
|
"index.js must not define a local rejectCrossSiteRead — require the shared util"
|
|
);
|
|
assert.ok(
|
|
!nodesSrc.includes("function rejectCrossSiteRead"),
|
|
"nodes.js must not define a local rejectCrossSiteRead — require the shared util"
|
|
);
|
|
});
|
|
|
|
pinnedTest("index.js mounts the default-secure /api read gate with the documented telemetry exemptions", () => {
|
|
assert.ok(
|
|
indexSrc.includes('app.use("/api", crossSiteReadGuard.createApiReadGate({'),
|
|
"index.js must mount the shared app-wide /api read gate — new data routes are guarded by default"
|
|
);
|
|
assert.ok(
|
|
!indexSrc.includes("function createApiReadGate"),
|
|
"index.js must not define a local createApiReadGate — require the shared util"
|
|
);
|
|
// Presence AND singularity: exactly one createApiReadGate reference in the
|
|
// code (the mount). A second mount elsewhere — even one with extra
|
|
// exemptions — would widen the unguarded surface behind the documented
|
|
// one, and the presence pin alone could not see it.
|
|
const occurrences = indexSrc.split("createApiReadGate").length - 1;
|
|
assert.strictEqual(
|
|
occurrences,
|
|
1,
|
|
`index.js must reference createApiReadGate exactly once (the documented mount); found ${occurrences}`
|
|
);
|
|
// The exemption list IS part of the security posture: pin it verbatim so it
|
|
// cannot silently grow (widening the unguarded surface) or shrink (breaking
|
|
// the scripted-monitor contract on the telemetry family) without a trip.
|
|
// These paths are the same surface RATE_LIMIT_EXEMPT_PATHS/PATTERNS treats
|
|
// as scripted-monitor territory, plus the /api/status/ metrics history
|
|
// routes enumerated EXACTLY (no prefix pattern — a future route under that
|
|
// namespace must not inherit the exemption).
|
|
for (const needle of [
|
|
'exemptPaths: ["/me", "/me/status", "/servers/statuses", "/scheduler/status", "/server-info", "/status/metrics/day", "/status/metrics/summary", "/status/snapshot"]',
|
|
"/^\\/server\\/[^/]+\\/status$/",
|
|
"/^\\/server\\/[^/]+\\/node-status$/",
|
|
]) {
|
|
assert.ok(
|
|
indexSrc.includes(needle),
|
|
`expected the exact read-gate exemption entry in index.js: ${needle}`
|
|
);
|
|
}
|
|
// The prefix pattern that once exempted the whole /api/status/ namespace
|
|
// must stay gone — its inheritance is exactly what the exact-path list
|
|
// replaces.
|
|
assert.ok(
|
|
!indexSrc.includes("/^\\/status\\//"),
|
|
"the /api/status/ prefix exemption must not return — future routes under that namespace must be guarded by default"
|
|
);
|
|
});
|
|
|
|
pinnedTest("the /api read gate mount precedes every /api route definition and the nodes router mount", () => {
|
|
// The app-wide gate only protects handlers registered AFTER it in the
|
|
// stack. Moving the mount below app.use(nodesRouter) — or below any /api
|
|
// GET route definition — would silently strip the default-secure read
|
|
// posture from nodes.js's session-authenticated reads (/api/nodes,
|
|
// /api/nodes/:id, /api/nodes/:id/build, /api/nodes/:id/ports/*, none of
|
|
// which carry a per-route guard) without tripping a single presence pin.
|
|
// Pin the ORDER, not just the existence.
|
|
const gateAt = indexSrc.indexOf('app.use("/api", crossSiteReadGuard.createApiReadGate({');
|
|
assert.ok(gateAt !== -1, "the /api read gate mount must exist");
|
|
const nodesRouterAt = indexSrc.indexOf("app.use(nodesRouter);");
|
|
assert.ok(nodesRouterAt !== -1, "the nodes router mount must exist");
|
|
assert.ok(
|
|
gateAt < nodesRouterAt,
|
|
"the /api read gate must be mounted ahead of app.use(nodesRouter) — nodes.js session reads rely on the app-wide gate"
|
|
);
|
|
const routeRe = /app\.get\("\/api[^"]*"/g;
|
|
let match;
|
|
while ((match = routeRe.exec(indexSrc)) !== null) {
|
|
assert.ok(
|
|
match.index > gateAt,
|
|
`/api GET route ${match[0]} is defined before the /api read gate — it would bypass the default-secure read posture`
|
|
);
|
|
}
|
|
});
|
|
|
|
pinnedTest("the upload-url relay uses the panel's SSRF validator, not a private copy", () => {
|
|
// The shared module is wired on both sides.
|
|
assert.ok(
|
|
nodesSrc.includes('require("./utils/remote-url-guard")'),
|
|
"nodes.js must require utils/remote-url-guard.js"
|
|
);
|
|
assert.ok(
|
|
indexSrc.includes('require("./utils/remote-url-guard")'),
|
|
"index.js must require utils/remote-url-guard.js"
|
|
);
|
|
// The relay route actually calls the shared validator (window scoped to the
|
|
// route body so a stray reference elsewhere cannot satisfy this).
|
|
const at = nodesSrc.indexOf('app.post("/api/nodes/server/:name/upload-url"');
|
|
assert.notStrictEqual(at, -1, "expected the upload-url relay route in nodes.js");
|
|
const routeWindow = nodesSrc.slice(at, at + 4000);
|
|
assert.match(
|
|
routeWindow,
|
|
/assertSafeRemoteUrlWithResolvedIp\(/,
|
|
"the upload-url relay must validate the URL with the panel's assertSafeRemoteUrlWithResolvedIp"
|
|
);
|
|
// Anti-drift: the weaker duplicate (missing fec0::/10, ff00::/8, NAT64
|
|
// 64:ff9b::/96, TEST-NETs and the 80/443 port allowlist) must not come back.
|
|
assert.ok(
|
|
!nodesSrc.includes("uploaderAssertSafeRemoteUrl"),
|
|
"nodes.js must not carry a private uploaderAssertSafeRemoteUrl copy — use utils/remote-url-guard.js"
|
|
);
|
|
assert.ok(
|
|
!nodesSrc.includes("isUploaderPrivate"),
|
|
"nodes.js must not carry private isUploaderPrivateIPv4/IPv6 classifiers — use utils/remote-url-guard.js"
|
|
);
|
|
});
|
|
|
|
// ---- Functional: the real nodes.js app rejects cross-site reads -------------
|
|
|
|
const nodesApp = require("../nodes.js");
|
|
|
|
// adpanel:backups-list-brake — index.js injects the ALWAYS-ON backups-list
|
|
// read brake (nodeBackupsListRateLimiter) through setUploadPolicyHooks at
|
|
// startup; this harness targets the cross-site read guard's ordering relative
|
|
// to the auth gate, not the brake, so it injects a pass-through stub exactly
|
|
// like the suspension bridge harness does for the upload limiter (the gate
|
|
// itself fails closed when no hook arrives — pinned in
|
|
// tests/node-backups-list-brake.test.js).
|
|
const fileGuardFixtureHooks = {
|
|
fsReadRateLimiter: (req, res, next) => next(),
|
|
fsMutateRateLimiter: (req, res, next) => next(),
|
|
backupsListRateLimiter: (req, res, next) => next(),
|
|
};
|
|
nodesApp.setUploadPolicyHooks(fileGuardFixtureHooks);
|
|
|
|
pinnedTest("the proxy Files routes use the same read and mutation limiters as the panel", async () => {
|
|
assert.match(indexSrc, /fsReadRateLimiter: serverFsReadRateLimiter,/);
|
|
assert.match(indexSrc, /fsMutateRateLimiter: serverFsMutateRateLimiter,/);
|
|
const calls = [];
|
|
const server = http.createServer(nodesApp);
|
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
const base = `http://127.0.0.1:${server.address().port}/api/nodes/server/fixture`;
|
|
try {
|
|
nodesApp.setUploadPolicyHooks({
|
|
...fileGuardFixtureHooks,
|
|
fsReadRateLimiter: (req, res) => { calls.push("read"); res.sendStatus(429); },
|
|
fsMutateRateLimiter: (req, res) => { calls.push("mutate"); res.sendStatus(429); },
|
|
});
|
|
for (const [method, route, budget] of [
|
|
["GET", "entries", "read"], ["GET", "file", "read"], ["HEAD", "download", "read"],
|
|
["POST", "file", "mutate"], ["POST", "delete", "mutate"], ["POST", "delete-batch", "mutate"],
|
|
["POST", "rename", "mutate"], ["POST", "create", "mutate"],
|
|
]) {
|
|
const response = await fetch(`${base}/${route}`, { method });
|
|
assert.strictEqual(response.status, 429, `${method} ${route}`);
|
|
assert.deepStrictEqual(calls.splice(0), [budget]);
|
|
await response.text();
|
|
}
|
|
} finally {
|
|
nodesApp.setUploadPolicyHooks(fileGuardFixtureHooks);
|
|
await new Promise((resolve) => server.close(resolve));
|
|
}
|
|
});
|
|
|
|
pinnedTest("integration: the relay file-read GETs reject cross-site reads ahead of auth", async () => {
|
|
const server = http.createServer(nodesApp);
|
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
// Teardown inside the tallied body (see pinnedTest above): a failed close
|
|
// must fail the test in direct node-file mode too.
|
|
try {
|
|
// Per guarded relay, three environment-independent assertions:
|
|
//
|
|
// Cross-site: the shared guard must answer 403 with ITS OWN error body —
|
|
// reaching the guard's response proves the request never reached the
|
|
// access gate (a 401/403/404/500 from the gate would mean the guard did
|
|
// not run first).
|
|
//
|
|
// Same-origin and headerless (curl / API scripts): past the guard, into
|
|
// the access gate — which, with no session, answers 401 "not
|
|
// authenticated" before touching the database. Asserting the 401 (not
|
|
// the guard's 403) proves the guard did not over-block legitimate
|
|
// same-origin / scripted traffic.
|
|
//
|
|
// The uniform 401 also regression-pins the /eula ordering fix: if
|
|
// performPanelEulaStatus ever resolves the server (remoteContext) BEFORE
|
|
// authenticating again, this harness would stop seeing a deterministic
|
|
// 401 and this assertion would fail.
|
|
for (const route of RELAY_GUARDED_ROUTES) {
|
|
const url = `${base}${route.replace(":name", "parity-probe-server")}`;
|
|
|
|
const blocked = await fetch(url, { headers: { "Sec-Fetch-Site": "cross-site" } });
|
|
assert.strictEqual(
|
|
blocked.status,
|
|
403,
|
|
`${route} must answer 403 for a cross-site read (got ${blocked.status})`
|
|
);
|
|
assert.deepStrictEqual(
|
|
await blocked.json(),
|
|
{ error: "cross-site request blocked" },
|
|
`${route} cross-site rejection must carry the shared guard's error body`
|
|
);
|
|
|
|
const sameOrigin = await fetch(url, { headers: { "Sec-Fetch-Site": "same-origin" } });
|
|
assert.strictEqual(sameOrigin.status, 401, `${route} must let same-origin requests reach the access gate`);
|
|
assert.deepStrictEqual(await sameOrigin.json(), { error: "not authenticated" });
|
|
|
|
const headerless = await fetch(url);
|
|
assert.strictEqual(headerless.status, 401, `${route} must not block headerless non-browser clients`);
|
|
assert.deepStrictEqual(await headerless.json(), { error: "not authenticated" });
|
|
}
|
|
} finally {
|
|
await new Promise((r) => server.close(r));
|
|
}
|
|
});
|
|
|
|
pinnedTest("integration: the guard falls back to Origin/Referer when Sec-Fetch-Site is absent", async () => {
|
|
const server = http.createServer(nodesApp);
|
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
const url = `${base}/api/nodes/server/parity-probe-server/file`;
|
|
|
|
try {
|
|
// Old-browser cross-site fetch: Origin present, no Fetch Metadata → the
|
|
// guard must answer 403 with ITS OWN body (a 401 would mean the guard let
|
|
// it through to the auth gate — the hole this fallback closes).
|
|
const evilOrigin = await fetch(url, { headers: { Origin: "https://evil.example" } });
|
|
assert.strictEqual(evilOrigin.status, 403, "cross-origin Origin without metadata must be rejected by the guard");
|
|
assert.deepStrictEqual(await evilOrigin.json(), { error: "cross-site request blocked" });
|
|
|
|
// Same for Referer-only evidence (old-browser navigations/embeds).
|
|
const evilReferer = await fetch(url, { headers: { Referer: "https://evil.example/attack.html" } });
|
|
assert.strictEqual(evilReferer.status, 403, "cross-origin Referer without metadata must be rejected by the guard");
|
|
assert.deepStrictEqual(await evilReferer.json(), { error: "cross-site request blocked" });
|
|
|
|
// Sec-Fetch-Site: same-site + foreign Origin is held to the host standard.
|
|
const sameSiteForeign = await fetch(url, {
|
|
headers: { "Sec-Fetch-Site": "same-site", Origin: "https://evil.example.com" },
|
|
});
|
|
assert.strictEqual(sameSiteForeign.status, 403, "same-site attestation must not endorse a foreign host");
|
|
|
|
// Same-origin evidence passes the guard into the 401 auth gate.
|
|
const sameOrigin = await fetch(url, { headers: { Origin: base } });
|
|
assert.strictEqual(sameOrigin.status, 401, "same-origin Origin without metadata must reach the auth gate");
|
|
assert.deepStrictEqual(await sameOrigin.json(), { error: "not authenticated" });
|
|
|
|
// Opaque null origin carries no cookies here → passes into the auth gate.
|
|
const nullOrigin = await fetch(url, { headers: { Origin: "null" } });
|
|
assert.strictEqual(nullOrigin.status, 401, "cookieless null Origin must reach the auth gate");
|
|
} finally {
|
|
await new Promise((r) => server.close(r));
|
|
}
|
|
});
|
|
|
|
pinnedTest("integration: cookie-bearing evidence-less reads are rejected; attested navigations and declared origins reach auth", async () => {
|
|
const server = http.createServer(nodesApp);
|
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
const url = `${base}/api/nodes/server/parity-probe-server/file`;
|
|
|
|
try {
|
|
// The closed residual: an old browser whose Referer was stripped — or a
|
|
// same-site sibling that stripped its own — arrives with zero evidence
|
|
// while SameSite=Lax still attaches the session cookie. The guard must
|
|
// answer 403 with ITS OWN body ahead of the auth gate.
|
|
const stripped = await fetch(url, { headers: { Cookie: "connect.sid=parity" } });
|
|
assert.strictEqual(
|
|
stripped.status,
|
|
403,
|
|
"cookie-bearing evidence-less read must be rejected by the guard"
|
|
);
|
|
assert.deepStrictEqual(
|
|
await stripped.json(),
|
|
{ error: "cross-site request blocked" },
|
|
"the evidence-less cookie rejection must carry the shared guard's error body"
|
|
);
|
|
|
|
// Same-site attestation with no evidence host: the sibling-subdomain
|
|
// shape on CURRENT browsers (no-cors GET, referrerPolicy: no-referrer).
|
|
const sameSiteSibling = await fetch(url, {
|
|
headers: { Cookie: "connect.sid=parity", "Sec-Fetch-Site": "same-site" },
|
|
});
|
|
assert.strictEqual(
|
|
sameSiteSibling.status,
|
|
403,
|
|
"same-site attestation with no evidence host must be rejected when cookies ride along"
|
|
);
|
|
|
|
// Browser-attested top-level navigation (address bar / bookmark /
|
|
// reload): hostile JS cannot forge Sec-Fetch-*, so "none" keeps
|
|
// cookie-bearing requests working — past the guard, into the 401 auth
|
|
// gate (no session here).
|
|
const navigation = await fetch(url, {
|
|
headers: { Cookie: "connect.sid=parity", "Sec-Fetch-Site": "none" },
|
|
});
|
|
assert.strictEqual(navigation.status, 401, "attested no-initiator navigation must reach the auth gate");
|
|
assert.deepStrictEqual(await navigation.json(), { error: "not authenticated" });
|
|
|
|
// Scripted session clients declare themselves with an Origin — the same
|
|
// one-header declaration the CSRF middleware requires of them for
|
|
// writes. Same-host evidence passes the guard into the 401 auth gate.
|
|
const declared = await fetch(url, {
|
|
headers: { Cookie: "connect.sid=parity", Origin: base },
|
|
});
|
|
assert.strictEqual(declared.status, 401, "cookie + same-host Origin (scripted client) must reach the auth gate");
|
|
assert.deepStrictEqual(await declared.json(), { error: "not authenticated" });
|
|
} finally {
|
|
await new Promise((r) => server.close(r));
|
|
}
|
|
});
|
|
|
|
// ---- adpanel:csrf-port-awareness — the shared explicit-port rule --------------
|
|
|
|
pinnedTest("the explicit-port rule is ONE shared decision routed through by both trust surfaces", () => {
|
|
const guardSrcFull = 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")
|
|
);
|
|
assert.ok(
|
|
originHostSrc.includes("function csrfPortMismatch"),
|
|
"utils/origin-host.js is the ONE home of the explicit-port decision (adpanel:csrf-port-awareness)"
|
|
);
|
|
// Anti-drift: no surface may carry a second copy of the rule.
|
|
assert.ok(
|
|
!indexSrc.includes("function csrfPortMismatch") && !guardSrcFull.includes("function csrfPortMismatch"),
|
|
"neither index.js nor the read guard may define a local csrfPortMismatch"
|
|
);
|
|
for (const [label, src] of [["index.js", indexSrc], ["cross-site-read-guard.js", guardSrcFull]]) {
|
|
assert.ok(
|
|
src.includes("csrfPortMismatch({"),
|
|
`${label} must route the explicit-port decision through the shared csrfPortMismatch`
|
|
);
|
|
assert.ok(
|
|
src.includes("parseOriginHostPort(") && src.includes("extractHeaderHostPort("),
|
|
`${label} must derive ports from the shared port-preserving primitives in utils/origin-host.js`
|
|
);
|
|
}
|
|
// The middleware must decide the port rule BEFORE the loopback alias grant:
|
|
// the grant is host-level and must never bypass it.
|
|
const win = indexSrc.slice(
|
|
indexSrc.indexOf("async function sameOriginProtection"),
|
|
indexSrc.indexOf("app.use(sameOriginProtection);")
|
|
);
|
|
const portAt = win.indexOf("csrfPortMismatch({");
|
|
const aliasAt = win.indexOf('allowedHosts.add("localhost")');
|
|
assert.notStrictEqual(portAt, -1, "expected the port check inside sameOriginProtection");
|
|
assert.notStrictEqual(aliasAt, -1, "expected the loopback alias grant inside sameOriginProtection");
|
|
assert.ok(portAt < aliasAt, "the port check must run ahead of the host-level alias grant");
|
|
// The guard needs the public URL's explicit port for the proxy-rewrite escape.
|
|
assert.ok(
|
|
indexSrc.includes("panelPublicPort: _CSRF_PANEL_PUBLIC_PORT"),
|
|
"index.js must inject the PANEL_PUBLIC_URL port into the guard's trust context"
|
|
);
|
|
});
|
|
|
|
pinnedTest("integration: cookie-bearing sibling-port reads are rejected; same-port and cookie-less shapes reach auth", async () => {
|
|
const server = http.createServer(nodesApp);
|
|
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
const url = `${base}/api/nodes/server/parity-probe-server/file`;
|
|
|
|
try {
|
|
// The listening port is explicit and non-default, so it is real port
|
|
// evidence on the serving side: an Origin from the SAME host on a
|
|
// DIFFERENT explicit port with cookies riding is exactly the residual
|
|
// the shared rule closes — the guard's own 403, ahead of the auth gate.
|
|
const sibling = await fetch(url, {
|
|
headers: { Cookie: "connect.sid=parity", Origin: "http://127.0.0.1:9999" },
|
|
});
|
|
assert.strictEqual(sibling.status, 403, "cookie-bearing sibling-port read must be rejected by the guard");
|
|
assert.deepStrictEqual(
|
|
await sibling.json(),
|
|
{ error: "cross-site request blocked" },
|
|
"the sibling-port rejection must carry the shared guard's error body"
|
|
);
|
|
|
|
// Equal explicit ports: same host AND same port — passes the guard into
|
|
// the 401 auth gate (no behavior change for legitimate same-origin
|
|
// scripted clients).
|
|
const samePort = await fetch(url, {
|
|
headers: { Cookie: "connect.sid=parity", Origin: base },
|
|
});
|
|
assert.strictEqual(samePort.status, 401, "same-host same-port Origin must reach the auth gate");
|
|
assert.deepStrictEqual(await samePort.json(), { error: "not authenticated" });
|
|
|
|
// Cookie-less sibling-port request: no ambient authority — the same
|
|
// posture the evidence-less path already gives anonymous requests; it
|
|
// falls through to the auth gate, not the guard's 403.
|
|
const anonymous = await fetch(url, {
|
|
headers: { Origin: "http://127.0.0.1:9999" },
|
|
});
|
|
assert.strictEqual(anonymous.status, 401, "cookie-less sibling-port request must keep the no-cookie posture");
|
|
assert.deepStrictEqual(await anonymous.json(), { error: "not authenticated" });
|
|
} finally {
|
|
await new Promise((r) => server.close(r));
|
|
}
|
|
});
|