Files
Kelx/tests/relay-perms-before-suspension.test.js
T
2026-11-30 16:32:37 +00:00

146 lines
8.9 KiB
JavaScript

"use strict";
// adpanel:fs-perms-before-suspension — source-level pins for the nodes.js
// relay fs routes' guard ORDER: authorization (403) before state (423), the
// same policy the panel's own fs routes implement and document in index.js.
// A caller without the fine-grained perm must not learn the server's
// suspension state, so every relay fs route answers the perm denial before
// the suspension body (the pre-2026-10 relay order was the exact inverse).
//
// No behavioral test can reach these pre-flight blocks (nodes.js boots its
// express app on require), so — same technique as
// tests/legacy-fs-refusal-pins.test.js — each route body is sliced between
// stable route-string anchors, full-line comments are stripped (prose must
// never satisfy the assertions), and the perm-check call is asserted to
// appear textually BEFORE the suspension call. A sweep test additionally
// asserts that the set of routes carrying both an fs perm gate and a
// suspension gate is EXACTLY the flipped list below, so the flipped set can
// neither silently shrink (a route reverting to suspension-first) nor grow
// (a new relay fs route reviving the old order).
const test = require("node:test");
const assert = require("node:assert");
const fs = require("node:fs");
const path = require("node:path");
const ROOT = path.join(__dirname, "..");
const NODES_JS = path.join(ROOT, "nodes.js");
// Strip full-line comments so prose mentioning the guarded calls cannot
// satisfy the assertions (e.g. extract's "admins pass checkUserPerm too").
function stripFullLineComments(src) {
return src
.split("\n")
.filter((line) => !/^\s*\/\//.test(line))
.join("\n");
}
const rawSrc = fs.readFileSync(NODES_JS, "utf8");
const nodesSrc = stripFullLineComments(rawSrc);
// One entry per flipped relay fs route, in file order. permCall is the
// fine-grained fs perm gate (checkUserPerm / resolveFsWriteMode); the
// suspensionCall must sit textually AFTER it in the pre-flight block.
const FLIPPED_ROUTES = [
{ method: "GET", route: "/api/nodes/server/:name/entries", permCall: 'checkUserPerm(req, serverName, "files_read")', suspensionCall: "rejectIfServerSuspended(res, serverName)" },
{ method: "GET", route: "/api/nodes/server/:name/file", permCall: 'checkUserPerm(req, serverName, "files_read")', suspensionCall: "rejectIfServerSuspended(res, serverName)" },
{ method: "GET", route: "/api/nodes/server/:name/download", permCall: 'checkUserPerm(req, serverName, "files_read")', suspensionCall: "rejectIfServerSuspended(res, serverName)" },
{ method: "POST", route: "/api/nodes/server/:name/file", permCall: "resolveFsWriteMode(req, serverName)", suspensionCall: "rejectIfServerSuspended(res, serverName)" },
{ method: "POST", route: "/api/nodes/server/:name/delete", permCall: 'checkUserPerm(req, req.params.name, "files_delete")', suspensionCall: "isServerSuspended(ctx.server)" },
{ method: "POST", route: "/api/nodes/server/:name/delete-batch", permCall: 'checkUserPerm(req, req.params.name, "files_delete")', suspensionCall: "isServerSuspended(ctx.server)" },
{ method: "POST", route: "/api/nodes/server/:name/rename", permCall: 'checkUserPerm(req, req.params.name, "files_rename")', suspensionCall: "isServerSuspended(ctx.server)" },
// extract keeps its canOverwrite files_write lookup together with the
// files_create perm check — both before the suspension gate.
{ method: "POST", route: "/api/nodes/server/:name/extract", permCall: 'checkUserPerm(req, req.params.name, "files_create")', suspensionCall: "isServerSuspended(ctx.server)", alsoBeforeSuspension: 'canOverwrite = await checkUserPerm(req, req.params.name, "files_write")' },
{ method: "POST", route: "/api/nodes/server/:name/archive", permCall: 'checkUserPerm(req, req.params.name, "files_archive")', suspensionCall: "isServerSuspended(ctx.server)" },
{ method: "POST", route: "/api/nodes/server/:name/upload", permCall: 'checkUserPerm(req, req.params.name, "files_upload")', suspensionCall: "isServerSuspended(ctx.server)" },
{ method: "POST", route: "/api/nodes/server/:name/upload-url", permCall: 'checkUserPerm(req, req.params.name, "files_upload")', suspensionCall: "isServerSuspended(ctx.server)" },
{ method: "POST", route: "/api/nodes/server/:name/create", permCall: 'checkUserPerm(req, req.params.name, "files_create")', suspensionCall: "isServerSuspended(ctx.server)" },
];
function anchorFor(entry) {
return `app.${entry.method.toLowerCase()}("${entry.route}"`;
}
// A route body ends at the next top-level registration OR declaration:
// nodes.js keeps helper functions (performPanel*, relayPanelResult) between
// route registrations, and a helper's own guard order must never be pulled
// into a route's window where it could satisfy or contaminate its assertion.
function routeWindow(start, label) {
assert.notStrictEqual(start, -1, `${label}: route anchor not found`);
const endRe = /^(?:app\.(?:get|post|put|delete|patch|all|use)\s*\(|(?:async\s+)?function\s[A-Za-z_$]|(?:const|let|var)\s[A-Za-z_$]|module\.exports)/gm;
endRe.lastIndex = start + 1;
let end = nodesSrc.length;
let m;
while ((m = endRe.exec(nodesSrc)) !== null) { end = m.index; break; }
return nodesSrc.slice(start, end);
}
for (const entry of FLIPPED_ROUTES) {
test(`relay fs route answers perm denial (403) before suspension (423): ${entry.method} ${entry.route}`, () => {
const start = nodesSrc.indexOf(anchorFor(entry));
const body = routeWindow(start, `${entry.method} ${entry.route}`);
const permAt = body.indexOf(entry.permCall);
const suspensionAt = body.indexOf(entry.suspensionCall);
assert.ok(permAt !== -1, `the fs perm gate (${entry.permCall}) must stay in the pre-flight`);
assert.ok(suspensionAt !== -1, `the suspension gate (${entry.suspensionCall}) must stay in the pre-flight`);
assert.ok(
permAt < suspensionAt,
`${entry.method} ${entry.route}: the perm check must run BEFORE the suspension body (adpanel:fs-perms-before-suspension — a caller without the fine-grained perm must not learn the server's suspension state)`
);
if (entry.alsoBeforeSuspension) {
const extraAt = body.indexOf(entry.alsoBeforeSuspension);
assert.ok(extraAt !== -1 && extraAt < suspensionAt, "the canOverwrite files_write lookup must stay together with the perm check, before the suspension gate");
}
});
}
test("exactly the flipped set: every nodes.js route carrying an fs perm gate AND a suspension gate orders perm before suspension", () => {
const FS_PERM_MARKERS = [
"files_read", "files_create", "files_write", "files_delete",
"files_rename", "files_archive", "files_upload",
"resolveFsWriteMode(req",
];
const SUSPENSION_MARKERS = ["rejectIfServerSuspended(res", "isServerSuspended(ctx.server)"];
const starts = [];
const re = /^app\.(?:get|post|put|delete|patch|all|use)\s*\(/gm;
let m;
while ((m = re.exec(nodesSrc)) !== null) starts.push(m.index);
const detected = [];
for (const start of starts) {
const body = routeWindow(start, "route window");
const hasFsPerm = FS_PERM_MARKERS.some((s) => body.includes(s));
const hasSuspension = SUSPENSION_MARKERS.some((s) => body.includes(s));
if (!hasFsPerm || !hasSuspension) continue;
const sig = body.match(/^app\.(get|post|put|delete|patch|all)\s*\(\s*"([^"]+)"/);
assert.ok(sig, "expected to read the method and path off the route registration");
const permAt = Math.min(...FS_PERM_MARKERS.map((s) => body.indexOf(s)).filter((i) => i !== -1));
const suspensionAt = Math.min(...SUSPENSION_MARKERS.map((s) => body.indexOf(s)).filter((i) => i !== -1));
assert.ok(
permAt < suspensionAt,
`${sig[1].toUpperCase()} ${sig[2]}: an fs perm gate and a suspension gate in one pre-flight must answer the perm denial first (adpanel:fs-perms-before-suspension)`
);
detected.push(`${sig[1].toUpperCase()} ${sig[2]}`);
}
const expected = FLIPPED_ROUTES.map((e) => `${e.method} ${e.route}`);
assert.deepStrictEqual(
detected.sort(),
expected.sort(),
"the set of routes carrying an fs perm gate plus a suspension gate must be exactly the flipped relay fs routes — a drift in either direction regresses the policy"
);
});
test("the adpanel:fs-perms-before-suspension comment exists in nodes.js, documented once in the entries relay (the first flipped route)", () => {
const marker = "adpanel:fs-perms-before-suspension";
const at = rawSrc.indexOf(marker);
assert.notStrictEqual(at, -1, "the policy comment must exist in nodes.js");
assert.strictEqual(rawSrc.indexOf(marker, at + 1), -1, "the comment is documented once — in the entries relay — not re-pasted per route");
const entriesAnchor = rawSrc.indexOf('app.get("/api/nodes/server/:name/entries"');
const nextRouteAnchor = rawSrc.indexOf('app.get("/api/nodes/server/:name/file"', entriesAnchor);
assert.ok(entriesAnchor !== -1 && nextRouteAnchor !== -1, "expected the entries and file GET route anchors");
assert.ok(at > entriesAnchor && at < nextRouteAnchor, "the comment must sit inside the entries relay body (the first flipped route)");
});