685 lines
33 KiB
JavaScript
685 lines
33 KiB
JavaScript
"use strict";
|
|
|
|
// adpanel:logout-reliability — POST /logout is the availability-critical
|
|
// revocation surface: it revokes db-proxy tokens, tears down live SSH
|
|
// terminal tunnels, disconnects the session's sockets, revokes the remember
|
|
// lineage and writes the sid tombstone BEFORE destroying the session. Two
|
|
// reliability hazards are closed here and locked:
|
|
//
|
|
// 1. The generic budgets must never block logout. /logout was a plain
|
|
// consumer of the app-wide in-memory budget (whenever
|
|
// security.rate_limiting === true), so an exhausted per-IP generic
|
|
// window 429'd POST /logout and NONE of the server-side revocation ran
|
|
// — the session stayed live server-side while the client (which used to
|
|
// redirect unconditionally) presented the logout as success. /logout now
|
|
// rides the ONE shared exempt list (RATE_LIMIT_EXEMPT_PATHS, consulted
|
|
// by both generic budgets through isRateLimitExempt) and is budgeted by
|
|
// a DEDICATED brake instead: windowMs 10 min, max 10, own
|
|
// buildSharedRateLimitRedisStore instance with the DISTINCT "logout:"
|
|
// prefix, passOnStoreError true (a store outage must never lock users
|
|
// out of logout), keyed per logged-in user with a /56-bucketed IP
|
|
// fallback for anonymous floods.
|
|
// 2. The client must not present a failed logout as success. Both logout
|
|
// handlers (public/js/settings.js, public/js/dashboard.js) used to
|
|
// delete cookies and redirect to /login regardless of the response —
|
|
// on a 429 (throttled) or 500 (tombstone pre-flight failure) the server
|
|
// may still hold a LIVE session while the browser shows the login page.
|
|
// They now treat logout as complete ONLY on res.ok && success === true;
|
|
// otherwise cookies stay, no redirect happens, and the server's error
|
|
// text (or the honest fallback) is surfaced via the files' existing
|
|
// alert idiom. Cookie deletion is cosmetic (HttpOnly auth cookies are
|
|
// server-cleared) and deliberately moved AFTER the confirmed response.
|
|
//
|
|
// CSRF posture is unchanged: sameOriginProtection stays the app-wide
|
|
// cross-site guard and the limiter adds throttling only — no new bypass.
|
|
//
|
|
// Technique: index.js boots servers on require, so the shipped definitions
|
|
// are extracted from source and evaluated (rateLimiterMiddleware and
|
|
// isRateLimitExempt in a vm sandbox; logoutRateLimiter as REAL
|
|
// express-rate-limit over a fake Redis store through the shipped
|
|
// buildSharedRateLimitRedisStore seam — same harnesses as
|
|
// tests/progress-poll-budget.test.js and
|
|
// tests/admin-create-throttle-identity.test.js). The frontend handlers are
|
|
// extracted verbatim from both files and run in a vm sandbox with stubbed
|
|
// document/fetch/location.
|
|
|
|
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, ipKeyGenerator } = require("express-rate-limit");
|
|
|
|
const ROOT = path.join(__dirname, "..");
|
|
const INDEX_JS = path.join(ROOT, "index.js");
|
|
const SETTINGS_JS = path.join(ROOT, "public", "js", "settings.js");
|
|
const DASHBOARD_JS = path.join(ROOT, "public", "js", "dashboard.js");
|
|
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
|
const settingsSource = fs.readFileSync(SETTINGS_JS, "utf8");
|
|
const dashboardSource = fs.readFileSync(DASHBOARD_JS, "utf8");
|
|
|
|
const LOGOUT_LIMITER = "logoutRateLimiter";
|
|
const LOGOUT_429_TEXT = "Too many logout attempts. Please try again shortly.";
|
|
|
|
function countOccurrences(haystack, needle) {
|
|
return haystack.split(needle).length - 1;
|
|
}
|
|
|
|
function indexOfOrThrow(source, needle, from = 0) {
|
|
const idx = source.indexOf(needle, from);
|
|
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
|
|
return idx;
|
|
}
|
|
|
|
// Comment- and string-aware brace matcher (same scanning discipline as
|
|
// tests/limiter-ipv6-bucketing.test.js / tests/admin-create-throttle-identity.test.js).
|
|
function matchBrace(source, openIdx) {
|
|
let depth = 0;
|
|
let inLine = false;
|
|
let inBlock = false;
|
|
let quote = null;
|
|
for (let i = openIdx; i < source.length; i++) {
|
|
const c = source[i];
|
|
const n = source[i + 1];
|
|
if (inLine) {
|
|
if (c === "\n") inLine = false;
|
|
continue;
|
|
}
|
|
if (inBlock) {
|
|
if (c === "*" && n === "/") { inBlock = false; i++; }
|
|
continue;
|
|
}
|
|
if (quote) {
|
|
if (c === "\\") { i++; continue; }
|
|
if (c === quote) quote = null;
|
|
continue;
|
|
}
|
|
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
|
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
|
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
|
if (c === "{") depth++;
|
|
else if (c === "}") {
|
|
depth--;
|
|
if (depth === 0) return i;
|
|
}
|
|
}
|
|
throw new Error(`unbalanced braces at offset ${openIdx}`);
|
|
}
|
|
|
|
// Same matcher over parens (for extracting an addEventListener(...) call).
|
|
function matchParen(source, openIdx) {
|
|
let depth = 0;
|
|
let inLine = false;
|
|
let inBlock = false;
|
|
let quote = null;
|
|
for (let i = openIdx; i < source.length; i++) {
|
|
const c = source[i];
|
|
const n = source[i + 1];
|
|
if (inLine) {
|
|
if (c === "\n") inLine = false;
|
|
continue;
|
|
}
|
|
if (inBlock) {
|
|
if (c === "*" && n === "/") { inBlock = false; i++; }
|
|
continue;
|
|
}
|
|
if (quote) {
|
|
if (c === "\\") { i++; continue; }
|
|
if (c === quote) quote = null;
|
|
continue;
|
|
}
|
|
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
|
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
|
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
|
if (c === "(") depth++;
|
|
else if (c === ")") {
|
|
depth--;
|
|
if (depth === 0) return i;
|
|
}
|
|
}
|
|
throw new Error(`unbalanced parens at offset ${openIdx}`);
|
|
}
|
|
|
|
function extractRateLimitExpression(constName) {
|
|
const anchor = `const ${constName} = rateLimit(`;
|
|
const start = indexOfOrThrow(indexSource, anchor);
|
|
const openBrace = indexSource.indexOf("{", start + anchor.length);
|
|
assert.ok(openBrace > start, `${constName}: rateLimit({ not found`);
|
|
const closeBrace = matchBrace(indexSource, openBrace);
|
|
assert.strictEqual(indexSource[closeBrace + 1], ")", `${constName}: the rateLimit call must close right after the object literal`);
|
|
return indexSource.slice(start + `const ${constName} = `.length, closeBrace + 2);
|
|
}
|
|
|
|
// Extract a limiter's keyGenerator function source and evaluate it against the
|
|
// REAL ipKeyGenerator (same technique as tests/admin-create-throttle-identity.test.js).
|
|
function extractKeyGenerator(constName, deps = {}) {
|
|
const expr = extractRateLimitExpression(constName);
|
|
const marker = "keyGenerator: ";
|
|
const at = expr.indexOf(marker);
|
|
assert.ok(at >= 0, `${constName}: no keyGenerator found`);
|
|
const exprStart = at + marker.length;
|
|
let fnSource;
|
|
if (expr.startsWith("(req) => {", exprStart)) {
|
|
const openBrace = exprStart + "(req) => ".length;
|
|
const closeBrace = matchBrace(expr, openBrace);
|
|
fnSource = expr.slice(exprStart, closeBrace + 1);
|
|
} else {
|
|
const lineEnd = expr.indexOf("\n", exprStart);
|
|
const oneLine = expr.slice(exprStart, lineEnd);
|
|
assert.ok(oneLine.endsWith(","), `${constName}: single-line keyGenerator must end with ,`);
|
|
fnSource = oneLine.slice(0, -1);
|
|
}
|
|
return new Function(
|
|
"ipKeyGenerator",
|
|
"getRequestIp",
|
|
`return ${fnSource};`
|
|
)(ipKeyGenerator, deps.getRequestIp || ((req) => req.sourceIp));
|
|
}
|
|
|
|
// Extract the contiguous RATE_LIMIT_EXEMPT_PATHS/PATTERNS + isRateLimitExempt
|
|
// block and evaluate it so the pins exercise the SHIPPED list (same
|
|
// technique as tests/progress-poll-budget.test.js).
|
|
function extractExemptHelper() {
|
|
const start = indexOfOrThrow(indexSource, "const RATE_LIMIT_EXEMPT_PATHS = new Set([");
|
|
const fnStart = indexOfOrThrow(indexSource, "function isRateLimitExempt(path, method) {");
|
|
assert.ok(fnStart > start, "the helper follows the lists");
|
|
let depth = 0;
|
|
let inLine = false;
|
|
let inBlock = false;
|
|
let quote = null;
|
|
let openFound = false;
|
|
for (let i = fnStart; i < indexSource.length; i++) {
|
|
const c = indexSource[i];
|
|
const n = indexSource[i + 1];
|
|
if (inLine) { if (c === "\n") inLine = false; continue; }
|
|
if (inBlock) { if (c === "*" && n === "/") { inBlock = false; i++; } continue; }
|
|
if (quote) { if (c === "\\") { i++; continue; } if (c === quote) quote = null; continue; }
|
|
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
|
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
|
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
|
if (c === "{") { depth++; openFound = true; }
|
|
else if (c === "}") {
|
|
depth--;
|
|
if (openFound && depth === 0) {
|
|
return vm.runInContext(indexSource.slice(start, i + 1) + "\nisRateLimitExempt;", vm.createContext({ Set, RegExp }));
|
|
}
|
|
}
|
|
}
|
|
throw new Error("unbalanced braces while extracting isRateLimitExempt");
|
|
}
|
|
|
|
// Extract rateLimiterMiddleware verbatim (same technique as
|
|
// tests/progress-poll-budget.test.js).
|
|
function extractRateLimiterMiddleware() {
|
|
const fnStart = indexOfOrThrow(indexSource, "function rateLimiterMiddleware(req, res, next) {");
|
|
const open = indexSource.indexOf("{", fnStart);
|
|
const close = matchBrace(indexSource, open);
|
|
return indexSource.slice(fnStart, close + 1);
|
|
}
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 1. /logout rides the ONE shared exempt list — the generic budgets can
|
|
// never block server-side revocation
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("/logout is exempt from BOTH generic budgets via the shared isRateLimitExempt helper", () => {
|
|
const isRateLimitExempt = extractExemptHelper();
|
|
assert.equal(isRateLimitExempt("/logout"), true, "/logout must be exempt from the generic budgets (the dedicated logoutRateLimiter budgets it instead)");
|
|
// adpanel:rate-limit-exempt-normalization — Express dispatches
|
|
// case-insensitively (strict:false), so exotic spellings reach the SAME
|
|
// route and must keep the exemption; anything else must stay budgeted.
|
|
assert.equal(isRateLimitExempt("/LOGOUT"), true, "the case-variant spelling routes to /logout and keeps the exemption");
|
|
assert.equal(isRateLimitExempt("/logout/"), true, "the trailing-slash spelling routes to /logout and keeps the exemption");
|
|
// Exact-match semantics: no over-broad prefix (same discipline as the
|
|
// progress-poll exemption).
|
|
assert.equal(isRateLimitExempt("/logout-extra"), false, "no over-broad prefix exemption");
|
|
assert.equal(isRateLimitExempt("/api/me"), true, "pre-existing exemptions survive untouched");
|
|
assert.equal(isRateLimitExempt("/health"), true, "pre-existing exemptions survive untouched");
|
|
assert.equal(isRateLimitExempt("/api/servers/statuses"), true, "pre-existing exemptions survive untouched");
|
|
// The entry lives in the ONE shared source (the Set), not in a second list.
|
|
const setBlock = indexSource.slice(
|
|
indexOfOrThrow(indexSource, "const RATE_LIMIT_EXEMPT_PATHS = new Set(["),
|
|
indexOfOrThrow(indexSource, "const RATE_LIMIT_EXEMPT_PATTERNS")
|
|
);
|
|
assert.ok(setBlock.includes('"/logout"'), 'the "/logout" entry lives in RATE_LIMIT_EXEMPT_PATHS itself');
|
|
});
|
|
|
|
test("an exhausted generic in-memory budget 429s generic paths while /logout still passes", () => {
|
|
const isRateLimitExempt = extractExemptHelper();
|
|
const middleware = vm.runInContext(`(${extractRateLimiterMiddleware()})`, vm.createContext({
|
|
security: { rate_limiting: true, limit: 2, window_seconds: 120 },
|
|
isRequestFromTrustedSubnet: () => false,
|
|
redisApiLimiterMounted: false,
|
|
redisClient: null,
|
|
isRateLimitExempt,
|
|
ipKeyGenerator,
|
|
getRequestIp: (req) => req.headers["x-test-ip"] || "127.0.0.1",
|
|
rateRequests: new Map(),
|
|
RATE_MAX_TRACKED_IPS: 50000,
|
|
String, Date, Math, Number, parseInt,
|
|
}));
|
|
const run = (p, ip) => {
|
|
const res = {
|
|
statusCode: 0,
|
|
headers: {},
|
|
body: null,
|
|
status(code) { this.statusCode = code; return this; },
|
|
setHeader(k, v) { this.headers[k] = v; return this; },
|
|
send(body) { this.body = body; return this; },
|
|
};
|
|
let nexted = false;
|
|
middleware({ path: p, method: "POST", headers: { "x-test-ip": ip } }, res, () => { nexted = true; });
|
|
return { nexted, res };
|
|
};
|
|
// The generic budget admits exactly 2 generic requests, then 429s.
|
|
assert.equal(run("/api/servers", "10.9.9.9").nexted, true);
|
|
assert.equal(run("/api/settings/security", "10.9.9.9").nexted, true);
|
|
const third = run("/api/servers", "10.9.9.9");
|
|
assert.equal(third.nexted, false, "the generic budget enforces");
|
|
assert.equal(third.res.statusCode, 429, "an over-budget generic request is 429'd");
|
|
// /logout rides through untouched — before AND after the exhaustion.
|
|
const logoutBefore = run("/logout", "10.9.9.9");
|
|
assert.equal(logoutBefore.nexted, true, "/logout passes while the generic budget still has room");
|
|
assert.equal(logoutBefore.res.statusCode, 0, "/logout is never answered by the generic budget");
|
|
const logoutAfter = run("/logout", "10.9.9.9");
|
|
assert.equal(logoutAfter.nexted, true, "/logout passes AFTER the generic budget is exhausted — server-side revocation stays reachable");
|
|
assert.equal(logoutAfter.res.statusCode, 0, "/logout is never 429'd by the generic budget");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 2. The dedicated logoutRateLimiter — definition, keying, mount
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("logoutRateLimiter exists with the mandated budget on its own store instance", () => {
|
|
const expr = extractRateLimitExpression(LOGOUT_LIMITER);
|
|
assert.ok(expr.includes("windowMs: 10 * 60 * 1000"), "windowMs must be 10 minutes");
|
|
assert.ok(expr.includes("max: 10"), "max 10 per window");
|
|
assert.ok(expr.includes("standardHeaders: true") && expr.includes("legacyHeaders: false"), "standard headers so the 429 carries Retry-After");
|
|
assert.ok(expr.includes("passOnStoreError: true"), "a store outage must never lock users out of logout");
|
|
assert.ok(
|
|
expr.includes('buildSharedRateLimitRedisStore("logout:")'),
|
|
'its OWN store instance via the shared factory with the DISTINCT "logout:" prefix (one store instance per limiter — AGENTS.md limiter rule)'
|
|
);
|
|
// Always-on brake: it must NOT consult security.rate_limiting (logout
|
|
// revocation is availability-critical regardless of the optional global
|
|
// brake), and it must NOT skip authenticated or anonymous callers (both
|
|
// shapes are budgeted — the keyGenerator namespaces them apart).
|
|
assert.ok(!/\brate_limiting\b/.test(expr), "logoutRateLimiter must be an always-on brake (no security.rate_limiting coupling)");
|
|
assert.ok(!/\bskip\s*:/.test(expr), "no skip — anonymous floods count on the IP fallback, logged-in users on their email key");
|
|
});
|
|
|
|
test("logoutRateLimiter is NOT wired to the trusted-subnet bypass (consumer set unchanged)", () => {
|
|
const expr = extractRateLimitExpression(LOGOUT_LIMITER);
|
|
assert.ok(!expr.includes("isRequestFromTrustedSubnet"), "the logout brake must not consult network position (logout is a revocation surface; the bypass consumer census stays untouched)");
|
|
// The trusted-subnet bypass consumer census (pinned by
|
|
// tests/trusted-subnet-limiter-bypass.test.js): definition + 3 generic
|
|
// call sites + the owner dep injection = 5. The logout brake adds none.
|
|
assert.strictEqual(countOccurrences(indexSource, "isRequestFromTrustedSubnet"), 5, "isRequestFromTrustedSubnet must still appear exactly 5 times in index.js");
|
|
});
|
|
|
|
test("the logout brake's 429 wording is byte-exact and appears exactly once", () => {
|
|
assert.strictEqual(
|
|
countOccurrences(indexSource, `res.status(429).json({ error: "${LOGOUT_429_TEXT}" });`),
|
|
1,
|
|
"the logout 429 body must exist exactly once (inside the limiter handler)"
|
|
);
|
|
const expr = extractRateLimitExpression(LOGOUT_LIMITER);
|
|
assert.ok(expr.includes(LOGOUT_429_TEXT), "the limiter handler renders the logout 429 text");
|
|
});
|
|
|
|
test("POST /logout mounts the limiter first, then the handler", () => {
|
|
const registration = 'app.post("/logout", logoutRateLimiter, async (req, res) => {';
|
|
assert.ok(indexSource.includes(registration), `expected ${registration} in index.js`);
|
|
const at = indexOfOrThrow(indexSource, registration);
|
|
const limiterDef = indexOfOrThrow(indexSource, `const ${LOGOUT_LIMITER} = rateLimit(`);
|
|
assert.ok(limiterDef < at, "the limiter definition precedes its mount");
|
|
// The handler's revocation choreography is untouched by this fix.
|
|
const handlerBody = indexSource.slice(at, indexOfOrThrow(indexSource, "const ENV_FILE_PATH", at));
|
|
for (const marker of [
|
|
"await dbProxy.revokeAllForUser(logoutUser);",
|
|
"destroyLiveSshTerminalSockets(logoutUser)",
|
|
"disconnectSocketsForUser(logoutUser, \"logged-out\", { onlySessionId: req.sessionID });",
|
|
"await revokeRememberLoginLineage(rememberLoginId, {",
|
|
"await writeRevokedSidTombstone(req.sessionID);",
|
|
"req.session.destroy(",
|
|
]) {
|
|
assert.ok(handlerBody.includes(marker), `the logout handler keeps its revocation step: ${marker}`);
|
|
}
|
|
});
|
|
|
|
test("CSRF posture unchanged: sameOriginProtection stays the app-wide cross-site guard", () => {
|
|
assert.ok(indexSource.includes("app.use(sameOriginProtection);"), "the app-wide sameOriginProtection registration must remain");
|
|
const expr = extractRateLimitExpression(LOGOUT_LIMITER);
|
|
assert.ok(!expr.includes("sameOrigin"), "the limiter adds throttling only — it does not touch the cross-site posture");
|
|
});
|
|
|
|
test("the adpanel:logout-reliability tag documents the constraint at both edits", () => {
|
|
assert.ok(countOccurrences(indexSource, "// adpanel:logout-reliability") >= 2, "index.js carries the tag on the brake definition and the exempt entry");
|
|
assert.ok(settingsSource.includes("// adpanel:logout-reliability"), "settings.js logout handler carries the tag");
|
|
assert.ok(dashboardSource.includes("// adpanel:logout-reliability"), "dashboard.js logout handler carries the tag");
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 3. KeyGenerator behavior pins (shipped source + real ipKeyGenerator)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
test("keyed per logged-in user: one stable email key across IPs, /56 rotation and sids", () => {
|
|
const keyGen = extractKeyGenerator(LOGOUT_LIMITER);
|
|
const ips = ["192.0.2.1", "2001:db8::1", "2001:db8::ffff", "2001:db8:0:100::1"];
|
|
const keys = new Set();
|
|
for (const ip of ips) {
|
|
for (const sid of ["sid-a", "sid-b"]) {
|
|
keys.add(keyGen({ sourceIp: ip, session: { user: "ops@example.com" }, sessionID: sid }));
|
|
}
|
|
}
|
|
assert.strictEqual(keys.size, 1, "IP and session churn cannot mint a fresh logout budget");
|
|
assert.ok(keys.has("logout:ops@example.com"), "the key is the stable email identity under the distinct prefix");
|
|
});
|
|
|
|
test("anonymous floods fall back to the /56-bucketed IP key; keys are never empty", () => {
|
|
const keyGen = extractKeyGenerator(LOGOUT_LIMITER);
|
|
assert.strictEqual(keyGen({ sourceIp: "2001:db8::1", session: undefined }), "logout:ip:2001:db8::/56", "anon IPv6 collapses to the /56 bucket");
|
|
assert.strictEqual(keyGen({ sourceIp: "2001:db8::1", session: undefined }), keyGen({ sourceIp: "2001:db8::ffff", session: undefined }), "intra-/56 rotation shares one anon bucket");
|
|
assert.notStrictEqual(keyGen({ sourceIp: "2001:db8::1", session: undefined }), keyGen({ sourceIp: "2001:db8:0:100::1", session: undefined }), "a different /56 is a different anon bucket");
|
|
assert.strictEqual(keyGen({ sourceIp: "192.0.2.1", session: undefined }), "logout:ip:192.0.2.1", "IPv4 passthrough (single-arg ipKeyGenerator form, byte-identical to raw)");
|
|
// A whitespace-only session user must not mint an empty email component.
|
|
assert.strictEqual(keyGen({ sourceIp: "192.0.2.1", session: { user: " " } }), "logout:ip:192.0.2.1", "a whitespace session user takes the IP fallback");
|
|
for (const req of [
|
|
{ sourceIp: undefined, session: undefined },
|
|
{ sourceIp: "", session: undefined },
|
|
{ sourceIp: "", session: { user: "" } },
|
|
{ session: { user: " " } },
|
|
]) {
|
|
const key = keyGen(req);
|
|
assert.ok(typeof key === "string" && key.length > 0, "keys must never be empty (v8 validation)");
|
|
assert.ok(key.startsWith("logout:"), "every key lives under the distinct prefix");
|
|
}
|
|
// The email key and the anon fallback namespace stay disjoint.
|
|
assert.notStrictEqual(
|
|
keyGen({ sourceIp: "192.0.2.1", session: undefined }),
|
|
keyGen({ sourceIp: "192.0.2.1", session: { user: "192.0.2.1" } }),
|
|
"an email that echoes the IP text still keys differently from the anon fallback"
|
|
);
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 4. Behavior through the SHIPPED definition: fake Redis via the store seam,
|
|
// real express-rate-limit, real express app (same harness as
|
|
// tests/admin-create-throttle-identity.test.js)
|
|
// ---------------------------------------------------------------------------
|
|
|
|
class FakeRedisStore {
|
|
constructor(prefix) {
|
|
this.prefix = prefix;
|
|
this.counts = new Map();
|
|
}
|
|
async init() {}
|
|
async increment(key) {
|
|
const cur = (this.counts.get(key) || 0) + 1;
|
|
this.counts.set(key, cur);
|
|
return { totalHits: cur, resetTime: new Date(Date.now() + 10 * 60 * 1000) };
|
|
}
|
|
async decrement(key) {
|
|
this.counts.set(key, Math.max(0, (this.counts.get(key) || 1) - 1));
|
|
}
|
|
async resetKey(key) {
|
|
this.counts.delete(key);
|
|
}
|
|
async resetAll() {
|
|
this.counts.clear();
|
|
}
|
|
}
|
|
|
|
function buildLimiter() {
|
|
const stores = [];
|
|
const log = [];
|
|
const sandbox = {
|
|
rateLimit,
|
|
redisClient: { isReady: true }, // truthy → the shipped store expression builds the store
|
|
buildSharedRateLimitRedisStore: (prefix) => {
|
|
const store = new FakeRedisStore(prefix);
|
|
stores.push(store);
|
|
return store;
|
|
},
|
|
ipKeyGenerator,
|
|
getRequestIp: (req) => req.headers["x-test-ip"] || "127.0.0.1",
|
|
securityLog: (msg, req) => log.push({ msg, ip: req.headers["x-test-ip"] }),
|
|
};
|
|
const options = extractRateLimitExpression(LOGOUT_LIMITER);
|
|
// evaluate the SHIPPED rateLimit({...}) call directly (same as
|
|
// tests/admin-create-throttle-identity.test.js — do NOT re-wrap it).
|
|
const middleware = vm.runInContext(`(${options})`, vm.createContext(sandbox), { filename: "index.js[logoutRateLimiter]" });
|
|
return { middleware, stores, log };
|
|
}
|
|
|
|
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 hit(base, headers) {
|
|
const res = await fetch(base + "/logout", { method: "POST", headers: headers || {} });
|
|
let body = null;
|
|
try { body = await res.json(); } catch { body = null; }
|
|
return { status: res.status, body, headers: res.headers };
|
|
}
|
|
|
|
function makeLogoutApp(middleware) {
|
|
const app = express();
|
|
app.use((req, res, next) => {
|
|
if (req.headers["x-test-user"]) req.session = { user: req.headers["x-test-user"] };
|
|
req.sessionID = req.headers["x-test-sid"] || "sid-test";
|
|
next();
|
|
});
|
|
// The route shape mirrors the shipped mount: limiter first, handler second.
|
|
app.post("/logout", middleware, (req, res) => res.json({ success: true }));
|
|
return app;
|
|
}
|
|
|
|
test("10 logouts pass per user; the 11th is throttled by the dedicated budget with the byte-exact 429 body", async () => {
|
|
const { middleware, stores, log } = buildLimiter();
|
|
const app = makeLogoutApp(middleware);
|
|
const { server, base } = await listen(app);
|
|
try {
|
|
for (let i = 0; i < 10; i++) {
|
|
const r = await hit(base, { "x-test-ip": "10.1.1.1", "x-test-user": "ops@example.com" });
|
|
assert.equal(r.status, 200, `logout ${i + 1} within the dedicated budget`);
|
|
}
|
|
const blocked = await hit(base, { "x-test-ip": "10.1.1.1", "x-test-user": "ops@example.com" });
|
|
assert.equal(blocked.status, 429, "the 11th logout is throttled by the DEDICATED budget");
|
|
assert.deepEqual(blocked.body, { error: LOGOUT_429_TEXT }, "the 429 body is the byte-exact logout wording");
|
|
assert.ok(blocked.headers.get("retry-after"), "the 429 carries Retry-After");
|
|
// The refused request never reaches the handler (no success body would
|
|
// have been produced anyway, but the counter proves the brake fired).
|
|
const store = stores.find((s) => s.prefix === "logout:");
|
|
assert.ok(store, "the limiter built its own store instance");
|
|
assert.equal(store.counts.get("logout:ops@example.com"), 11, "the refused attempt is still charged");
|
|
assert.equal(store.counts.size, 1, "one per-user counter");
|
|
assert.ok(log.length >= 1, "the throttle is logged server-side");
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|
|
|
|
test("a second user keeps its own budget; the first user's exhaustion does not leak", async () => {
|
|
const { middleware, stores } = buildLimiter();
|
|
const app = makeLogoutApp(middleware);
|
|
const { server, base } = await listen(app);
|
|
try {
|
|
for (let i = 0; i < 10; i++) {
|
|
const r = await hit(base, { "x-test-ip": "10.1.1.1", "x-test-user": "ops@example.com" });
|
|
assert.equal(r.status, 200);
|
|
}
|
|
assert.equal((await hit(base, { "x-test-ip": "10.1.1.1", "x-test-user": "ops@example.com" })).status, 429);
|
|
const other = await hit(base, { "x-test-ip": "10.1.1.1", "x-test-user": "other@example.com" });
|
|
assert.equal(other.status, 200, "a different logged-in user keys its own budget");
|
|
const store = stores.find((s) => s.prefix === "logout:");
|
|
assert.equal(store.counts.size, 2, "two independent per-user counters");
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|
|
|
|
test("anonymous floods share the /56-bucketed IP counter and are throttled at the same budget", async () => {
|
|
const { middleware, stores } = buildLimiter();
|
|
const app = makeLogoutApp(middleware);
|
|
const { server, base } = await listen(app);
|
|
try {
|
|
for (let i = 0; i < 10; i++) {
|
|
const r = await hit(base, { "x-test-ip": "2001:db8::1" });
|
|
assert.equal(r.status, 200, `anon logout ${i + 1} within the budget`);
|
|
}
|
|
const rotated = await hit(base, { "x-test-ip": "2001:db8::ffff" });
|
|
assert.equal(rotated.status, 429, "intra-/56 address rotation cannot mint a fresh anon budget");
|
|
assert.deepEqual(rotated.body, { error: LOGOUT_429_TEXT }, "the anon 429 carries the same byte-exact wording");
|
|
const store = stores.find((s) => s.prefix === "logout:");
|
|
assert.equal(store.counts.size, 1, "one anon bucket for the whole /56");
|
|
assert.equal(store.counts.get("logout:ip:2001:db8::/56"), 11, "the bucket charged every attempt including the refused one");
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|
|
|
|
test("store isolation: only logout: keys exist; a missing IP falls back to the non-empty unknown bucket", async () => {
|
|
const { middleware, stores } = buildLimiter();
|
|
const app = makeLogoutApp(middleware);
|
|
const { server, base } = await listen(app);
|
|
try {
|
|
const r1 = await hit(base, { "x-test-user": "ops@example.com" });
|
|
assert.equal(r1.status, 200);
|
|
const r2 = await hit(base, {});
|
|
assert.equal(r2.status, 200, "a request with no resolvable IP still gets a non-empty key and passes");
|
|
for (const store of stores) {
|
|
for (const key of store.counts.keys()) {
|
|
assert.ok(key.startsWith("logout:"), `every counter lives under the distinct prefix (got ${key})`);
|
|
assert.ok(key.length > "logout:".length, `no empty key suffix (got ${key})`);
|
|
}
|
|
}
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|
|
|
|
// ---------------------------------------------------------------------------
|
|
// 5. Frontend — the REAL handlers, vm-extracted from both files
|
|
// ---------------------------------------------------------------------------
|
|
|
|
const SETTINGS_HANDLER_START = 'document.getElementById("logoutBtn").addEventListener("click"';
|
|
const DASHBOARD_HANDLER_START = "document.getElementById('logoutBtn')?.addEventListener('click'";
|
|
|
|
function extractFrontendHandler(source, startMarker, label) {
|
|
const start = indexOfOrThrow(source, startMarker);
|
|
const addListenerAt = indexOfOrThrow(source, "addEventListener(", start);
|
|
const openParen = indexOfOrThrow(source, "(", addListenerAt + "addEventListener".length);
|
|
const closeParen = matchParen(source, openParen);
|
|
let end = closeParen + 1;
|
|
if (source[end] === ";") end += 1;
|
|
return source.slice(start, end);
|
|
}
|
|
|
|
function makeFrontendHarness(source, startMarker, label) {
|
|
const handlerSource = extractFrontendHandler(source, startMarker, label);
|
|
const events = {
|
|
cookieClears: 0,
|
|
redirects: [],
|
|
alerts: [],
|
|
consoleErrors: [],
|
|
order: [], // "fetch" | "cookies" | "redirect:<target>" in call order
|
|
};
|
|
const btnStub = {
|
|
addEventListener: (_type, fn) => { btnStub.handler = fn; },
|
|
};
|
|
const sandbox = {
|
|
document: { getElementById: () => btnStub },
|
|
deleteAllClientCookies: () => { events.cookieClears += 1; events.order.push("cookies"); },
|
|
location: {
|
|
set href(v) { events.redirects.push(v); events.order.push(`redirect:${v}`); },
|
|
get href() { return events.redirects[events.redirects.length - 1]; },
|
|
},
|
|
alert: (msg) => { events.alerts.push(String(msg)); },
|
|
console: { error: (...args) => { events.consoleErrors.push(args); }, log: () => {}, warn: () => {} },
|
|
fetch: null, // set per scenario in click()
|
|
setTimeout: (fn) => { fn(); return 0; },
|
|
};
|
|
vm.runInContext(handlerSource, vm.createContext(sandbox), { filename: `${label}[logoutBtn]` });
|
|
assert.ok(typeof btnStub.handler === "function", `${label}: the logout click handler was registered`);
|
|
return {
|
|
events,
|
|
async click(fetchBehavior) {
|
|
sandbox.fetch = async (...args) => {
|
|
events.order.push("fetch");
|
|
return fetchBehavior(...args);
|
|
};
|
|
const event = { preventDefault: () => {} };
|
|
await btnStub.handler(event);
|
|
},
|
|
};
|
|
}
|
|
|
|
const LOGOUT_429_BODY = { error: LOGOUT_429_TEXT };
|
|
const LOGOUT_500_BODY = { error: "Failed to logout" };
|
|
const LOGOUT_OK_BODY = { success: true, revocationDegraded: false, sessionRevocationDegraded: false };
|
|
|
|
function okResponse(body) {
|
|
return { ok: true, status: 200, json: async () => body };
|
|
}
|
|
function errorResponse(status, body) {
|
|
return { ok: false, status, json: async () => body };
|
|
}
|
|
|
|
for (const [label, source, startMarker] of [
|
|
["settings.js", settingsSource, SETTINGS_HANDLER_START],
|
|
["dashboard.js", dashboardSource, DASHBOARD_HANDLER_START],
|
|
]) {
|
|
test(`[${label}] a confirmed logout (ok + success:true) clears cookies and redirects exactly once`, async () => {
|
|
const h = makeFrontendHarness(source, startMarker, label);
|
|
await h.click(async () => okResponse(LOGOUT_OK_BODY));
|
|
assert.equal(h.events.cookieClears, 1, "client cookies are cleared exactly once");
|
|
assert.deepEqual(h.events.redirects, ["/login"], "the only redirect is /login");
|
|
assert.deepEqual(h.events.alerts, [], "no error alert on a confirmed logout");
|
|
assert.deepEqual(h.events.consoleErrors, [], "no console error on a confirmed logout");
|
|
});
|
|
|
|
test(`[${label}] a 429-throttled logout is NOT presented as success — no cookies cleared, no redirect, server text surfaced`, async () => {
|
|
const h = makeFrontendHarness(source, startMarker, label);
|
|
await h.click(async () => errorResponse(429, LOGOUT_429_BODY));
|
|
assert.equal(h.events.cookieClears, 0, "cookies must stay: the server may still hold a live session");
|
|
assert.deepEqual(h.events.redirects, [], "no redirect — the browser state stays truthful");
|
|
assert.deepEqual(h.events.alerts, [LOGOUT_429_TEXT], "the server's error text is surfaced via the file's alert idiom");
|
|
});
|
|
|
|
test(`[${label}] a failed logout (500) is NOT presented as success`, async () => {
|
|
const h = makeFrontendHarness(source, startMarker, label);
|
|
await h.click(async () => errorResponse(500, LOGOUT_500_BODY));
|
|
assert.equal(h.events.cookieClears, 0, "no cookie deletion on a failed revocation");
|
|
assert.deepEqual(h.events.redirects, [], "no redirect");
|
|
assert.deepEqual(h.events.alerts, ["Failed to logout"], "the server's error text is surfaced");
|
|
});
|
|
|
|
test(`[${label}] an ok response WITHOUT the success flag is treated as failure (no redirect)`, async () => {
|
|
const h = makeFrontendHarness(source, startMarker, label);
|
|
await h.click(async () => okResponse({ revocationDegraded: false }));
|
|
assert.equal(h.events.cookieClears, 0, "no cookie deletion without the explicit success flag");
|
|
assert.deepEqual(h.events.redirects, [], "no redirect");
|
|
assert.deepEqual(h.events.alerts, ["Failed to log out"], "the honest fallback wording without server error text");
|
|
});
|
|
|
|
test(`[${label}] a network error is NOT presented as success`, async () => {
|
|
const h = makeFrontendHarness(source, startMarker, label);
|
|
await h.click(async () => { throw new Error("network down"); });
|
|
assert.equal(h.events.cookieClears, 0, "no cookie deletion when the request never completed");
|
|
assert.deepEqual(h.events.redirects, [], "no redirect");
|
|
assert.deepEqual(h.events.alerts, ["Failed to log out"], "the fallback wording on a network error");
|
|
});
|
|
|
|
test(`[${label}] the handler waits for the server's verdict BEFORE clearing cookies (order pin)`, async () => {
|
|
const h = makeFrontendHarness(source, startMarker, label);
|
|
await h.click(async () => okResponse(LOGOUT_OK_BODY));
|
|
assert.equal(h.events.order[0], "fetch", "the fetch resolved first");
|
|
assert.ok(h.events.order.indexOf("cookies") > 0, "cookie clearing happens after the fetch");
|
|
assert.ok(h.events.order.indexOf("redirect:/login") > 0, "the redirect happens after the fetch");
|
|
});
|
|
}
|