"use strict"; // adpanel:rate-limit-policy-owner — behavior + wiring pins for the global /api // rate-limit policy owner (services/global-rate-limit-owner.js). // // Constraint under test: express-rate-limit v8 bakes windowMs at CONSTRUCTION // (only `limit` is per-request hot), and rate-limit-redis seeds every // counter's EXPIRE from the init()ed windowMs — so before this campaign a // runtime security.json window_seconds change reached the in-memory /api // backstop live but the Redis-backed limiter only after a restart (the old // adpanel:rate-limit-window-freeze constraint, deliberately obsolete now). // The fix is a rebuild-on-save OWNER: the limiter for app.use("/api/") is // constructed by services/global-rate-limit-owner.js, and applyPolicy() — // called by POST /api/settings/security after a successful persist and by the // fs.watch merge — rebuilds ONLY when the effective windowMs changed, into a // NEW limiter with a NEW RateLimitRedisStore instance under a generation- // scoped prefix ("rl:g1:", "rl:g2:", ...) so old-generation buckets never // bleed into (nor get reset by) the new policy. // // Locked here: // - owner units against the REAL express-rate-limit + a fake Redis // (in-memory Map sendCommand implementing the store's actual wire // commands): generation-1 enforcement, live `max`, window rebuild into a // new generation with fresh buckets AND the new EXPIRE seed, no-rebuild // idempotence (counters survive), flag flips without rebuild, trusted- // subnet/exempt-path skip via the ONE helper, pass-through when Redis is // absent at boot, and the fail-open sendCommand posture end-to-end; // - save-route wiring via the house vm-extraction technique: applyPolicy() // runs after a successful persist and before the response; a failed save // (safeWriteJson throws / step-up refused) leaves the previous effective // policy enforcing; every fallible await of POST /api/settings/security // sits inside the containment guard (a rejected gate answers the bounded // 500 instead of hanging the client); // - the fs.watch merge re-applies the policy for hand-edited files, and the // obsolete window-freeze comment is gone (the code no longer freezes). 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 express = require("express"); const { rateLimit } = require("express-rate-limit"); const { RedisStore: RateLimitRedisStore } = require("rate-limit-redis"); const ROOT = path.join(__dirname, ".."); const INDEX_JS = path.join(ROOT, "index.js"); const OWNER_JS = path.join(ROOT, "services", "global-rate-limit-owner.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const ownerSource = fs.readFileSync(OWNER_JS, "utf8"); const { createGlobalRateLimitOwner } = require(OWNER_JS); // --------------------------------------------------------------------------- // Fake Redis: implements the exact wire commands rate-limit-redis 4.3.1 // issues through sendCommand — ["SCRIPT","LOAD",script] and // ["EVALSHA",sha,"1",key,resetFlag,windowMs] (increment) / ["EVALSHA",sha, // "1",key] (get) — with the increment script's real semantics (fresh key → // {1, windowMs}; existing → {hits, timeToExpire}). // --------------------------------------------------------------------------- function createFakeRedis() { const data = new Map(); // key -> { hits, exp } let shaCounter = 0; const loadedShas = new Map(); const commands = []; const sendCommand = async (...args) => { commands.push(args); const cmd = args[0]; if (cmd === "SCRIPT") { const script = args[2]; let sha = loadedShas.get(script); if (!sha) { sha = `sha${++shaCounter}`; loadedShas.set(script, sha); } return sha; } if (cmd === "EVALSHA") { if (args.length >= 6) { // increment: EVALSHA const key = args[3]; const resetOnChange = args[4] === "1"; const windowMs = parseInt(args[5], 10); const now = Date.now(); const entry = data.get(key); if (!entry || entry.exp <= now) { data.set(key, { hits: 1, exp: now + windowMs }); return [1, windowMs]; } entry.hits += 1; if (resetOnChange) { entry.exp = now + windowMs; return [entry.hits, windowMs]; } return [entry.hits, entry.exp - now]; } // get: EVALSHA const key = args[3]; const entry = data.get(key); if (!entry || entry.exp <= Date.now()) return [0, -2]; return [entry.hits, entry.exp - Date.now()]; } throw new Error(`fake redis: unsupported command ${cmd}`); }; return { sendCommand, data, commands }; } // Hardened sendCommand wrapper with index.js's exact safeRedisSendCommand // semantics (fail-open placeholder reply, NOSCRIPT rethrow) over an // injectable underlying client — the same closure shape the owner receives. function createHardenedWrapper(client, security) { return async (...args) => { try { const safeArgs = args.map((arg) => { if (arg === null || arg === undefined) return "0"; if (typeof arg === "number") { const n = Math.floor(arg); return Number.isFinite(n) ? String(n) : "0"; } if (typeof arg === "string") return arg; return String(arg); }); return await client.sendCommand(safeArgs); } catch (err) { if (/NOSCRIPT/i.test(String(err?.message || ""))) throw err; const windowMs = parseInt(security.window_seconds, 10) * 1000 || 120000; return [1, windowMs]; } }; } async function listen(app) { return new Promise((resolve) => { const server = app.listen(0, "127.0.0.1", () => resolve({ server, base: `http://127.0.0.1:${server.address().port}` })); }); } async function getJson(base, p) { const res = await fetch(base + p, { headers: { "user-agent": "policy-owner-test" } }); let body = null; try { body = await res.json(); } catch { body = null; } return { status: res.status, body, headers: res.headers }; } function buildOwnerHarness({ security, sendCommand, isRequestFromTrustedSubnet, isRateLimitExempt }) { const owner = createGlobalRateLimitOwner({ rateLimit, RateLimitRedisStore, getSecurity: () => security, redisSendCommand: sendCommand, isRequestFromTrustedSubnet: isRequestFromTrustedSubnet || (() => false), isRateLimitExempt: isRateLimitExempt || (() => false), basePrefix: "rl", }); const app = express(); app.use("/api/", owner.middleware); app.get("/api/ping", (req, res) => res.json({ ok: true })); app.get("/api/me", (req, res) => res.json({ ok: true })); return owner; } function fakeRedisStats(fake, prefix) { let hits = 0; for (const [key, entry] of fake.data.entries()) { if (key.startsWith(prefix)) hits += entry.hits; } return hits; } // --------------------------------------------------------------------------- // Owner units — real express-rate-limit over the fake Redis // --------------------------------------------------------------------------- test("owner: generation 1 enforces the boot policy; `max` stays live without a rebuild", async () => { const security = { rate_limiting: true, limit: 3, window_seconds: 120 }; const fake = createFakeRedis(); const owner = buildOwnerHarness({ security, sendCommand: fake.sendCommand }); assert.deepEqual(owner.describePolicy(), { mounted: true, enforcing: true, generation: 1, windowMs: 120000 }); const app = express(); app.use("/api/", owner.middleware); app.get("/api/ping", (req, res) => res.json({ ok: true })); const { server, base } = await listen(app); try { const first = await getJson(base, "/api/ping"); assert.equal(first.status, 200); assert.equal(fakeRedisStats(fake, "rl:legacy-w120000:"), 1, "the shared window namespace counts the first hit"); // `max` is a live function: raising the limit admits more requests with // NO rebuild and NO counter reset (hit 1 is already counted; hits 2..10 // are admitted under the raised limit). security.limit = 10; assert.equal(owner.applyPolicy().rebuilt, false, "a limit change must not rebuild"); for (let i = 0; i < 9; i++) { const r = await getJson(base, "/api/ping"); assert.equal(r.status, 200, `request ${i + 2} admitted under the raised live limit`); } assert.equal(fakeRedisStats(fake, "rl:legacy-w120000:"), 10, "counters were not reset by the no-op applyPolicy"); security.limit = 3; const over = await getJson(base, "/api/ping"); assert.equal(over.status, 429); assert.deepEqual(over.body, { error: "Too many requests from this IP, please try again later." }); assert.ok(over.headers.get("retry-after"), "the 429 carries the standard Retry-After header"); assert.equal(owner.describePolicy().generation, 1, "still generation 1 throughout"); } finally { server.close(); } }); test("owner: a window_seconds change applies WITHOUT restart — new generation, fresh buckets, new EXPIRE seed", async () => { const security = { rate_limiting: true, limit: 3, window_seconds: 120 }; const fake = createFakeRedis(); const owner = buildOwnerHarness({ security, sendCommand: fake.sendCommand }); const app = express(); app.use("/api/", owner.middleware); app.get("/api/ping", (req, res) => res.json({ ok: true })); const { server, base } = await listen(app); try { for (let i = 0; i < 3; i++) assert.equal((await getJson(base, "/api/ping")).status, 200); assert.equal((await getJson(base, "/api/ping")).status, 429, "limit 3 blocks the 4th request in generation 1"); // express-rate-limit increments BEFORE the limit check, so the blocked // request consumed a store hit too. assert.equal(fakeRedisStats(fake, "rl:legacy-w120000:"), 4); // THE fix: the saved window takes effect live. security.window_seconds = 600; const applied = owner.applyPolicy(); assert.equal(applied.rebuilt, true, "a changed window must rebuild"); assert.equal(applied.generation, 2); assert.equal(applied.windowMs, 600000); assert.equal(owner.describePolicy().windowMs, 600000, "describePolicy reports the enforced window"); assert.equal(owner.describePolicy().generation, 2); // Old-generation buckets are not consulted: the blocked IP passes again. const after = await getJson(base, "/api/ping"); assert.equal(after.status, 200, "the rebuilt generation starts the IP at zero under its own prefix"); // The new enforced window is the STORE's EXPIRE seed, not just a label. const g2entry = [...fake.data.entries()].find(([k]) => k.startsWith("rl:legacy-w600000:")); assert.ok(g2entry, "a generation-2 bucket exists"); const ttl = g2entry[1].exp - Date.now(); assert.ok(ttl > 590000 && ttl <= 600000, `the rebuilt store seeds EXPIRE from the new 600s window (got ${ttl}ms)`); const g1entry = [...fake.data.entries()].find(([k]) => k.startsWith("rl:legacy-w120000:")); assert.equal(g1entry[1].hits, 4, "generation-1 counters are frozen — never consulted after the rebuild"); // The new generation enforces at its own limit. assert.equal((await getJson(base, "/api/ping")).status, 200); assert.equal((await getJson(base, "/api/ping")).status, 200); assert.equal((await getJson(base, "/api/ping")).status, 429, "generation 2 enforces its own counter window"); assert.equal(fakeRedisStats(fake, "rl:legacy-w600000:"), 4, "new-window counts stay independent of the old window"); } finally { server.close(); } }); test("owner: applyPolicy is idempotent on an unchanged window and flag flips never rebuild", async () => { const security = { rate_limiting: true, limit: 3, window_seconds: 120 }; const fake = createFakeRedis(); const owner = buildOwnerHarness({ security, sendCommand: fake.sendCommand }); const app = express(); app.use("/api/", owner.middleware); app.get("/api/ping", (req, res) => res.json({ ok: true })); const { server, base } = await listen(app); try { for (let i = 0; i < 2; i++) assert.equal((await getJson(base, "/api/ping")).status, 200); // The fs.watch merge fires after the save route's own applyPolicy(): a // second call with the same window must NOT rebuild (no counter reset). const noop = owner.applyPolicy(); assert.equal(noop.rebuilt, false, "unchanged window is a no-op"); assert.equal(owner.describePolicy().generation, 1, "still generation 1 after the no-op"); assert.equal((await getJson(base, "/api/ping")).status, 200, "pre-noop counters survived (hit 3)"); assert.equal((await getJson(base, "/api/ping")).status, 429, "the 4th request is still blocked"); assert.equal(fakeRedisStats(fake, "rl:legacy-w120000:"), 4); // Flag off: nothing enforces; the skip reads live so NO rebuild happens. security.rate_limiting = false; assert.equal(owner.applyPolicy().rebuilt, false, "a flag flip must not rebuild"); assert.equal((await getJson(base, "/api/ping")).status, 200, "flag off passes"); assert.equal(fakeRedisStats(fake, "rl:legacy-w120000:"), 4, "the skipped request consumed no budget"); // Flag on again: the intact counter still blocks. security.rate_limiting = true; assert.equal((await getJson(base, "/api/ping")).status, 429, "counter survived the disabled period"); } finally { server.close(); } }); test("owner: restarted workers and missed window round trips share the persisted revision budget", async () => { const security = { rate_limiting: true, limit: 2, window_seconds: 120, rate_limit_revision: "a".repeat(32), rate_limit_revision_window_ms: 120000 }; const fake = createFakeRedis(); const first = buildOwnerHarness({ security, sendCommand: fake.sendCommand }); security.window_seconds = 600; security.rate_limit_revision_window_ms = 600000; security.rate_limit_revision = "b".repeat(32); first.applyPolicy(); const restarted = buildOwnerHarness({ security, sendCommand: fake.sendCommand }); const app = express(); app.use("/api/first", first.middleware); app.use("/api/restarted", restarted.middleware); app.get("/api/:worker", (_req, res) => res.json({ ok: true })); const { server, base } = await listen(app); try { assert.equal((await getJson(base, "/api/first")).status, 200); assert.equal((await getJson(base, "/api/restarted")).status, 200); assert.equal((await getJson(base, "/api/first")).status, 429); assert.equal(fake.data.size, 1, "local generation differences cannot split the budget"); const missed = buildOwnerHarness({ security, sendCommand: fake.sendCommand }); security.rate_limit_revision = "c".repeat(32); assert.equal(missed.applyPolicy().rebuilt, true, "a new revision rebuilds even with the same effective window"); } finally { server.close(); } }); test("owner: the skip consults the ONE exempt helper with the original path and the trusted-subnet bypass", async () => { const security = { rate_limiting: true, limit: 3, window_seconds: 120 }; const fake = createFakeRedis(); const exemptCalls = []; let trusted = false; const owner = createGlobalRateLimitOwner({ rateLimit, RateLimitRedisStore, getSecurity: () => security, redisSendCommand: fake.sendCommand, isRequestFromTrustedSubnet: () => trusted, isRateLimitExempt: (p) => { exemptCalls.push(p); return p === "/api/me"; }, basePrefix: "rl", }); const app = express(); app.use("/api/", owner.middleware); app.get("/api/ping", (req, res) => res.json({ ok: true })); app.get("/api/me", (req, res) => res.json({ ok: true })); const { server, base } = await listen(app); try { assert.equal((await getJson(base, "/api/me")).status, 200); assert.deepEqual(exemptCalls, ["/api/me"], "the skip hands the ORIGINAL request path (not the mount-stripped req.path) to the exempt helper"); assert.equal(fake.data.size, 0, "an exempted endpoint consumes no budget"); trusted = true; assert.equal((await getJson(base, "/api/ping")).status, 200, "trusted-subnet IPs bypass the global brake"); assert.equal(fake.data.size, 0, "bypassed requests are never counted"); trusted = false; assert.equal((await getJson(base, "/api/ping")).status, 200, "normal IPs are counted"); assert.equal(fake.data.size, 1, "the counted request created exactly one bucket"); } finally { server.close(); } }); test("owner: Redis absent at boot → pass-through middleware (the in-memory fallback owns the budget)", async () => { const security = { rate_limiting: true, limit: 3, window_seconds: 120 }; const owner = buildOwnerHarness({ security, sendCommand: null }); assert.deepEqual( owner.describePolicy(), { mounted: false, enforcing: false, generation: 0, windowMs: null }, "describePolicy must keep redisApiLimiterMounted semantics truthful (not mounted)" ); const applied = owner.applyPolicy(); assert.equal(applied.rebuilt, false, "no Redis → nothing to rebuild"); assert.equal(applied.reason, "no-redis-at-boot"); const app = express(); app.use("/api/", owner.middleware); app.get("/api/ping", (req, res) => res.json({ ok: true })); const { server, base } = await listen(app); try { for (let i = 0; i < 10; i++) { const r = await getJson(base, "/api/ping"); assert.equal(r.status, 200, "pass-through never throttles — the in-memory middleware enforces instead"); } } finally { server.close(); } }); test("owner: the injected hardened sendCommand keeps the fail-open posture and the NOSCRIPT rethrow behavior", async () => { // Redis down since boot: EVALSHA rejects with a connection error → the // wrapper's placeholder reply keeps requests passing (no 500). (SCRIPT LOAD // is answered with a sha so the store constructor's un-awaited loads don't // reject — the boot-down SCRIPT-LOAD rejection itself is covered by // passOnStoreError at increment time, not by the constructor.) const security = { rate_limiting: true, limit: 3, window_seconds: 120 }; const downClient = { sendCommand: async (args) => { if (args[0] === "EVALSHA") throw new Error("Connection closed"); return "sha-down"; }, }; const owner = buildOwnerHarness({ security, sendCommand: createHardenedWrapper(downClient, security) }); const app = express(); app.use("/api/", owner.middleware); app.get("/api/ping", (req, res) => res.json({ ok: true })); const { server, base } = await listen(app); try { for (let i = 0; i < 5; i++) { const r = await getJson(base, "/api/ping"); assert.equal(r.status, 200, "store errors fail open — abuse brake, not an auth control"); } } finally { server.close(); } // NOSCRIPT: the wrapper rethrows so rate-limit-redis' retryableIncrement // self-heals (SCRIPT LOAD + retry); here the retry still fails, the store // rejects, passOnStoreError keeps the request passing — never a 500. let evalshaCalls = 0; const noscriptClient = { sendCommand: async (args) => { if (args[0] === "EVALSHA") { evalshaCalls += 1; throw new Error("NOSCRIPT rate limiter script"); } return "sha-noscript-test"; }, }; const owner2 = buildOwnerHarness({ security, sendCommand: createHardenedWrapper(noscriptClient, security) }); const app2 = express(); app2.use("/api/", owner2.middleware); app2.get("/api/ping", (req, res) => res.json({ ok: true })); const l2 = await listen(app2); try { const r = await getJson(l2.base, "/api/ping"); assert.equal(r.status, 200, "NOSCRIPT retry exhaustion still fails open via passOnStoreError"); assert.ok(evalshaCalls >= 2, "the store actually retried after the SCRIPT LOAD"); } finally { l2.server.close(); } }); // --------------------------------------------------------------------------- // index.js wiring pins // --------------------------------------------------------------------------- function countOccurrences(haystack, needle) { return haystack.split(needle).length - 1; } test("index.js mounts the owner middleware exactly once and keeps redisApiLimiterMounted semantics", () => { assert.equal( countOccurrences(indexSource, 'app.use("/api/", globalRateLimitOwner.middleware);'), 1, "exactly one /api/ limiter mount — through the owner's swap-safe middleware wrapper" ); assert.equal(countOccurrences(indexSource, 'app.use("/api/", globalLimiter);'), 0, "the frozen-policy construction is gone"); assert.equal(countOccurrences(indexSource, "redisApiLimiterMounted = true;"), 1, "the mount marker stays truthful"); assert.equal(countOccurrences(indexSource, "let globalRateLimitOwner = null;"), 1, "the owner handle is module-level so the save route and fs.watch can reach it"); assert.equal(countOccurrences(indexSource, "const globalLimiter = rateLimit({"), 0, "no parallel limiter construction may remain in index.js"); }); test("index.js publishes policies through the atomic store and watches renamed configuration", () => { const saveIdx = indexSource.indexOf('app.post("/api/settings/security", sessionRevoke2faRateLimiter'); assert.ok(saveIdx >= 0, "save route anchor"); const saveWindow = indexSource.slice(saveIdx, saveIdx + 6000); const persistIdx = saveWindow.indexOf("await securityPolicyStore.save("); assert.ok(persistIdx >= 0, "the save route persists security.json"); assert.ok(persistIdx < saveWindow.indexOf("return res.json({"), "the commit completes before success"); const storeAt = indexSource.indexOf("const securityPolicyStore = createSecurityPolicyStore("); const storeWiring = indexSource.slice(storeAt, storeAt + 600); assert.ok(storeWiring.includes("if (globalRateLimitOwner) globalRateLimitOwner.applyPolicy();"), "only committed publication applies the policy"); assert.ok(indexSource.includes("securityPolicyStore.watch();"), "the atomic replacement remains observable"); assert.ok(!indexSource.includes("fs.watch(SECURITY_FILE"), "no stale inode-bound watcher remains"); }); test("index.js injects the hardened sendCommand closure and the shared helpers into the owner", () => { const constructionIdx = indexSource.indexOf("globalRateLimitOwner = createGlobalRateLimitOwner({"); assert.ok(constructionIdx >= 0, "owner construction anchor"); const window = indexSource.slice(constructionIdx, constructionIdx + 900); for (const marker of [ "redisSendCommand: safeRedisSendCommand,", "isRequestFromTrustedSubnet,", "isRateLimitExempt,", "getSecurity: () => security,", "RateLimitRedisStore,", "rateLimit,", ]) { assert.ok(window.includes(marker), `owner construction must inject ${marker}`); } assert.ok(indexSource.includes('const { createGlobalRateLimitOwner } = require("./services/global-rate-limit-owner");'), "index.js requires the ONE policy owner module"); }); test("the obsolete window-freeze constraint is gone and the rebuild-on-save contract is documented", () => { assert.equal(countOccurrences(indexSource, "adpanel:rate-limit-window-freeze"), 0, "the stale freeze comment must not contradict the code"); assert.ok(indexSource.includes("// adpanel:rate-limit-policy-owner"), "index.js documents the rebuild-on-save contract"); assert.ok(ownerSource.includes("// adpanel:rate-limit-policy-owner"), "the owner module documents the generation contract"); assert.ok(ownerSource.includes("generation-scoped prefix"), "the owner documents why every generation gets a fresh store + prefix"); }); // --------------------------------------------------------------------------- // Save-route wiring — house vm-extraction of the REAL route statement // --------------------------------------------------------------------------- function extractRouteStatement(source, marker) { const start = source.indexOf(marker); assert.ok(start >= 0, `route marker not found: ${marker}`); let i = start; let depth = 0; let started = false; let inString = null; while (i < source.length) { const ch = source[i]; if (inString) { if (ch === "\\") { i += 2; continue; } if (ch === inString) inString = null; i += 1; continue; } if (ch === "/" && source[i + 1] === "/") { const j = source.indexOf("\n", i); i = j < 0 ? source.length : j; continue; } if (ch === "/" && source[i + 1] === "*") { const j = source.indexOf("*/", i + 2); i = j < 0 ? source.length : j + 2; continue; } if (ch === '"' || ch === "'" || ch === "`") { inString = ch; i += 1; continue; } if (ch === "(") { depth += 1; started = true; } else if (ch === ")") { depth -= 1; } if (started && depth === 0) { let end = i + 1; while (end < source.length && source[end] === ";") end += 1; return source.slice(start, end); } i += 1; } assert.fail(`unbalanced route statement: ${marker}`); } const securityPostStatement = extractRouteStatement( indexSource, 'app.post("/api/settings/security", sessionRevoke2faRateLimiter' ); function makeRes() { const res = { statusCode: 0, body: null, headersSent: false, endCalls: 0, }; res.status = (code) => { res.statusCode = code; res.headersSent = true; return res; }; res.json = (body) => { res.body = body; if (!res.statusCode) res.statusCode = 200; res.headersSent = true; return res; }; res.end = () => { res.endCalls += 1; return res; }; return res; } function makeReq(body) { return { body: body || {}, headers: { "user-agent": "policy-owner-test" }, session: { user: "admin@example.test" }, }; } // Loads the route statement into a sandbox; `overrides` replaces any dep by // name (the containment test injects rejecting awaitables). Returns // { handler, calls, security, owner } — calls is an ordered log of the // persist/apply/response choreography. function loadSecurityPostRoute(overrides = {}) { const captured = []; const security = { rate_limiting: false, limit: 300, window_seconds: 120, trusted_subnets: [] }; const calls = []; const owner = { applyPolicy: (...a) => { calls.push("applyPolicy"); if (overrides.applyPolicyImpl) return overrides.applyPolicyImpl(...a); return { rebuilt: true, generation: 2, windowMs: 600000 }; }, }; const sandbox = { sessionRevoke2faRateLimiter: (req, res, next) => next(), isAdmin: async (req) => true, requireActionTokenOr403: async () => true, findUserByEmail: async () => ({ id: 7, email: "admin@example.test", admin: 1 }), requireDestructiveActionStepUp: async (req, res, user, reason) => { calls.push(`stepUp:${reason}`); if (overrides.stepUpOk === false) { res.status(403).json({ error: "step-up required" }); return { ok: false }; } return { ok: true, graceExpiresAt: 123456 }; }, safeWriteJson: (file, obj) => { calls.push("safeWriteJson"); if (overrides.safeWriteJsonImpl) return overrides.safeWriteJsonImpl(file, obj); return true; }, securityPolicyStore: { save: async (changes) => { calls.push("safeWriteJson"); const candidate = { ...security, ...changes }; if (overrides.safeWriteJsonImpl && overrides.safeWriteJsonImpl("/security.json", candidate) === false) throw new Error("write failed"); Object.assign(security, candidate); owner.applyPolicy(); } }, getVerifiedSessionRevokeGraceState: async () => ({ expiresAt: 999 }), getDestructiveActionSecurityAsync: async () => ({ password: true }), validateTrustedSubnetsInput: () => ({ ok: true, entries: [], invalid: [], reason: "" }), globalRateLimitOwner: owner, security, SECURITY_FILE: "/security.json", console: { error: () => {}, log: () => {}, warn: () => {} }, ...(overrides.isAdmin ? { isAdmin: overrides.isAdmin } : {}), ...(overrides.requireActionTokenOr403 ? { requireActionTokenOr403: overrides.requireActionTokenOr403 } : {}), ...(overrides.findUserByEmail ? { findUserByEmail: overrides.findUserByEmail } : {}), ...(overrides.requireDestructiveActionStepUp ? { requireDestructiveActionStepUp: overrides.requireDestructiveActionStepUp } : {}), ...(overrides.getVerifiedSessionRevokeGraceState ? { getVerifiedSessionRevokeGraceState: overrides.getVerifiedSessionRevokeGraceState } : {}), ...(overrides.getDestructiveActionSecurityAsync ? { getDestructiveActionSecurityAsync: overrides.getDestructiveActionSecurityAsync } : {}), }; const ctx = vm.createContext({ ...sandbox, app: { get: (...args) => captured.push(args), post: (...args) => captured.push(args) }, String, Number, Boolean, Math, Date, Object, Array, JSON, Promise, Error, RegExp, }); vm.runInContext(securityPostStatement, ctx, { filename: "index.js[POST /api/settings/security]" }); assert.equal(captured.length, 1, "exactly one route registration"); const handler = captured[0][captured[0].length - 1]; return { handler, calls, security, owner }; } test("save route: a successful save persists, THEN applies the policy, THEN responds", async () => { const { handler, calls, security } = loadSecurityPostRoute({}); const res = makeRes(); await handler(makeReq({ rate_limiting: true, limit: 300, window_seconds: 600 }), res); assert.equal(res.statusCode, 200); assert.equal(res.body.ok, true); assert.equal(security.window_seconds, 600, "the live policy object carries the saved window"); assert.equal(security.limit, 300); assert.ok(security.rate_limiting === true); assert.deepEqual(calls, ["stepUp:Security settings update", "safeWriteJson", "applyPolicy"], "persist → apply → respond, in that order"); }); test("save route: a failed persist leaves the previous effective policy enforcing (no applyPolicy call)", async () => { const { handler, calls } = loadSecurityPostRoute({ safeWriteJsonImpl: () => { throw new Error("EACCES"); }, }); const res = makeRes(); await handler(makeReq({ rate_limiting: true, limit: 300, window_seconds: 600 }), res); assert.equal(res.statusCode, 500); assert.deepEqual(res.body, { error: "failed to save" }, "the route's existing safe wording"); assert.ok(!calls.includes("applyPolicy"), "a failed save must NOT rebuild the limiter"); assert.deepEqual(calls, ["stepUp:Security settings update", "safeWriteJson"]); }); test("save route: a refused step-up never reaches the persist or the rebuild", async () => { const { handler, calls } = loadSecurityPostRoute({ stepUpOk: false }); const res = makeRes(); await handler(makeReq({ rate_limiting: true, limit: 300, window_seconds: 600 }), res); assert.equal(res.statusCode, 403); assert.ok(!calls.includes("safeWriteJson"), "no persist"); assert.ok(!calls.includes("applyPolicy"), "no rebuild — the previous policy stays enforcing"); }); test("save route containment: every previously-uncovered await answers a bounded 500 (no hang, no rejection)", async () => { for (const [label, deps] of [ ["isAdmin rejects", { isAdmin: async () => { throw new Error("db down"); } }], ["requireActionTokenOr403 rejects", { requireActionTokenOr403: async () => { throw new Error("redis timeout"); } }], ["findUserByEmail rejects", { findUserByEmail: async () => { throw new Error("db down"); } }], ["requireDestructiveActionStepUp rejects", { requireDestructiveActionStepUp: async () => { throw new Error("db down"); } }], ["grace-state rejects after persist", { // stepUp must withhold graceExpiresAt or the `||` short-circuit never // reaches the getVerifiedSessionRevokeGraceState await. requireDestructiveActionStepUp: async () => ({ ok: true }), getVerifiedSessionRevokeGraceState: async () => { throw new Error("db down"); }, }], ["revoke-security rejects after persist", { getDestructiveActionSecurityAsync: async () => { throw new Error("db down"); } }], ]) { const { handler, calls } = loadSecurityPostRoute(deps); const res = makeRes(); let rejection = null; try { await handler(makeReq({ rate_limiting: true, limit: 300, window_seconds: 600 }), res); } catch (err) { rejection = err; } assert.equal(rejection, null, `${label}: the handler must settle, not reject (Express 4 leaves a rejected handler unanswered)`); assert.equal(res.statusCode, 500, `${label}: bounded 500`); assert.deepEqual(res.body, { error: "failed to save" }, `${label}: the route's safe wording`); if (label === "grace-state rejects after persist" || label === "revoke-security rejects after persist") { assert.ok(calls.includes("applyPolicy"), `${label}: the policy was already applied after the successful persist — the save itself succeeded`); } else { assert.ok(!calls.includes("applyPolicy"), `${label}: nothing was persisted, so nothing was rebuilt`); } } });