"use strict"; // Structure pins for the backups-list read brake (adpanel:backups-list-brake). // // index.js and nodes.js are application bundles (module side effects, DB and // network at require time — never require() them from a test), so these tests // pin the fix structurally on well-anchored source windows, matching the // convention of tests/scheduler-redis-decouple.test.js (whose read-brake pin // this brake deliberately mirrors) and tests/node-relay-backups-action-token.test.js. // // The regression each pin exists to prevent: // 1. GET /api/nodes/server/:name/backups losing its rate brake again — every // list dial holds a 15s node budget and triggers the daemon's orphan // sweep, and the global throttles are no-ops on the shipped default // (security.rate_limiting is false in security.json), so an unbraked // route lets any backups_view holder stream unbounded panel→node dials; // 2. the brake degrading to conditional or shared: it must stay ALWAYS-ON // (no skip), per-account keyed, with its own "node-backups-list:" store // instance — two limiters sharing a prefix share one budget; // 3. the injection dropping out of setUploadPolicyHooks on either side — // the nodes.js gate must keep failing CLOSED (429, never unbraked) and // the mutating siblings must keep their existing nodeUploadRateLimiterGate // mounts untouched. 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 INDEX_SRC = fs.readFileSync(path.join(ROOT, "index.js"), "utf8"); const NODES_SRC = fs.readFileSync(path.join(ROOT, "nodes.js"), "utf8"); function functionWindow(src, anchor, label) { const start = src.indexOf(anchor); assert.notStrictEqual(start, -1, `${label}: anchor not found: ${anchor}`); const end = src.indexOf("\n}", start); assert.notStrictEqual(end, -1, `${label}: no closing brace after: ${anchor}`); return src.slice(start, end + 2); } // ─── 1. The limiter in index.js ────────────────────────────────────────────── test("nodeBackupsListRateLimiter exists exactly once, with its own store instance and prefix", () => { const declCount = INDEX_SRC.split("const nodeBackupsListRateLimiter = rateLimit({").length - 1; assert.strictEqual(declCount, 1, "the limiter must be defined exactly once (injected, not forked)"); const decl = functionWindow(INDEX_SRC, "const nodeBackupsListRateLimiter = rateLimit({", "nodeBackupsListRateLimiter"); assert.ok( decl.includes('store: redisClient ? buildSharedRateLimitRedisStore("node-backups-list:", 10 * 60 * 1000) : undefined'), "the brake must use its own \"node-backups-list:\" prefix (one store instance + distinct prefix per limiter; each buildSharedRateLimitRedisStore call constructs a NEW store)" ); assert.ok( decl.includes("windowMs: 10 * 60 * 1000,") && decl.includes("max: 120,"), "the brake's strictness is part of the contract (120/10min, mirroring the scheduler read brake) — a wiring-correct limiter with a dropped ceiling is not the reviewed brake" ); assert.ok(decl.includes("passOnStoreError: true"), "the brake must fail open on store errors — abuse brake, not an auth control"); }); test("nodeBackupsListRateLimiter is ALWAYS-ON and account-keyed (scheduler read brake semantics)", () => { const decl = functionWindow(INDEX_SRC, "const nodeBackupsListRateLimiter = rateLimit({", "nodeBackupsListRateLimiter"); // The audit's point: the global throttles are no-ops on the shipped default // (security.rate_limiting is false in security.json), so a brake gated on // that flag would be a no-op too. The scheduler read brake is unconditional; // this one must be too. assert.ok(!decl.includes("skip: (req)"), "the brake must NOT skip sessionless requests — an anonymous flood must not hit no brake at all"); assert.ok(!decl.includes("security.rate_limiting"), "the brake must not consult security.rate_limiting — the global flag is false in shipped config"); assert.ok( decl.includes('return email ? `node-backups-list:${email}` : `node-backups-list:ip:${ipKeyGenerator(String(req.ip || "unknown"))}`;'), "authenticated traffic keys per ACCOUNT email; sessionless traffic shares a per-IP bucket via ipKeyGenerator (fs-read / scheduler-read doctrine)" ); assert.ok( decl.includes('res.status(429).json({ error: "Too many backups list requests, slow down." })'), "the limiter's 429 shape must match the gate's missing-hook fallback so clients see one shape" ); }); test("the limiter is defined before the setUploadPolicyHooks injection consumes it", () => { const limiterAt = INDEX_SRC.indexOf("const nodeBackupsListRateLimiter = rateLimit({"); const injectAt = INDEX_SRC.indexOf("backupsListRateLimiter: nodeBackupsListRateLimiter,"); assert.notStrictEqual(injectAt, -1, "index.js must pass the limiter through setUploadPolicyHooks"); assert.ok(limiterAt !== -1 && limiterAt < injectAt, "the limiter must be defined before the injection site executes at module load"); }); // ─── 2. The mount + injection in nodes.js ──────────────────────────────────── test("GET /api/nodes/server/:name/backups mounts the brake after rejectCrossSiteRead, before the handler", () => { assert.ok( NODES_SRC.includes('app.get("/api/nodes/server/:name/backups", rejectCrossSiteRead, nodeBackupsListRateLimiterGate, async (req, res) => {'), "the list route must mount rejectCrossSiteRead + nodeBackupsListRateLimiterGate as route middleware, exactly like schedulerTasksReadRateLimiter on the scheduler tasks GET" ); const mounts = NODES_SRC.split("\n").filter((line) => /app\.(?:get|post|put|delete)\(.*nodeBackupsListRateLimiterGate/.test(line)); assert.strictEqual(mounts.length, 1, "the brake must mount on the GET list route ONLY — the mutating siblings keep their own nodeUploadRateLimiterGate budgets"); }); test("the nodes.js gate resolves the injected limiter and fails CLOSED with the limiter's 429 shape", () => { const gate = functionWindow(NODES_SRC, "function nodeBackupsListRateLimiterGate(req, res, next) {", "nodeBackupsListRateLimiterGate"); assert.ok(gate.includes("const limiter = _backupsListRateLimiter;"), "the gate must resolve the injected limiter per-request"); assert.ok( gate.includes('return res.status(429).json({ error: "Too many backups list requests, slow down." });'), "without the hook the gate must reject with the limiter's own 429 shape — no hook ever leaves the list route unbraked" ); assert.ok(gate.includes("return limiter(req, res, next);"), "the gate must delegate to the injected limiter when present"); const setter = functionWindow(NODES_SRC, "function setUploadPolicyHooks(hooks = {}) {", "setUploadPolicyHooks"); assert.ok( setter.includes('_backupsListRateLimiter = typeof hooks.backupsListRateLimiter === "function" ? hooks.backupsListRateLimiter : null;'), "setUploadPolicyHooks must parse the backupsListRateLimiter hook (a non-function injection degrades to fail-closed null)" ); }); test("the three mutating backups relays keep their existing nodeUploadRateLimiterGate mounts", () => { for (const marker of [ 'app.post("/api/nodes/server/:name/backups", nodeUploadRateLimiterGate,', 'app.post("/api/nodes/server/:name/backups/:backupId/restore", nodeUploadRateLimiterGate,', 'app.delete("/api/nodes/server/:name/backups/:backupId", nodeUploadRateLimiterGate,', ]) { assert.ok(NODES_SRC.includes(marker), `mutating relay must keep its own gate: ${marker}`); } }); // ─── 3. Prefix distinctness ────────────────────────────────────────────────── test("the node-backups-list prefix stays distinct fleet-wide", () => { // Two limiters sharing a prefix share one budget; the same pin guards // index.js in tests/scheduler-redis-decouple.test.js — repeated here so // this file's failure message names the brake that drifted. const prefixes = [...INDEX_SRC.matchAll(/buildSharedRateLimitRedisStore\("([^"]+)"/g)].map((m) => m[1]); assert.strictEqual(new Set(prefixes).size, prefixes.length, "rate-limit store prefixes must stay distinct fleet-wide"); assert.ok(prefixes.includes("node-backups-list:"), "the backups list brake's prefix must be present in the store-prefix set"); });