583 lines
28 KiB
JavaScript
583 lines
28 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:preauth-gate-case-fold — tests for the generic pre-auth gate's
|
|
// exemption case handling (index.js, the app.use middleware carrying the
|
|
// adpanel:preauth-gate-case-fold comment).
|
|
//
|
|
// Express dispatches routes case-insensitively (caseSensitive: false is the
|
|
// default in both apps), so /LOGIN, /Api/Me or /HEALTHZ reach exactly the
|
|
// same handlers as their lowercase spellings. The gate's route-like
|
|
// exemptions must fold case the same way, or the gate redirects/401s
|
|
// requests the router would have served (the consistency defect this fixes:
|
|
// pre-fix, /LOGIN got the gate's 302 while /login got the login page).
|
|
//
|
|
// The static-prefix exemptions stay case-sensitive ON PURPOSE: their content
|
|
// is served from the case-sensitive filesystem (express.static resolves the
|
|
// FILE case-sensitively — /images/REAL.PNG 404s where /images/real.png
|
|
// serves; pinned behaviorally below), so exempting case variants would
|
|
// widen the unauthenticated surface without serving anything new.
|
|
//
|
|
// These tests pin:
|
|
// - every route-like entry (the three auth-page prefixes, /favicon.ico,
|
|
// /healthz, /healtz, /api/me, /api/maintenance/status) is exempt for
|
|
// lowercase AND case-variant spellings
|
|
// - the static-prefix entries stay exempt only for exact-case spellings;
|
|
// case variants are NOT exempt (fail closed into the redirect/401)
|
|
// - match shapes are unchanged: startsWith stays startsWith, === stays ===
|
|
// (so /api/me/status and /healthz-extra are still not exempt)
|
|
// - trailing-slash parity (the strict:false mirror): the === entries
|
|
// compare a one-trailing-slash-stripped form, so /favicon.ico/,
|
|
// /api/me/ and /healthz/ are exempt exactly where the router serves
|
|
// them, while two-slash spellings (/favicon.ico//) stay gate-blocked —
|
|
// the router 404s those too (pinned behaviorally against the installed
|
|
// express below); the prefix entries keep the folded path (a trailing
|
|
// slash already matches startsWith) and '/' strips to "" (root stays
|
|
// gated)
|
|
// - the gate's unauthenticated redirect carries Cache-Control: no-store
|
|
// (a JSON-accepting fetch reaches it with no header otherwise — the
|
|
// global HTML no-store middleware is GET/HEAD + HTML-Accept only), and
|
|
// the /api/ 401 exit inherits its Cache-Control from the CDN/proxy
|
|
// middleware mounted immediately before the gate (pinned by composing
|
|
// both extracted middlewares)
|
|
// - one lowercased path const feeds the prefix entries and one
|
|
// slash-stripped const feeds the five exact entries; the static
|
|
// prefixes still compare the raw path
|
|
// - the stealth gate still runs BEFORE this gate and its login-path
|
|
// classifier folds case, so case-variant login paths are intercepted
|
|
// upstream when stealth is active (no ordering regression)
|
|
// - the /api/me equivalence: an unauthenticated case-variant /API/ME is now
|
|
// served by the route itself, which returns 401 {ok:false, user:null} —
|
|
// the same status and not-authenticated semantics as the gate's API-format
|
|
// 401 ({error:"not authenticated"}), just the endpoint's own canonical
|
|
// shape. That is the desired equivalence: the case variant is the same
|
|
// route and must receive the response the route gives, mirroring the
|
|
// documented lesson on the gate's own /api/ discrimination below it.
|
|
|
|
const test = require("node:test");
|
|
const assert = require("node:assert");
|
|
const fs = require("node:fs");
|
|
const os = require("node:os");
|
|
const path = require("node:path");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
|
|
// Locate the enclosing `app.use(` middleware for an inner marker and slice
|
|
// the brace-balanced block plus its trailing `);`. The block under test
|
|
// contains no brace-bearing string/regex literals, so naive matching suffices.
|
|
function extractMiddleware(source, innerMarker) {
|
|
const markerIdx = source.indexOf(innerMarker);
|
|
assert.ok(markerIdx >= 0, `marker not found: ${innerMarker}`);
|
|
const start = source.lastIndexOf("app.use(", markerIdx);
|
|
assert.ok(start >= 0, `app.use( not found before marker: ${innerMarker}`);
|
|
const bodyStart = source.indexOf("{", start);
|
|
let depth = 0;
|
|
let i = bodyStart;
|
|
for (; i < source.length; i += 1) {
|
|
if (source[i] === "{") depth += 1;
|
|
else if (source[i] === "}") {
|
|
depth -= 1;
|
|
if (depth === 0) {
|
|
i += 1;
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
assert.ok(depth === 0, `unbalanced braces after marker: ${innerMarker}`);
|
|
while (i < source.length && (source[i] === ")" || source[i] === ";" || /\s/.test(source[i]))) {
|
|
i += 1;
|
|
if (source[i - 1] === ")") break;
|
|
}
|
|
return source.slice(start, i);
|
|
}
|
|
|
|
const GATE_MARKER = "// adpanel:preauth-gate-case-fold —";
|
|
|
|
function loadGate() {
|
|
const block = extractMiddleware(indexSource, GATE_MARKER);
|
|
let captured = null;
|
|
const sandbox = {
|
|
app: { use: (mw) => { captured = mw; } },
|
|
isOpenNodeRoute: async (req) => req._openRoute === true,
|
|
isAuthenticated: async (req) => req._authed === true
|
|
};
|
|
require("node:vm").createContext(sandbox);
|
|
require("node:vm").runInContext(block, sandbox);
|
|
assert.ok(captured, "preauth gate middleware was not registered");
|
|
return captured;
|
|
}
|
|
|
|
function makeRes() {
|
|
return {
|
|
statusCode: 0,
|
|
body: null,
|
|
redirectedTo: null,
|
|
headers: {},
|
|
status(c) { this.statusCode = c; return this; },
|
|
json(b) { this.body = b; return this; },
|
|
redirect(target) { this.redirectedTo = target; return this; },
|
|
setHeader(name, value) { this.headers[String(name).toLowerCase()] = value; }
|
|
};
|
|
}
|
|
|
|
async function runGate(gate, req) {
|
|
const res = makeRes();
|
|
let nexted = false;
|
|
let nextArg = undefined;
|
|
await Promise.resolve(gate(req, res, (arg) => { nexted = true; nextArg = arg; }));
|
|
return { res, nexted, nextArg };
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Source pins: one folded const feeds the 8 route-like entries; static
|
|
// prefixes keep the raw path; match shapes are unchanged
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("source pin: the folded const feeds the prefix entries and one slash-stripped const feeds the five exact entries", () => {
|
|
const block = extractMiddleware(indexSource, GATE_MARKER);
|
|
// Count on CODE only: the gate's explanatory comment mentions the const
|
|
// names, and the pins below are about the code shape.
|
|
const code = block.split("\n").filter((l) => !l.trim().startsWith("//")).join("\n");
|
|
|
|
const decl = "const pLowerPath = String(req.path || \"\").toLowerCase();";
|
|
assert.equal(code.split(decl).length - 1, 1,
|
|
"the gate must declare the folded path exactly once");
|
|
|
|
// The strip must remove exactly ONE trailing '/' (replace(/\/$/, "")) —
|
|
// not all of them — mirroring strict:false's single optional slash.
|
|
const stripDecl = "const pExact = pLowerPath.replace(/\\/$/, \"\");";
|
|
assert.equal(code.split(stripDecl).length - 1, 1,
|
|
"the gate must declare the one-trailing-slash-stripped form exactly once, stripping exactly ONE slash");
|
|
|
|
const prefixEntries = [
|
|
"pLowerPath.startsWith(\"/login\")",
|
|
"pLowerPath.startsWith(\"/register\")",
|
|
"pLowerPath.startsWith(\"/forgot-password\")"
|
|
];
|
|
for (const entry of prefixEntries) {
|
|
assert.equal(code.split(entry).length - 1, 1,
|
|
`prefix entry must stay on the folded path exactly once: ${entry}`);
|
|
}
|
|
|
|
const exactEntries = [
|
|
"pExact === \"/favicon.ico\"",
|
|
"pExact === \"/healthz\"",
|
|
"pExact === \"/healtz\"",
|
|
"pExact === \"/api/me\"",
|
|
"pExact === \"/api/maintenance/status\""
|
|
];
|
|
for (const entry of exactEntries) {
|
|
assert.equal(code.split(entry).length - 1, 1,
|
|
`exact entry must use the stripped form exactly once: ${entry}`);
|
|
}
|
|
|
|
// Nothing else may consume either const: the folded const appears once as
|
|
// its declaration, once inside the strip declaration, and three times as
|
|
// the prefix entries; the stripped const appears once as its declaration
|
|
// plus five entry uses. Adding an entry forces a conscious test update.
|
|
assert.equal((code.match(/pLowerPath/g) || []).length, 5,
|
|
"the folded const must appear exactly once as declaration, once in the strip declaration, plus three prefix uses");
|
|
assert.equal((code.match(/pExact/g) || []).length, 6,
|
|
"the stripped const must appear exactly once as declaration plus five exact-entry uses");
|
|
|
|
// The stripped form must not feed a prefix leg (prefix entries keep the
|
|
// folded path; a trailing slash on a prefix entry already matches).
|
|
assert.ok(!code.includes("pExact.startsWith"),
|
|
"prefix entries must stay on the folded path, not the stripped form");
|
|
|
|
// No case-sensitive residue on the folded entries.
|
|
for (const entry of ["req.path === \"/favicon.ico\"", "req.path === \"/healthz\"",
|
|
"req.path === \"/healtz\"", "req.path === \"/api/me\"",
|
|
"req.path === \"/api/maintenance/status\"", "req.path.startsWith(\"/login\")",
|
|
"req.path.startsWith(\"/register\")", "req.path.startsWith(\"/forgot-password\")"]) {
|
|
assert.ok(!block.includes(entry),
|
|
`folded entry must not remain on the raw path: ${entry}`);
|
|
}
|
|
});
|
|
|
|
test("source pin: static-prefix entries stay on the raw path (case-sensitive on purpose)", () => {
|
|
const block = extractMiddleware(indexSource, GATE_MARKER);
|
|
|
|
const rawPrefixEntries = [
|
|
"req.path.startsWith(\"/db-access/\")",
|
|
"req.path.startsWith(\"/images/\")",
|
|
"req.path.startsWith(\"/css/\")",
|
|
"req.path.startsWith(\"/js/\")",
|
|
"req.path.startsWith(\"/vendor/\")",
|
|
"req.path.startsWith(\"/uploads/\")",
|
|
"req.path.startsWith(\"/auth-assets/\")",
|
|
"req.path.startsWith(\"/branding-media/\")"
|
|
];
|
|
for (const entry of rawPrefixEntries) {
|
|
assert.equal(block.split(entry).length - 1, 1,
|
|
`static-prefix entry must keep the raw path exactly once: ${entry}`);
|
|
}
|
|
for (const entry of ["pLowerPath.startsWith(\"/db-access/\")", "pLowerPath.startsWith(\"/images/\")",
|
|
"pLowerPath.startsWith(\"/css/\")", "pLowerPath.startsWith(\"/js/\")",
|
|
"pLowerPath.startsWith(\"/vendor/\")", "pLowerPath.startsWith(\"/uploads/\")",
|
|
"pLowerPath.startsWith(\"/auth-assets/\")", "pLowerPath.startsWith(\"/branding-media/\")"]) {
|
|
assert.ok(!block.includes(entry),
|
|
`static prefix must NOT be case-folded (the filesystem serving it is case-sensitive): ${entry}`);
|
|
}
|
|
});
|
|
|
|
test("source pin: no route exists outside the folded prefixes' own class (no /LoginFoo handler)", () => {
|
|
// Folding startsWith("/login") exempts the case variants of the /login*
|
|
// prefixes. That only mirrors routing if every handler reachable under
|
|
// those prefixes is one of the known auth surfaces — otherwise a case
|
|
// variant would newly expose a different handler pre-auth.
|
|
const registrations = [...indexSource.matchAll(
|
|
/app\.(?:get|post|put|delete|all|use)\(\s*"\/(?:login|register|forgot-password)[^"]*"/g
|
|
)].map((m) => m[0]);
|
|
const mounted = new Set(registrations.map((r) => r.replace(/^app\.[a-z]+\(\s*"/, "").replace(/"$/, "")));
|
|
assert.deepEqual(mounted, new Set(["/login", "/register", "/forgot-password"]),
|
|
`unexpected handler mounted under a folded prefix: ${[...mounted].join(", ")}`);
|
|
assert.equal(indexSource.includes("app.get(\"/login.css\""), false,
|
|
"/login.css must stay static-served (already covered by the /login prefix), never a route");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavior pins (middleware replicated in a vm sandbox)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("route-like entries: lowercase and case variants are exempt (gate calls next)", async () => {
|
|
const gate = loadGate();
|
|
|
|
const exempt = [
|
|
"/login", "/LOGIN", "/Login", "/lOgIn", "/LOGIN/", // trailing slash = same route (strict:false)
|
|
"/register", "/REGISTER", "/Register",
|
|
"/forgot-password", "/FORGOT-PASSWORD", "/Forgot-Password",
|
|
"/favicon.ico", "/FAVICON.ICO", "/Favicon.ico",
|
|
"/healthz", "/HEALTHZ", "/Healthz",
|
|
"/healtz", "/HEALTZ", "/Healtz", // the documented stealth decoy route, folded
|
|
"/api/me", "/API/ME", "/Api/Me",
|
|
"/api/maintenance/status", "/API/MAINTENANCE/STATUS", "/Api/Maintenance/Status"
|
|
];
|
|
for (const p of exempt) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, true, `${p} must be exempt (the router serves the same handler)`);
|
|
assert.equal(out.res.statusCode, 0, `${p} must not be answered by the gate itself`);
|
|
assert.equal(out.res.redirectedTo, null, `${p} must not be redirected by the gate`);
|
|
}
|
|
});
|
|
|
|
test("trailing-slash parity: one-slash spellings of the exact entries are exempt (strict:false mirror)", async () => {
|
|
const gate = loadGate();
|
|
|
|
// Express mounts routes strict:false — exactly ONE trailing '/' is
|
|
// optional — so these spellings reach the same handlers as the bare
|
|
// spellings and must be exempt exactly the same way (verified against
|
|
// the installed express in the behavioral test below).
|
|
const exempt = [
|
|
"/favicon.ico/", "/FAVICON.ico/",
|
|
"/healthz/", "/HEALTHZ/",
|
|
"/healtz/", "/HEALTZ/",
|
|
"/api/me/", "/API/ME/",
|
|
"/api/maintenance/status/", "/API/MAINTENANCE/STATUS/"
|
|
];
|
|
for (const p of exempt) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, true, `${p} must be exempt (strict:false serves the one-slash spelling)`);
|
|
assert.equal(out.res.statusCode, 0, `${p} must not be answered by the gate itself`);
|
|
}
|
|
});
|
|
|
|
test("trailing-slash parity: two-slash spellings are NOT exempt (the router 404s them too)", async () => {
|
|
const gate = loadGate();
|
|
|
|
// The strip removes exactly ONE trailing slash, so a two-slash spelling
|
|
// keeps its extra slash and misses every entry — matching the router,
|
|
// which does not serve it (pinned behaviorally below).
|
|
for (const p of ["/favicon.ico//", "/healthz//", "/healtz//", "/api/me//", "/api/maintenance/status//"]) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, false, `${p} must not be exempt (strict:false makes at most ONE slash optional)`);
|
|
if (p.toLowerCase().startsWith("/api/")) {
|
|
assert.equal(out.res.statusCode, 401, `${p} keeps the gate's API-format 401`);
|
|
assert.deepEqual(out.res.body, { error: "not authenticated" });
|
|
} else {
|
|
assert.equal(out.res.redirectedTo, "/login", `${p} falls into the unauthenticated redirect`);
|
|
}
|
|
}
|
|
|
|
// '/' strips to "" and still misses every entry: root behavior unchanged.
|
|
const root = await runGate(gate, { path: "/", method: "GET" });
|
|
assert.equal(root.nexted, false, "/ must not be exempt");
|
|
assert.equal(root.res.redirectedTo, "/login", "/ must keep the unauthenticated redirect");
|
|
});
|
|
|
|
test("prefix entries keep the folded path: trailing slash already matches startsWith (unchanged)", async () => {
|
|
const gate = loadGate();
|
|
|
|
// The strip feeds ONLY the === legs: the prefix entries stay on the
|
|
// folded path, where a trailing slash already matched before this fix.
|
|
// (A two-slash spelling under a prefix therefore stays exempt though the
|
|
// router 404s it — the same cosmetic class the === legs just closed, left
|
|
// as-is here on purpose: startsWith shape unchanged, sub-path handlers
|
|
// under these prefixes are the auth pages themselves.)
|
|
for (const p of ["/login/", "/register/", "/forgot-password/", "/LOGIN/", "/register//"]) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, true, `${p} must stay exempt (a trailing slash on a prefix entry already matches)`);
|
|
}
|
|
});
|
|
|
|
test("gate redirect carries Cache-Control: no-store (JSON-accepting fetches reach it headerless otherwise)", async () => {
|
|
const gate = loadGate();
|
|
|
|
const out = await runGate(gate, { path: "/dashboard", method: "GET" });
|
|
assert.equal(out.res.redirectedTo, "/login");
|
|
assert.equal(out.res.headers["cache-control"], "no-store",
|
|
"the gate's unauthenticated redirect must set Cache-Control: no-store");
|
|
|
|
// Same header on every redirect exit class (case-variant static prefix
|
|
// fails closed into the redirect).
|
|
const cv = await runGate(gate, { path: "/IMAGES/x.png", method: "GET" });
|
|
assert.equal(cv.res.redirectedTo, "/login");
|
|
assert.equal(cv.res.headers["cache-control"], "no-store",
|
|
"every gate redirect must set Cache-Control: no-store");
|
|
});
|
|
|
|
test("the /api/ 401 exit inherits Cache-Control from the CDN/proxy middleware mounted before the gate", async () => {
|
|
// The gate's 401 exit sets no header of its own on purpose: the
|
|
// "Prevent CDN/proxy caching of authenticated API responses" middleware
|
|
// immediately before the gate pre-sets Cache-Control on every /api/
|
|
// path regardless of method or Accept. Compose the two extracted
|
|
// middlewares to pin the wire shape the real stack produces.
|
|
const constMatch = indexSource.match(/const HTML_NO_STORE_CACHE_CONTROL = "([^"]+)"/);
|
|
assert.ok(constMatch, "HTML_NO_STORE_CACHE_CONTROL const not found");
|
|
|
|
let apiMw = null;
|
|
const apiSandbox = {
|
|
app: { use: (mw) => { apiMw = mw; } },
|
|
HTML_NO_STORE_CACHE_CONTROL: constMatch[1]
|
|
};
|
|
require("node:vm").createContext(apiSandbox);
|
|
// extractMiddleware finds the app.use( BEFORE the marker, so the marker
|
|
// must sit inside this block's body — "Vary", "Cookie" via setHeader is
|
|
// unique to the CDN/proxy middleware (the HTML no-store middleware
|
|
// appends Vary instead).
|
|
require("node:vm").runInContext(
|
|
extractMiddleware(indexSource, 'res.setHeader("Vary", "Cookie");'),
|
|
apiSandbox
|
|
);
|
|
assert.ok(apiMw, "CDN/proxy middleware was not registered");
|
|
|
|
// Ordering is load-bearing: if the middleware moved below the gate, the
|
|
// 401 would go headerless.
|
|
assert.ok(
|
|
indexSource.indexOf('res.setHeader("Vary", "Cookie");') < indexSource.indexOf(GATE_MARKER),
|
|
"the /api/ no-store middleware must precede the generic pre-auth gate"
|
|
);
|
|
|
|
const gate = loadGate();
|
|
const req = { path: "/api/settings/x", method: "GET" };
|
|
const res = makeRes();
|
|
let nexted = false;
|
|
await Promise.resolve(apiMw(req, res, () => {}));
|
|
await Promise.resolve(gate(req, res, () => { nexted = true; }));
|
|
assert.equal(nexted, false, "unauthenticated /api/ path must be answered by the gate's 401");
|
|
assert.equal(res.statusCode, 401);
|
|
assert.deepEqual(res.body, { error: "not authenticated" });
|
|
assert.equal(res.headers["cache-control"], constMatch[1],
|
|
"the 401 must carry the CDN/proxy middleware's Cache-Control");
|
|
});
|
|
|
|
test("static prefixes: lowercase stays exempt; case variants are NOT exempt (fail closed)", async () => {
|
|
const gate = loadGate();
|
|
|
|
for (const p of ["/images/x.png", "/css/x.css", "/js/x.js", "/vendor/v/font.css",
|
|
"/uploads/a.png", "/auth-assets/login.css", "/branding-media/login-background",
|
|
"/db-access/phpmyadmin/"]) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, true, `${p} (exact case) must stay exempt`);
|
|
}
|
|
|
|
for (const p of ["/IMAGES/x.png", "/CSS/x.css", "/JS/x.js", "/VENDOR/v/font.css",
|
|
"/UPLOADS/a.png", "/Images/x.png", "/AUTH-ASSETS/login.css", "/Branding-Media/login-background",
|
|
"/DB-ACCESS/phpmyadmin/"]) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, false, `${p} must NOT be exempt (case-sensitive serving layer)`);
|
|
assert.equal(out.res.redirectedTo, "/login", `${p} must fall into the unauthenticated redirect`);
|
|
}
|
|
});
|
|
|
|
test("match shapes unchanged: === entries do not absorb suffixes; unauth API format preserved", async () => {
|
|
const gate = loadGate();
|
|
|
|
// === stays ===: suffix paths under the exact entries were never exempt.
|
|
for (const p of ["/api/me/status", "/API/ME/status", "/healthz-extra", "/healtz2", "/favicon.ico.txt"]) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, false, `${p} must not be exempt`);
|
|
if (p.toLowerCase().startsWith("/api/")) {
|
|
assert.equal(out.res.statusCode, 401, `${p} must keep the gate's API-format 401`);
|
|
assert.deepEqual(out.res.body, { error: "not authenticated" });
|
|
} else {
|
|
assert.equal(out.res.redirectedTo, "/login", `${p} must be redirected`);
|
|
}
|
|
}
|
|
|
|
// startsWith stays startsWith: sub-paths of the auth pages were exempt
|
|
// before the fold and stay exempt (no shape change, only case).
|
|
for (const p of ["/login/foo", "/LOGIN/FOO", "/register/x", "/REGISTER/x"]) {
|
|
const out = await runGate(gate, { path: p, method: "GET" });
|
|
assert.equal(out.nexted, true, `${p} must stay exempt (prefix shape preserved)`);
|
|
}
|
|
|
|
// Unrelated paths still hit the gate.
|
|
const dash = await runGate(gate, { path: "/dashboard", method: "GET" });
|
|
assert.equal(dash.nexted, false);
|
|
assert.equal(dash.res.redirectedTo, "/login");
|
|
|
|
// Open node routes still bypass; authenticated users still pass through.
|
|
const open = await runGate(gate, { path: "/api/nodes/x/heartbeat", method: "POST", _openRoute: true });
|
|
assert.equal(open.nexted, true, "open node routes must still bypass the gate");
|
|
const authed = await runGate(gate, { path: "/dashboard", method: "GET", _authed: true });
|
|
assert.equal(authed.nexted, true, "authenticated requests must pass through");
|
|
});
|
|
|
|
test("gate errors still fall closed through next(err)", async () => {
|
|
const block = extractMiddleware(indexSource, GATE_MARKER);
|
|
let captured = null;
|
|
const sandbox = {
|
|
app: { use: (mw) => { captured = mw; } },
|
|
isOpenNodeRoute: async () => { throw new Error("boom"); },
|
|
isAuthenticated: async () => true
|
|
};
|
|
require("node:vm").createContext(sandbox);
|
|
require("node:vm").runInContext(block, sandbox);
|
|
const res = makeRes();
|
|
let nextArg = undefined;
|
|
await Promise.resolve(captured({ path: "/dashboard", method: "GET" }, res, (a) => { nextArg = a; }));
|
|
assert.ok(nextArg && nextArg.message === "boom", "errors must be forwarded via next(err)");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Ordering + equivalence pins
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("the stealth gate runs BEFORE this gate and folds case on login paths (no ordering regression)", () => {
|
|
const stealthIdx = indexSource.indexOf("if (!STEALTH_ACTIVE) return next();");
|
|
const gateIdx = indexSource.indexOf(GATE_MARKER);
|
|
assert.ok(stealthIdx >= 0 && gateIdx > stealthIdx,
|
|
"the stealth gate middleware must sit before the generic pre-auth gate");
|
|
// The stealth classifier folds case itself, so case-variant login paths are
|
|
// intercepted upstream when stealth is active regardless of this gate.
|
|
const fnStart = indexSource.indexOf("function isStealthProtectedLoginPath");
|
|
assert.ok(fnStart >= 0, "isStealthProtectedLoginPath not found");
|
|
const fnEnd = indexSource.indexOf("\n}", fnStart);
|
|
const fnBody = indexSource.slice(fnStart, fnEnd);
|
|
assert.match(fnBody, /toLowerCase\(\)/,
|
|
"the stealth login-path classifier must fold case");
|
|
});
|
|
|
|
test("the /api/me equivalence: an exempt case variant is served by the route's own 401 shape", () => {
|
|
// The gate exempts /API/ME the same as /api/me, so the request reaches
|
|
// app.get("/api/me"), which answers unauthenticated callers with
|
|
// 401 {ok:false, user:null} — the endpoint's canonical response. That is
|
|
// the same status and not-authenticated semantics as the gate's API-format
|
|
// 401 ({error:"not authenticated"}), which /API/ME used to receive instead;
|
|
// the route's own shape is the desired one (mirror routing, as documented
|
|
// on the gate's /api/ discrimination).
|
|
const routeStart = indexSource.indexOf("app.get(\"/api/me\"");
|
|
assert.ok(routeStart >= 0, "app.get(\"/api/me\") not found");
|
|
const routeEnd = indexSource.indexOf("app.post(\"/api/me/preferences\"", routeStart);
|
|
assert.ok(routeEnd > routeStart, "/api/me route end not found");
|
|
const routeBody = indexSource.slice(routeStart, routeEnd);
|
|
assert.match(routeBody, /res\.status\(401\)\.json\(\{ ok: false, user: null \}\)/,
|
|
"unauthenticated /api/me must keep its 401 {ok:false, user:null} response");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// Behavioral replication against the real express install: route dispatch
|
|
// folds case; file resolution does not
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("behavioral: express serves route case variants but express.static resolves files case-sensitively", async () => {
|
|
const express = require("express");
|
|
const fixtureRoot = fs.mkdtempSync(path.join(os.tmpdir(), "adpanel-casefold-"));
|
|
const imagesDir = path.join(fixtureRoot, "images");
|
|
fs.mkdirSync(imagesDir);
|
|
fs.writeFileSync(path.join(imagesDir, "real.png"), "PNGDATA");
|
|
|
|
const app = express();
|
|
let routeHits = 0;
|
|
app.get("/healthz", (req, res) => { routeHits += 1; res.json({ served: "healthz", reqPath: req.path }); });
|
|
app.get("/api/me", (req, res) => res.status(401).json({ ok: false, user: null }));
|
|
// Toy mount: mounted WITH a path prefix the prefix itself folds (it is a
|
|
// route mount); the FILENAME lookup below is what stays case-sensitive.
|
|
app.use("/images", express.static(imagesDir));
|
|
|
|
const server = app.listen(0, "127.0.0.1");
|
|
await new Promise((resolve) => server.once("listening", resolve));
|
|
try {
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
|
|
// Route dispatch is case-insensitive (the fact the fold mirrors), and
|
|
// req.path keeps the requested spelling (why the gate must fold itself).
|
|
for (const p of ["/healthz", "/HEALTHZ", "/Healthz"]) {
|
|
const res = await fetch(base + p);
|
|
assert.equal(res.status, 200, `${p} must reach the /healthz route`);
|
|
const body = await res.json();
|
|
assert.equal(body.served, "healthz");
|
|
assert.equal(body.reqPath, p, "req.path must preserve the requested spelling");
|
|
}
|
|
assert.equal(routeHits, 3);
|
|
|
|
// Exact-case file serves; the case-variant FILENAME 404s (the filesystem
|
|
// is case-sensitive). In the real app the static prefixes additionally
|
|
// pass a case-SENSITIVE wrapper check before express.static is reached.
|
|
const exact = await fetch(`${base}/images/real.png`);
|
|
assert.equal(exact.status, 200, "exact-case static file must serve");
|
|
const foldedFile = await fetch(`${base}/images/REAL.PNG`);
|
|
assert.equal(foldedFile.status, 404, "case-variant static FILENAME must 404");
|
|
|
|
// The /api/me route answers its case variant with its own 401 shape.
|
|
const me = await fetch(`${base}/API/ME`);
|
|
assert.equal(me.status, 401);
|
|
assert.deepEqual(await me.json(), { ok: false, user: null });
|
|
} finally {
|
|
server.close();
|
|
fs.rmSync(fixtureRoot, { recursive: true, force: true });
|
|
}
|
|
});
|
|
|
|
test("behavioral: express strict:false serves exactly ONE optional trailing slash (the parity the === legs mirror)", async () => {
|
|
// The finding this fix pins: express mounts routes strict:false, so the
|
|
// one-slash spellings of the exact entries are router-served (they must
|
|
// be gate-exempt) while the two-slash spellings are not (they must stay
|
|
// gate-blocked). Verified against the installed express.
|
|
const express = require("express");
|
|
const app = express();
|
|
app.get("/favicon.ico", (req, res) => res.json({ served: "favicon" }));
|
|
app.get("/healthz", (req, res) => res.json({ served: "healthz" }));
|
|
app.get("/healtz", (req, res) => res.json({ served: "healtz" }));
|
|
app.get("/api/me", (req, res) => res.status(401).json({ ok: false, user: null }));
|
|
app.get("/api/maintenance/status", (req, res) => res.json({ served: "maintenance" }));
|
|
app.use((req, res) => res.status(404).json({ notFound: req.path }));
|
|
|
|
const server = app.listen(0, "127.0.0.1");
|
|
await new Promise((resolve) => server.once("listening", resolve));
|
|
try {
|
|
const base = `http://127.0.0.1:${server.address().port}`;
|
|
|
|
// Exactly ONE trailing slash is optional: these spellings reach the
|
|
// same handlers their bare spellings reach.
|
|
for (const p of ["/favicon.ico/", "/healthz/", "/healtz/", "/api/maintenance/status/"]) {
|
|
const res = await fetch(base + p);
|
|
assert.equal(res.status, 200, `${p} must be router-served (strict:false) — hence gate-exempt`);
|
|
}
|
|
const me = await fetch(`${base}/api/me/`);
|
|
assert.equal(me.status, 401, "/api/me/ must reach the route's own 401 — hence gate-exempt");
|
|
|
|
// Two slashes are NOT optional: the router does not serve these, and
|
|
// the gate must not exempt them either (strip exactly one slash, not
|
|
// all of them).
|
|
for (const p of ["/favicon.ico//", "/healthz//", "/healtz//", "/api/me//", "/api/maintenance/status//"]) {
|
|
const res = await fetch(base + p);
|
|
assert.equal(res.status, 404, `${p} must 404 (the gate must NOT exempt it)`);
|
|
}
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|