"use strict"; // adpanel:attack-detector-keying — source + behavior pins for the /login // attack detector's IP keying. Reads index.js as text, like the other audit // tests. // // Constraint under test: the login attack detector (markLoginTraffic's // ≥100-unique-source arming map and isAggressiveLoginIp's armed-mode // per-source brake) must key on the SAME /56-bucketed key the rest of the // login surface uses (loginThrottle.ipKey — ipKeyGenerator, // utils/login-throttle.js). "What is a source on /login" is one // responsibility with one derivation; the detector's raw getRequestIp key // was the drifted copy. ipKeyGenerator leaves IPv4 keys byte-identical to // the raw form, so IPv4 behavior is unchanged; IPv6 sources aggregate per // /56 with two documented deltas (see the adpanel:attack-detector-keying // comment in index.js): arming requires ≥100 distinct /56 prefixes (one // rotating host or one NAT64 egress can no longer self-arm global attack // mode), and the armed-mode brake binds per /56, closing the raw-keying // bypass where a host rotating addresses never exceeded 25 hits on any // single address. 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_JS = path.join(ROOT, "index.js"); const indexSource = fs.readFileSync(INDEX_JS, "utf8"); const { ipKeyGenerator } = require("express-rate-limit"); function indexOfOrThrow(needle, from = 0) { const idx = indexSource.indexOf(needle, from); assert.ok(idx >= 0, `expected source pin not found: ${needle}`); return idx; } // Extract a full top-level function declaration by brace matching (skipping // line/block comments and string literals), so behavior pins evaluate the // SHIPPED source rather than a re-typed copy of it. The `async` modifier is // part of the match: the detector functions became async with the // detector-cluster-shared mirror, and slicing from `function name(` alone // would drop the modifier while keeping the body's awaits (a syntax error). function extractFunction(name) { let start = indexSource.indexOf(`async function ${name}(`); if (start < 0) start = indexOfOrThrow(`function ${name}(`); let i = indexSource.indexOf("{", start); let depth = 0; let inLine = false; let inBlock = false; let quote = null; for (; 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++; else if (c === "}") { depth--; if (depth === 0) return indexSource.slice(start, i + 1); } } throw new Error(`unbalanced braces while extracting ${name}`); } const middlewareSource = extractFunction("loginAttackMiddleware"); const markLoginTrafficSource = extractFunction("markLoginTraffic"); const isLoginUnderAttackSource = extractFunction("isLoginUnderAttack"); const isAggressiveLoginIpSource = extractFunction("isAggressiveLoginIp"); // The canonical wrapping shape lives in utils/login-throttle.js; the detector // must wrap identically (modulo the request identifier). const loginThrottleSource = fs.readFileSync(path.join(ROOT, "utils", "login-throttle.js"), "utf8"); const canonicalWrap = 'ipKeyGenerator(String(getRequestIp(request) || "unknown"))'; // --------------------------------------------------------------------------- // Source pins: the detector derives its key through the bucketed wrapper, the // raw derivation is gone, and the change is documented. // --------------------------------------------------------------------------- test("the attack detector keys via ipKeyGenerator(getRequestIp(...)) in the login-throttle shape", () => { // The derivation lives INSIDE the middleware (one derivation feeding both // markLoginTraffic and isAggressiveLoginIp) — not re-derived per call site. assert.ok( middlewareSource.includes('const ip = ipKeyGenerator(String(getRequestIp(req) || "unknown"));'), "loginAttackMiddleware must derive its key through the canonical bucketed wrapper" ); // Same wrapping expression as the canonical login limiter // (utils/login-throttle.js), identifier-normalized (req vs request). const derived = middlewareSource.match(/const ip = ([^;]+);/)[1]; assert.strictEqual( derived.replace("(req)", "(request)"), canonicalWrap, "the detector's wrapping expression must equal the login throttle's (identifier-normalized)" ); assert.ok( loginThrottleSource.includes(`login-req:\${${canonicalWrap}}`), "utils/login-throttle.js must keep the canonical bucketed login-req shape" ); }); test("no raw getRequestIp key derivation remains in the detector functions", () => { // markLoginTraffic and isAggressiveLoginIp take the pre-derived key; they // must not call getRequestIp at all. for (const [name, fnSource] of [ ["markLoginTraffic", markLoginTrafficSource], ["isAggressiveLoginIp", isAggressiveLoginIpSource], ]) { assert.ok( !fnSource.includes("getRequestIp("), `${name} must not call getRequestIp directly (only the middleware derives the key)` ); assert.ok( !fnSource.includes("ipKeyGenerator("), `${name} must not re-derive the key (one derivation in the middleware)` ); } // The middleware calls getRequestIp exactly once, inside the wrapper — // the raw `const ip = getRequestIp(req);` form is gone. assert.strictEqual( (middlewareSource.match(/getRequestIp\(req\)/g) || []).length, 1, "the middleware derives the key exactly once, through the wrapper" ); assert.ok( !middlewareSource.includes("const ip = getRequestIp(req);"), "the raw key derivation must be gone" ); }); test("the detector documents the keying constraint with the adpanel tag", () => { const middlewareStart = indexOfOrThrow("function loginAttackMiddleware(req, res, next) {"); const derivationIdx = indexSource.indexOf("const ip = ipKeyGenerator", middlewareStart); assert.ok(derivationIdx > middlewareStart, "the middleware derives its key"); const tagIdx = indexOfOrThrow("// adpanel:attack-detector-keying", middlewareStart); assert.ok( tagIdx > middlewareStart && tagIdx < derivationIdx, "the adpanel:attack-detector-keying comment must sit with the middleware's key derivation" ); // And the comment must carry the two documented IPv6 deltas. const comment = indexSource.slice(tagIdx, derivationIdx); assert.ok(comment.includes("/56"), "the comment names the /56 bucketing"); assert.ok(comment.includes("arming"), "the comment documents the arming delta"); assert.ok(comment.includes("the same trade-off the login throttle already documents"), "the comment cites the shared trade-off"); assert.ok(comment.includes("offices share the per-source budget"), "the comment cites the login throttle's own wording"); }); // --------------------------------------------------------------------------- // Behavior pins on the derived key (shipped expression + real ipKeyGenerator): // same-/56 equality, IPv4 passthrough. // --------------------------------------------------------------------------- function buildKeyDeriver() { const expr = middlewareSource.match(/const ip = ([^;]+);/)[1]; return new Function( "ipKeyGenerator", "getRequestIp", `return (req) => ${expr};` )(ipKeyGenerator, (req) => req.sourceIp); } test("detector key: IPv6 addresses in one /56 collapse to one arming/brake key", () => { const keyOf = buildKeyDeriver(); const a = keyOf({ sourceIp: "2001:db8::1" }); const b = keyOf({ sourceIp: "2001:db8::fffe" }); const c = keyOf({ sourceIp: "2001:db8::ffff" }); assert.strictEqual(a, b, "rotating /64 addresses inside one /56 must share the detector key"); assert.strictEqual(a, c); assert.strictEqual(a, "2001:db8::/56", "the /56 bucket is the key"); assert.notStrictEqual(a, keyOf({ sourceIp: "2001:db8:0:100::1" }), "a different /56 is a different source"); }); test("detector key: IPv4 passthrough is byte-identical to the old raw keying", () => { const keyOf = buildKeyDeriver(); assert.strictEqual(keyOf({ sourceIp: "192.0.2.1" }), "192.0.2.1", "IPv4 keys unchanged from the raw form"); assert.notStrictEqual( keyOf({ sourceIp: "192.0.2.1" }), keyOf({ sourceIp: "192.0.2.99" }), "distinct IPv4 hosts stay distinct detector sources" ); assert.strictEqual(keyOf({ sourceIp: "" }), "unknown", "the empty source falls to the shared unknown key"); }); // --------------------------------------------------------------------------- // Behavior pins on the arming + brake semantics (shipped function bodies, // evaluated with injected maps/constants and a controllable clock). // --------------------------------------------------------------------------- function buildArmingHarness({ uniqueIps, ipMax, holdMs = 60000, windowMs = 1000, ipWindowMs = 3000, mapMax = 10000 }) { let clock = 1_000_000; const Date = { now: () => clock }; const loginAttackIps = new Map(); const loginAttackIpHits = new Map(); // adpanel:detector-cluster-shared — the shipped detector functions now // mirror into the cluster-wide shared counters; this harness pins the // FAIL posture, so the stub reports the shared store unavailable and the // functions fall back to the per-process Maps exactly as before the // mirror existed. The shared-side behavior is pinned in // detector-cluster-shared.test.js. const sharedUnavailableStub = { armWindowBucket: async () => ({ sharedAvailable: false, uniqueSources: 0 }), brakeHit: async () => ({ sharedAvailable: false, hits: 0 }), }; const factory = new Function( "loginAttackIps", "LOGIN_ATTACK_WINDOW_MS", "LOGIN_MAP_MAX_SIZE", "LOGIN_ATTACK_UNIQUE_IPS", "LOGIN_ATTACK_HOLD_MS", "loginAttackIpHits", "LOGIN_ATTACK_IP_WINDOW_MS", "LOGIN_ATTACK_IP_MAX", "Date", "loginSharedCounters", `let loginUnderAttackUntil = 0; ${markLoginTrafficSource} ${isLoginUnderAttackSource} ${isAggressiveLoginIpSource} return { markLoginTraffic, isLoginUnderAttack, isAggressiveLoginIp };` ); const harness = factory( loginAttackIps, windowMs, mapMax, uniqueIps, holdMs, loginAttackIpHits, ipWindowMs, ipMax, Date, sharedUnavailableStub ); return { ...harness, keys: loginAttackIps, advance: (ms) => { clock += ms; }, }; } test("arming: one /56 with rotating addresses can no longer arm global attack mode; distinct /56s still arm", async () => { const h = buildArmingHarness({ uniqueIps: 3 }); const keyOf = (ip) => ipKeyGenerator(String(ip || "unknown")); await h.markLoginTraffic(keyOf("2001:db8::1")); await h.markLoginTraffic(keyOf("2001:db8::2")); await h.markLoginTraffic(keyOf("2001:db8::ffff")); assert.strictEqual(h.keys.size, 1, "three rotating addresses inside one /56 count as ONE source"); assert.ok(h.keys.has("2001:db8::/56"), "the arming key is the /56 bucket"); assert.ok(!h.isLoginUnderAttack(), "one /56 cannot single-handedly arm global attack mode"); await h.markLoginTraffic(keyOf("2001:db8:0:100::1")); await h.markLoginTraffic(keyOf("2001:db8:0:200::1")); assert.ok(h.isLoginUnderAttack(), "three distinct /56 prefixes arm global attack mode"); h.advance(70000); assert.ok(!h.isLoginUnderAttack(), "the arming hold expires"); }); test("arming: IPv4 arming is unchanged by the keying change", async () => { const h = buildArmingHarness({ uniqueIps: 3 }); await h.markLoginTraffic("192.0.2.1"); await h.markLoginTraffic("192.0.2.99"); await h.markLoginTraffic("192.0.2.200"); assert.ok(h.isLoginUnderAttack(), "three distinct IPv4 sources arm exactly as before"); }); test("armed-mode brake: 25 rotating addresses in one /56 stay under it, the 26th trips (bypass closed)", async () => { const h = buildArmingHarness({ uniqueIps: 3, ipMax: 25 }); const keyOf = (ip) => ipKeyGenerator(String(ip || "unknown")); // One host rotating 25 /64 addresses inside its /56: raw keying gave every // address its own hit counter, so this flood NEVER tripped the brake. for (let i = 1; i <= 25; i++) { assert.ok(!(await h.isAggressiveLoginIp(keyOf(`2001:db8::${i}`))), `hit ${i} from a fresh rotating address must stay under the brake`); } assert.ok(await h.isAggressiveLoginIp(keyOf("2001:db8::ffff")), "the 26th hit in the same /56 trips the armed-mode brake"); }); test("armed-mode brake: IPv4 passthrough behavior is unchanged (25 hits stay under, the 26th trips)", async () => { const h = buildArmingHarness({ uniqueIps: 3, ipMax: 25 }); for (let i = 1; i <= 25; i++) { assert.ok(!(await h.isAggressiveLoginIp("192.0.2.1")), `IPv4 hit ${i} must stay under the brake`); } assert.ok(await h.isAggressiveLoginIp("192.0.2.1"), "the 26th hit from one IPv4 trips the brake exactly as before"); }); test("armed-mode brake: the 3s sliding window still prunes per /56", async () => { const h = buildArmingHarness({ uniqueIps: 3, ipMax: 25 }); const keyOf = (ip) => ipKeyGenerator(String(ip || "unknown")); for (let i = 1; i <= 26; i++) await h.isAggressiveLoginIp(keyOf(`2001:db8::${i}`)); h.advance(4000); assert.ok(!(await h.isAggressiveLoginIp(keyOf("2001:db8::1"))), "hits older than the 3s window are pruned; the bucket restarts"); for (let i = 1; i <= 25; i++) await h.isAggressiveLoginIp(keyOf(`2001:db8::${i}`)); assert.ok(await h.isAggressiveLoginIp(keyOf("2001:db8::ffff")), "a fresh 26-hit burst in the window trips again"); }); // --------------------------------------------------------------------------- // Full-middleware behavior pin: the orchestration around the extracted key // (shipped middleware body, injected collaborators). // --------------------------------------------------------------------------- // The middleware is now async (adpanel:detector-cluster-shared: it awaits // the best-effort shared-counter mirrors). Harness collaborator signature // gains ANY_CAPTCHA_ENABLED + isLoginCaptchaGateArmedForIpShared (the // per-request gate verdict the middleware stashes; these keying tests set // the captcha flag false so the stash branch is inert here — the stash and // shared behavior are pinned in detector-cluster-shared.test.js). function buildMiddlewareHarness({ armed }) { // adpanel:login-retry-after — conscious harness update (additive): the // shipped middleware body now DERIVES its Retry-After argument from // LOGIN_ATTACK_IP_WINDOW_MS (Math.ceil(window/1000)) instead of a // hard-coded 5, so the constant must be in the harness's scope. The // shipped default (3000) is injected; the derivation itself is pinned in // tests/detector-cluster-shared.test.js. // adpanel:config-stat-revalidation — conscious harness update (additive): // the shipped body revalidates the hot-swapped captcha config from .env at // the top of its try block; a no-op is injected here (the revalidation's // own behavior is pinned in tests/config-stat-revalidation-consumers.test.js). return new Function( "ipKeyGenerator", "getRequestIp", "markLoginTraffic", "isLoginUnderAttack", "isAggressiveLoginIp", "sendLoginRateLimited", "securityLog", "ANY_CAPTCHA_ENABLED", "isLoginCaptchaGateArmedForIpShared", "LOGIN_ATTACK_IP_WINDOW_MS", "revalidateCaptchaConfigFromDisk", `${middlewareSource} return loginAttackMiddleware;` )( ipKeyGenerator, (req) => req.sourceIp, () => {}, // arming map fed with the derived key (pinned separately above) () => armed, (() => { const hits = new Map(); return (key) => { hits.set(key, (hits.get(key) || 0) + 1); return hits.get(key) > 25; }; })(), (req, res, log, reason) => { res.refusedReason = reason; res.setHeader("Retry-After", "5"); }, () => {}, false, async () => false, 3000, () => {} ); } test("middleware: disarmed mode never refuses and the arming map sees the single /56 key for the whole stream", async () => { const marked = []; // adpanel:config-stat-revalidation — conscious harness update (additive): // revalidateCaptchaConfigFromDisk is injected as a no-op (its behavior is // pinned in tests/config-stat-revalidation-consumers.test.js). const middleware = new Function( "ipKeyGenerator", "getRequestIp", "markLoginTraffic", "isLoginUnderAttack", "isAggressiveLoginIp", "sendLoginRateLimited", "securityLog", "ANY_CAPTCHA_ENABLED", "isLoginCaptchaGateArmedForIpShared", "LOGIN_ATTACK_IP_WINDOW_MS", "revalidateCaptchaConfigFromDisk", `${middlewareSource} return loginAttackMiddleware;` )( ipKeyGenerator, (req) => req.sourceIp, (key) => marked.push(key), () => false, () => true, // brake "trips" on every call — arming is what must hold it back (req, res, log, reason) => { res.refusedReason = reason; }, () => {}, false, async () => false, 3000, // adpanel:login-retry-after — the shipped body derives its Retry-After from this constant (see buildMiddlewareHarness) () => {} ); let passed = 0; for (let i = 1; i <= 30; i++) { const res = { locals: {}, setHeader() {} }; await middleware({ sourceIp: `2001:db8::${i}` }, res, () => { passed += 1; }); assert.strictEqual(res.locals.underAttack, false, "disarmed mode is surfaced as such"); assert.strictEqual(res.refusedReason, undefined, "disarmed mode must not refuse even aggressive sources"); } assert.strictEqual(passed, 30, "all requests pass through when not under attack"); assert.strictEqual(marked.length, 30, "the detector keeps seeing the full request stream (arming needs it)"); for (const key of marked) assert.strictEqual(key, "2001:db8::/56", "the arming map is fed the single /56 bucket key"); }); test("middleware: armed mode 429s the 26th request of a rotating-/56 flood through the shared responder", async () => { const middleware = buildMiddlewareHarness({ armed: true }); let passed = 0; let refused = 0; for (let i = 1; i <= 26; i++) { const res = { locals: {}, setHeader() {} }; await middleware({ sourceIp: `2001:db8::${i}` }, res, () => { passed += 1; }); if (res.refusedReason) refused += 1; } assert.strictEqual(passed, 25, "the first 25 rotating-address hits pass"); assert.strictEqual(refused, 1, "the 26th hit of the /56 flood is refused in armed mode"); }); test("middleware: armed mode leaves distinct /56s untouched and refuses the 26th hit of one IPv4 (unchanged)", async () => { const middleware = buildMiddlewareHarness({ armed: true }); let refused = 0; for (let i = 1; i <= 30; i++) { const res = { locals: {}, setHeader() {} }; await middleware({ sourceIp: `2001:db8:${i}::1` }, res, () => {}); if (res.refusedReason) refused += 1; } assert.strictEqual(refused, 0, "30 distinct /56 prefixes each stay under the per-source brake"); let v4Refused = 0; for (let i = 1; i <= 26; i++) { const res = { locals: {}, setHeader() {} }; await middleware({ sourceIp: "192.0.2.1" }, res, () => {}); if (res.refusedReason) v4Refused += 1; } assert.strictEqual(v4Refused, 1, "the 26th hit from one IPv4 is refused exactly as under the raw keying"); });