Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+479
View File
@@ -0,0 +1,479 @@
"use strict";
// Regression tests for the case-variant /api/nodes admin-gate bypass.
//
// All three gate layers (the index.js pre-mount admin gate, the index.js
// static-asset fast path, and the nodes.js in-app gate) classified request
// paths with CASE-SENSITIVE prefix/regex matches, while Express dispatches
// routes CASE-INSENSITIVELY by default (no "case sensitive routing" setting
// is enabled in either app). An authenticated non-admin could therefore
// request /API/NODES or /Api/Nodes/... — the gates saw an unknown prefix and
// waved the request through, and the router served the real /api/nodes
// handlers: fleet enumeration (GET /api/nodes, /:id), forced health checks
// (POST /:id/check), the port-probe oracle (GET /:id/ports/check), build
// config reads (GET /:id/build) and server creation with attacker-chosen
// host ports (POST /:id/servers/create).
//
// The fix classifies through utils/node-api-path.js (lowercased prefix
// match) at both gate layers and gives the six previously gate-only nodes.js
// handlers their own requireNodeAdmin() check. These tests pin:
// - case variants of /api/nodes are admin-gated again (the regression)
// - the /api/nodes/server/ exemption still works, for lowercase AND case
// variants (per-server access is enforced inside those handlers)
// - the pre-auth OPEN-route allowlists stay case-sensitive: a case-variant
// heartbeat/config.yml/installer request fails closed into the admin
// gate instead of widening pre-auth reach
// - the static-asset fast path never flags case-variant /api/ paths, so
// they cannot skip the session/isAdmin middlewares
// - the suspicious-path block fires on case variants of the patterns too
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const ROOT = path.join(__dirname, "..");
const INDEX_JS = path.join(ROOT, "index.js");
const NODES_JS = path.join(ROOT, "nodes.js");
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
const nodesSource = fs.readFileSync(NODES_JS, "utf8");
const { isNodeApiPath, isNodeServerApiPath } = require("../utils/node-api-path");
// Locate the enclosing `app.use(` middleware for an inner marker and slice
// the brace-balanced block plus its trailing `);`. The blocks under test
// contain 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);
}
function extractLine(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker not found: ${startMarker}`);
const end = source.indexOf(";\n", start);
assert.ok(end > start, `line end not found after: ${startMarker}`);
return source.slice(start, end + 1);
}
function makeRes() {
return {
statusCode: 0,
body: null,
status(c) { this.statusCode = c; return this; },
json(b) { this.body = b; return this; },
send(b) { this.body = b; return this; }
};
}
function runGate(middleware, req) {
const res = makeRes();
let nexted = false;
let nextArg = undefined;
return Promise.resolve(middleware(req, res, (arg) => { nexted = true; nextArg = arg; }))
.then(() => ({ res, nexted, nextArg }));
}
// ---------------------------------------------------------------------------
// utils/node-api-path.js classification
// ---------------------------------------------------------------------------
test("node api path helpers: exact namespace matches, case-insensitively", () => {
for (const p of ["/api/nodes", "/API/NODES", "/Api/Nodes", "/aPi/nOdEs",
"/api/nodes/", "/API/NODES/abc", "/API/NODES/server/x/info",
"/api/nodes/abc/build", "/api/nodes-server"]) {
assert.equal(isNodeApiPath(p), true, `isNodeApiPath(${p})`);
}
for (const p of ["", null, undefined, "/api/node", "/xapi/nodes", "/api/nodesx".replace("nodesx", "node"),
"/API", "/nodes", "/api/NODE", 12345]) {
assert.equal(isNodeApiPath(p), false, `isNodeApiPath(${String(p)}) must not match`);
}
for (const p of ["/api/nodes/server/", "/API/NODES/SERVER/x", "/Api/Nodes/Server/y/info"]) {
assert.equal(isNodeServerApiPath(p), true, `isNodeServerApiPath(${p})`);
}
for (const p of ["/api/nodes/abc", "/api/servers/x", "", null, undefined]) {
assert.equal(isNodeServerApiPath(p), false, `isNodeServerApiPath(${String(p)}) must not match`);
}
});
// ---------------------------------------------------------------------------
// index.js: the /api/nodes admin gate (pre nodesRouter mount)
// ---------------------------------------------------------------------------
const INDEX_GATE_MARKER = "// Classification must match Express's case-insensitive dispatch:";
function loadIndexGate() {
const block = extractMiddleware(indexSource, INDEX_GATE_MARKER);
let captured = null;
const sandbox = {
app: { use: (mw) => { captured = mw; } },
isOpenNodeRoute: async (req) => req._openRoute === true,
isAdmin: async (req) => req._admin === true,
isNodeApiPath,
isNodeServerApiPath
};
vm.createContext(sandbox);
vm.runInContext(block, sandbox);
assert.ok(captured, "index.js gate middleware was not registered");
return captured;
}
test("index.js node gate: case variants of /api/nodes require admin", async () => {
const gate = loadIndexGate();
for (const p of ["/api/nodes", "/API/NODES", "/Api/Nodes", "/API/NODES/abc",
"/API/NODES/abc/ports/check", "/aPi/nOdEs/x/build"]) {
const out = await runGate(gate, { path: p, method: "GET" });
assert.equal(out.nexted, false, `${p} must not pass the gate for a non-admin`);
assert.equal(out.res.statusCode, 403, `${p} must be 403 for a non-admin`);
}
for (const p of ["/api/nodes", "/API/NODES", "/API/NODES/abc/servers/create"]) {
const out = await runGate(gate, { path: p, method: "POST", _admin: true });
assert.equal(out.nexted, true, `${p} must pass the gate for an admin`);
assert.equal(out.res.statusCode, 0, `${p} must not be rejected for an admin`);
}
});
test("index.js node gate: server-route exemption works for case variants, open routes still bypass", async () => {
const gate = loadIndexGate();
for (const p of ["/api/nodes/server/foo/info", "/API/NODES/SERVER/foo/info",
"/Api/Nodes/Server/bar/file"]) {
const out = await runGate(gate, { path: p, method: "GET", _admin: false });
assert.equal(out.nexted, true, `${p} must be exempt from the admin requirement`);
}
const open = await runGate(gate, { path: "/api/nodes/x/heartbeat", method: "POST", _openRoute: true });
assert.equal(open.nexted, true, "open node routes (heartbeat) must still bypass the admin gate");
const openCfg = await runGate(gate, { path: "/api/nodes/x/config.yml", method: "GET", _openRoute: true });
assert.equal(openCfg.nexted, true, "open node routes (config.yml) must still bypass the admin gate");
const other = await runGate(gate, { path: "/api/servers/foo", method: "GET" });
assert.equal(other.nexted, true, "non-node paths must pass through untouched");
});
test("index.js node gate: gate errors fall closed through next(err)", async () => {
const block = extractMiddleware(indexSource, INDEX_GATE_MARKER);
let captured = null;
const sandbox = {
app: { use: (mw) => { captured = mw; } },
isOpenNodeRoute: async () => { throw new Error("boom"); },
isAdmin: async () => true,
isNodeApiPath,
isNodeServerApiPath
};
vm.createContext(sandbox);
vm.runInContext(block, sandbox);
const out = await runGate(captured, { path: "/api/nodes", method: "GET" });
assert.equal(out.nexted, true, "errors must be forwarded via next(err)");
assert.equal(out.nextArg && out.nextArg.message, "boom");
});
// ---------------------------------------------------------------------------
// nodes.js: the in-app gate
// ---------------------------------------------------------------------------
function loadNodesGate() {
const patternLine = extractLine(nodesSource, "const NODES_SERVER_ROUTES_PATTERN = ");
const block = extractMiddleware(nodesSource, 'if (path === "/health") return next();');
let captured = null;
const sandbox = {
app: { use: (mw) => { captured = mw; } },
NODES_SERVER_ROUTES_PATTERN: undefined,
isNodeApiPath
};
vm.createContext(sandbox);
vm.runInContext(patternLine, sandbox);
sandbox.NODES_SERVER_ROUTES_PATTERN = vm.runInContext("NODES_SERVER_ROUTES_PATTERN", sandbox);
vm.runInContext(block, sandbox);
assert.ok(captured, "nodes.js gate middleware was not registered");
return captured;
}
test("nodes.js gate: case variants of /api/nodes require req.isAdmin", async () => {
const gate = loadNodesGate();
for (const p of ["/api/nodes", "/API/NODES", "/Api/Nodes/abc", "/API/NODES/abc/servers/create",
"/API/NODES/abc/build"]) {
const out = await runGate(gate, { path: p, method: "GET", isAdmin: false });
assert.equal(out.nexted, false, `${p} must not pass the nodes.js gate without isAdmin`);
assert.equal(out.res.statusCode, 403, `${p} must be 403 without isAdmin`);
assert.equal(out.res.body && out.res.body.error, "admin required");
}
for (const p of ["/api/nodes", "/API/NODES/abc"]) {
const out = await runGate(gate, { path: p, method: "GET", isAdmin: true });
assert.equal(out.nexted, true, `${p} must pass the nodes.js gate with isAdmin`);
}
});
test("nodes.js gate: server-route exemption case-insensitive; health and heartbeat unaffected", async () => {
const gate = loadNodesGate();
for (const p of ["/api/nodes/server/foo/info", "/API/NODES/SERVER/foo/info",
"/Api/Nodes/Server/bar/backups", "/API/NODES/SERVER/baz/backups/b1/restore"]) {
const out = await runGate(gate, { path: p, method: "GET", isAdmin: false });
assert.equal(out.nexted, true, `${p} must be exempt (per-server access enforced in the handler)`);
}
const health = await runGate(gate, { path: "/health", method: "GET", isAdmin: false });
assert.equal(health.nexted, true, "/health stays public");
const beat = await runGate(gate, { path: "/api/nodes/x/heartbeat", method: "POST", isAdmin: false });
assert.equal(beat.nexted, true, "lowercase heartbeat stays open (token checked in the panel gate)");
// The heartbeat allowlist is deliberately case-sensitive (it grants
// pre-auth reachability): a case variant must fail closed into the admin
// requirement, not widen the pre-auth surface.
const beatCase = await runGate(gate, { path: "/API/NODES/x/heartbeat", method: "POST", isAdmin: false });
assert.equal(beatCase.nexted, false, "case-variant heartbeat must fail closed into the admin gate");
assert.equal(beatCase.res.statusCode, 403);
});
// ---------------------------------------------------------------------------
// index.js: static-asset fast path must never flag case-variant /api/ paths
// ---------------------------------------------------------------------------
function loadStaticClassifier() {
const block = extractMiddleware(indexSource, "req._staticAsset = true;");
let captured = null;
const sandbox = { app: { use: (mw) => { captured = mw; } } };
vm.createContext(sandbox);
vm.runInContext(block, sandbox);
assert.ok(captured, "static classifier middleware was not registered");
return captured;
}
test("static fast path: API paths (any case) are never flagged as static assets", () => {
const classify = loadStaticClassifier();
const flagged = (p) => {
const req = { path: p };
classify(req, {}, () => {});
return req._staticAsset === true;
};
assert.equal(flagged("/js/app.js"), true, "lowercase statics stay flagged");
assert.equal(flagged("/css/x.css"), true);
assert.equal(flagged("/favicon.ico"), true);
assert.equal(flagged("/api/nodes"), false, "API paths are excluded");
assert.equal(flagged("/api/nodes/foo.png"), false, "extension-bearing API paths stay excluded");
assert.equal(flagged("/API/nodes/foo.png"), false, "case-variant API paths must not take the static fast path");
assert.equal(flagged("/API/NODES"), false, "case-variant API paths must not take the static fast path");
// /CSS/x.css stays flagged through the lowercased prefix check (the /api/
// exclusion is the only case-insensitive EXCLUSION; the static prefixes are
// matched lowercased too, so case-variant static directories stay fast).
assert.equal(flagged("/CSS/x.css"), true, "non-API extension flagging is unchanged");
// Phase 7 (finding #8): extension matching no longer applies deeper in the
// tree. Server names may contain dots (utils/server-name.js), so dotted
// paths like /server/<name>.js are DYNAMIC routes — they must take the
// normal middleware path to get a real CSP nonce and the session /
// revoked-sid / suspension gates. Extension flagging is confined to
// single-segment root files, plus /uploads/ image extensions only.
assert.equal(flagged("/server/foo.js"), false, "dotted dynamic server route must not take the static fast path");
assert.equal(flagged("/server/foo.css"), false, "dotted dynamic server route must not take the static fast path");
assert.equal(flagged("/db-open/x.png"), false, "db-open is a dynamic route, not a static prefix");
assert.equal(flagged("/bot/x.js"), false, "nested non-static paths are no longer extension-flagged");
assert.equal(flagged("/uploads/a.pdf"), false, "uploads stay pre-auth only for image extensions");
assert.equal(flagged("/API/x.css"), false, "case-variant API path with a static extension stays excluded");
assert.equal(flagged("/login.css"), true, "single-segment root file stays flagged");
assert.equal(flagged("/vendor/fontawesome/css/all.min.css"), true, "vendor prefix stays flagged");
assert.equal(flagged("/uploads/a.png"), true, "uploads image extensions stay flagged");
});
// ---------------------------------------------------------------------------
// index.js: suspicious-path block fires on case variants too
// ---------------------------------------------------------------------------
test("suspicious path block: case variants of the patterns are blocked", async () => {
const patternLine = extractLine(indexSource, "const SUSPICIOUS_PATH_PATTERNS = ");
const block = extractMiddleware(indexSource, "const pathToCheck = req.path");
let captured = null;
const sandbox = { app: { use: (mw) => { captured = mw; } }, securityLog: () => {} };
vm.createContext(sandbox);
vm.runInContext(patternLine, sandbox);
vm.runInContext(block, sandbox);
assert.ok(captured, "suspicious-path middleware was not registered");
for (const p of ["/etc/passwd", "/Etc/Passwd", "/ETC/PASSWD", "/proc/self/environ",
"/PROC/SELF/environ", "/x/.env", "/x/.ENV"]) {
const res = makeRes();
let nexted = false;
captured({ path: p, method: "GET" }, res, () => { nexted = true; });
assert.equal(nexted, false, `${p} must be blocked`);
assert.equal(res.statusCode, 403, `${p} must be 403`);
}
const clean = makeRes();
let cleanNext = false;
captured({ path: "/api/nodes", method: "GET" }, clean, () => { cleanNext = true; });
assert.equal(cleanNext, true, "normal paths must pass the suspicious-path block");
});
// ---------------------------------------------------------------------------
// nodes.js: the six previously gate-only handlers are self-defending
// ---------------------------------------------------------------------------
test("nodes.js: node fleet handlers enforce requireNodeAdmin themselves", () => {
const handlers = [
["app.get(\"/api/nodes\"", "app.get(\"/api/nodes/:id\""],
["app.get(\"/api/nodes/:id\"", "app.post(\"/api/nodes/:id/check\""],
["app.post(\"/api/nodes/:id/check\"", "app.get(\"/api/nodes/:id/ports/check\""],
["app.get(\"/api/nodes/:id/ports/check\"", "app.get(\"/api/nodes/:id/ports/in-use\""],
["app.get(\"/api/nodes/:id/ports/in-use\"", "async function nodeProxyCreateHandler(req, res)"],
["app.get(\"/api/nodes/:id/build\"", "app.post(\"/api/nodes/:id/build\""]
];
for (const [startMarker, endMarker] of handlers) {
const start = nodesSource.indexOf(startMarker);
assert.ok(start >= 0, `handler not found: ${startMarker}`);
const end = nodesSource.indexOf(endMarker, start);
assert.ok(end > start, `end handler not found after: ${startMarker}`);
const body = nodesSource.slice(start, end);
assert.match(
body,
/if \(!\(await requireNodeAdmin\(req, res\)\)\) return;/,
`${startMarker} must enforce requireNodeAdmin internally`
);
}
// M3: the servers/create handler body lives in nodeProxyCreateHandler
// (registered through a crash-safe try/catch wrapper — Express 4 does not
// catch async throws); the self-defending requireNodeAdmin check must be
// inside the handler itself.
const handlerStart = nodesSource.indexOf("async function nodeProxyCreateHandler(req, res)");
assert.ok(handlerStart >= 0, "nodeProxyCreateHandler not found");
const registrationStart = nodesSource.indexOf('app.post("/api/nodes/:id/servers/create"', handlerStart);
assert.ok(registrationStart > handlerStart, "route registration not found after nodeProxyCreateHandler");
const handlerBody = nodesSource.slice(handlerStart, registrationStart);
assert.match(
handlerBody,
/if \(!\(await requireNodeAdmin\(req, res\)\)\) return;/,
"nodeProxyCreateHandler must enforce requireNodeAdmin internally"
);
assert.match(
nodesSource.slice(registrationStart),
/return await nodeProxyCreateHandler\(req, res\);/,
"the servers/create route must delegate to nodeProxyCreateHandler"
);
});
test("source-level: no case-sensitive /api/nodes prefix gates remain", () => {
assert.doesNotMatch(indexSource, /req\.path\.startsWith\("\/api\/nodes"/,
"index.js must classify through the case-insensitive helper");
assert.doesNotMatch(nodesSource, /path\.startsWith\("\/api\/nodes"/,
"nodes.js must classify through the case-insensitive helper");
assert.match(indexSource, /require\("\.\/utils\/node-api-path"\)/,
"index.js must use utils/node-api-path.js");
assert.match(nodesSource, /require\("\.\/utils\/node-api-path"\)/,
"nodes.js must use utils/node-api-path.js");
});
// ---------------------------------------------------------------------------
// index.js: suspension/installing guard resolvers must catch case variants
// ---------------------------------------------------------------------------
// Locate a top-level `function <name>(...)` declaration and slice its
// brace-balanced body. The guard functions contain no brace-bearing
// string/regex literals (their regex literals only carry `\/` escapes and
// `(\/.*)?$` groups), so naive matching suffices.
function extractFunction(source, startMarker) {
const start = source.indexOf(startMarker);
assert.ok(start >= 0, `marker not found: ${startMarker}`);
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: ${startMarker}`);
return source.slice(start, i);
}
function loadSuspensionGuard() {
const block = extractFunction(indexSource, "function getSuspensionGuardTarget");
const sandbox = { decodeServerPathSegment: (s) => String(s) };
vm.createContext(sandbox);
vm.runInContext(block, sandbox);
return vm.runInContext("getSuspensionGuardTarget", sandbox);
}
function loadInstallingGuard() {
const block = extractFunction(indexSource, "function getInstallingGuardTarget");
const sandbox = { decodeServerPathSegment: (s) => String(s) };
vm.createContext(sandbox);
vm.runInContext(block, sandbox);
return vm.runInContext("getInstallingGuardTarget", sandbox);
}
test("guard resolvers: case-variant paths are guarded exactly like lowercase", () => {
const suspension = loadSuspensionGuard();
const installing = loadInstallingGuard();
// getSuspensionGuardTarget
assert.deepEqual(suspension({ path: "/server/MyBot" }), { name: "MyBot", page: true });
assert.deepEqual(suspension({ path: "/SERVER/MyBot" }), { name: "MyBot", page: true },
"case-variant page path must be guarded identically (the regression)");
assert.deepEqual(suspension({ path: "/api/nodes/server/MyBot/file" }), { name: "MyBot", page: false });
assert.deepEqual(suspension({ path: "/API/NODES/SERVER/MyBot/file" }), { name: "MyBot", page: false });
assert.deepEqual(suspension({ path: "/API/SERVER/MyBot" }), { name: "MyBot", page: false });
assert.equal(suspension({ path: "/api/servers/create" }), null, "create must stay exempt");
assert.equal(suspension({ path: "/API/SERVERS/CREATE" }), null,
"case-variant create must stay exempt (special case preserved)");
assert.equal(suspension({ path: "/api/scheduler/status" }), null, "scheduler status must stay exempt");
// getInstallingGuardTarget
assert.equal(installing({ path: "/api/nodes/server/MyBot/info" }), null, "info must stay exempt");
assert.equal(installing({ path: "/API/NODES/SERVER/MyBot/INFO" }), null,
"case-variant exemption must be preserved");
assert.equal(installing({ path: "/api/nodes/server/MyBot/file" }), "MyBot");
assert.equal(installing({ path: "/API/NODES/SERVER/MyBot/file" }), "MyBot",
"case-variant path must be guarded identically (the regression)");
assert.equal(installing({ path: "/server/MyBot" }), null, "main page render must stay exempt");
assert.equal(installing({ path: "/api/servers/MyBot/permissions" }), null, "permissions must stay exempt");
});
test("Scheduler lifecycle guards scope status as a server name on task routes", () => {
const suspension = loadSuspensionGuard();
const installing = loadInstallingGuard();
for (const path of ["/api/scheduler/status/tasks", "/API/SCHEDULER/Status/TASKS/fixture"] ) {
const target = suspension({ path });
assert.equal(target?.name.toLowerCase(), "status");
assert.equal(target.page, false);
assert.equal(installing({ path })?.toLowerCase(), "status");
}
assert.equal(suspension({ path: "/API/SCHEDULER/STATUS/" }), null);
assert.equal(installing({ path: "/API/SCHEDULER/STATUS/" }), null);
});