Initial upload to Gitea

This commit is contained in:
antonn committed 2026-11-30 16:32:37 +00:00
1 parent 78193254ad
commit 8478998cae
1485 files changed
+461025 -42348

No files matched your search

+510
View File
@@ -0,0 +1,510 @@
"use strict";
// adpanel:store-fallback-valid-hits — source + behavior pins for the shared
// rate-limit Redis store wrapper's error fallback.
//
// Constraint under test: on a mid-run Redis error the wrapper's sendCommand
// returns a FAKE SUCCESS reply instead of rejecting (the designed fail-open —
// these limiters are abuse brakes, not auth controls). That fake reply must
// satisfy express-rate-limit's validation contract: positiveHits rejects any
// totalHits < 1 (INCR is monotone, so a 0 reply can only mean an invalid
// reply). In express-rate-limit v8.5.2 that ERR_ERL_INVALID_HITS throw is
// caught and logged by the validation wrapper — it never reaches next(error)
// — so with a 0 fallback every request through every limiter logged the
// validation error (log amplification) and the hit went uncounted (used
// reads 0): the fail-open still happened, by accident rather than by design.
// (The /api/* 500 residual was the OTHER error class — the boot-down SCRIPT
// LOAD rejection escaping increment(), closed by passOnStoreError: true;
// second constraint below.) The fallback therefore returns ONE transient,
// never-persisted hit in a fresh fallback window: totalHits 1 passes
// validation, 1 <= max keeps the request allowed, and the designed fail-open
// runs clean.
//
// Two consumer contracts share the ONE wrapper (buildSharedRateLimitRedisStore):
// * express-rate-limit middleware (fallbackHits=1, the default) — needs the
// validation-valid reply above;
// * login-throttle's three reservation counters (fallbackHits=0, ONLY via
// loginThrottleStoreFactory) — its own arithmetic binds "bump() returns 0
// only on a store error" as the fail-closed reservation sentinel; giving
// those counters a 1-on-error reply would ADMIT a login on a degraded
// store, flipping the reservation fail-open. Never point the 0-sentinel
// factory at express-rate-limit middleware.
//
// Second constraint pinned here (same tag): the /api/* globalLimiter must set
// passOnStoreError: true like every other limiter. Without it, the one shape
// the wrapper cannot absorb — Redis down since boot, where the store's
// un-awaited SCRIPT LOAD rejects and rate-limit-redis' retry throws out of
// increment() — rethrows out of the middleware and 500s every /api/* request,
// contradicting the limiter's documented fail-open-on-store-errors role.
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 loginThrottleSource = fs.readFileSync(path.join(ROOT, "utils", "login-throttle.js"), "utf8");
const { rateLimit: expressRateLimit, MemoryStore, ipKeyGenerator } = require("express-rate-limit");
const { RedisStore: RealRateLimitRedisStore } = require("rate-limit-redis");
const { createLoginThrottle } = require("../utils/login-throttle.js");
const FALLBACK_WINDOW_MS = 5 * 60 * 1000;
function indexOfOrThrow(needle, from = 0) {
const idx = indexSource.indexOf(needle, from);
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
return idx;
}
function countOccurrences(needle) {
let count = 0;
let pos = 0;
for (;;) {
const idx = indexSource.indexOf(needle, pos);
if (idx < 0) return count;
count += 1;
pos = idx + needle.length;
}
}
// Brace matcher that skips line/block comments and string literals, so the
// extracted text is the shipped source (same technique as
// tests/limiter-ipv6-bucketing.test.js). Returns the index of the `}` that
// closes the `{` at openBraceIndex.
function findBalancedClose(src, openBraceIndex) {
let depth = 0;
let inLine = false;
let inBlock = false;
let quote = null;
for (let i = openBraceIndex; i < src.length; i++) {
const c = src[i];
const n = src[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 while extracting store wrapper");
}
// Extract the object literal passed to `new RateLimitRedisStore({...})` that
// follows `marker` (e.g. "const buildAssistantRedisStore = "). The extracted
// text keeps the factory's free variables (prefix/client/fallbackHits/...,
// redisClient, security) — bind them when evaluating so the behavior pins
// exercise the SHIPPED sendCommand bodies, not re-typed copies.
function extractStoreObject(marker) {
const markerAt = indexOfOrThrow(marker);
const newAt = indexSource.indexOf("new RateLimitRedisStore(", markerAt);
assert.ok(newAt > markerAt, `expected a RateLimitRedisStore construction after: ${marker}`);
const open = indexSource.indexOf("{", newAt);
assert.ok(open > newAt, "store construction must open an options object");
const close = findBalancedClose(indexSource, open);
return indexSource.slice(open, close + 1);
}
// Evaluate an extracted store options object against the REAL rate-limit-redis
// RedisStore, binding the wrapper's free variables. console is always stubbed
// so error-path logging never leaks into test output.
function evalStoreObject(objText, freeVars = {}) {
const names = ["RateLimitRedisStore", "console", ...Object.keys(freeVars)];
const values = [RealRateLimitRedisStore, { error() {} }, ...Object.values(freeVars)];
const build = new Function(...names, `return new RateLimitRedisStore(${objText});`);
return build(...values);
}
// rate-limit-redis' constructor fires SCRIPT LOAD for its two Lua scripts
// un-awaited. With a stub client that fails them, those promises reject after
// the test body finished (loadIncrementScript's "unexpected reply" TypeError);
// the production retry chain awaits the increment sha per request, but the
// get sha is only awaited by store.get(). Marking both handled in the harness
// keeps the pins free of harness-only unhandledRejection noise.
function silenceBootScriptRejections(store) {
store.incrementScriptSha?.catch(() => {});
store.getScriptSha?.catch(() => {});
}
// A stub node-redis-style client dispatching on the command head. Handlers
// receive the full safeArgs array (["SCRIPT","LOAD",lua] / ["EVALSHA",sha,...]).
function makeRedisStub(handlers) {
return {
sent: [],
async sendCommand(args) {
this.sent.push(args);
const head = args[0];
const handler = handlers[head] ?? handlers.default;
if (!handler) throw new Error(`unexpected stub command: ${head}`);
return handler(args);
},
};
}
const connectionError = () => { throw new Error("Stream isn't writeable and enableOfflineQueue options is false"); };
// The shape that must self-heal through rate-limit-redis' retryableIncrement:
// the first EVALSHA lands after a Redis restart and the server answers
// NOSCRIPT (script cache flushed, keys intact).
const noscriptError = () => { throw new Error("NOSCRIPT No matching script. Please use EVAL."); };
// ---------------------------------------------------------------------------
// Source pins — the fallback shape itself.
// ---------------------------------------------------------------------------
test("every error fallback returns a validation-valid hit count: no [0, ...] reply remains", () => {
// The two literal middleware-bound wrappers (the /api global limiter's
// safeRedisStore and the assistant limiter factory) return the literal
// single-hit placeholder.
assert.strictEqual(countOccurrences("return [1, windowMs];"), 2,
"safeRedisStore and buildAssistantRedisStore must each return the [1, windowMs] placeholder exactly once");
// The shared per-limiter factory shapes the fallback through fallbackHits
// and defaults it to the validation-valid 1.
indexOfOrThrow("return [fallbackHits, fallbackWindowMs];");
indexOfOrThrow("fallbackWindowMs = 5 * 60 * 1000, client = redisClient, fallbackHits = 1");
// The audited fake-success shape is gone everywhere (HEAD returned
// [0, Date.now() + windowMs] — a 0 hit count AND an epoch-ms resetTime).
assert.strictEqual(countOccurrences("return [0,"), 0,
"no store wrapper may answer a store error with a 0 totalHits reply (ERR_ERL_INVALID_HITS caught and logged per request per limiter — log amplification)");
assert.strictEqual(countOccurrences("Date.now() + windowMs]"), 0,
"no fallback may return an epoch-ms resetTime (parseScriptResponse adds the reply's RELATIVE ms TTL)");
});
test("the fallback shape carries the adpanel:store-fallback-valid-hits constraint at every site", () => {
// safeRedisSendCommand (the hardened wrapper), buildAssistantRedisStore
// (behavior matrix + shared-factory note), buildSharedRateLimitRedisStore
// (the fallbackHits contract) — and, since adpanel:rate-limit-policy-owner,
// the /api/* global limiter's own options block, which now lives in the ONE
// policy owner (services/global-rate-limit-owner.js).
const ownerSource = fs.readFileSync(path.join(ROOT, "services", "global-rate-limit-owner.js"), "utf8");
assert.ok(countOccurrences("// adpanel:store-fallback-valid-hits") + (ownerSource.match(/\/\/ adpanel:store-fallback-valid-hits/g) || []).length >= 4,
"each wrapper fallback documents why 1 and not 0");
assert.ok(indexSource.includes("totalHits >= 1: express-rate-limit's positiveHits validation treats 0"),
"the constraint comment must name the validation contract the reply must satisfy");
});
test("the login throttle's reservation counters keep the fail-closed 0 sentinel; middleware never gets it", () => {
// The split factories: middleware stores ride the default (1), the throttle's
// three reservation counters override to 0 (its error sentinel).
indexOfOrThrow("const loginThrottleStoreFactory = redisClient ? (prefix, windowMs) => buildSharedRateLimitRedisStore(prefix, windowMs, redisClient, 0) : null;");
indexOfOrThrow("const loginRequestLimiterStoreFactory = redisClient ? (prefix, windowMs) => buildSharedRateLimitRedisStore(prefix, windowMs) : null;");
assert.strictEqual(countOccurrences("buildSharedRateLimitRedisStore(prefix, windowMs, redisClient, 0)"), 1,
"exactly ONE factory may pass the 0 sentinel (the login throttle's reservation counters)");
assert.ok(indexSource.includes("point the 0-sentinel factory at express-rate-limit middleware"),
"the 0-sentinel factory must document that middleware would re-break positiveHits");
assert.ok(indexSource.includes("bump() returns 0 only on a store error"),
"the sentinel contract must stay tied to login-throttle's own arithmetic");
});
// ---------------------------------------------------------------------------
// Source pins — passOnStoreError coverage (every limiter fails open on the
// increment() rejection the wrapper cannot absorb).
// ---------------------------------------------------------------------------
test("the /api/* globalLimiter sets passOnStoreError: true and documents the shape it covers", () => {
// adpanel:rate-limit-policy-owner — the /api/* global limiter's options now
// live in the ONE policy owner (services/global-rate-limit-owner.js); the
// pin consciously tracks the shipped construction there, preserving the
// intent: the limiter actually wired to the hardened fallback wrapper
// (via the injected redisSendCommand closure) must fail open on the
// increment() rejection that wrapper cannot absorb.
const ownerSource = fs.readFileSync(path.join(ROOT, "services", "global-rate-limit-owner.js"), "utf8");
const open = ownerSource.indexOf("const limiter = rateLimit({");
assert.ok(open >= 0, "the owner's global limiter construction not found");
const objOpen = ownerSource.indexOf("{", open);
const objClose = findBalancedClose(ownerSource, objOpen);
const globalLimiterOptions = ownerSource.slice(objOpen, objClose + 1);
assert.ok(/passOnStoreError:\s*true/.test(globalLimiterOptions),
"the /api/* globalLimiter must fail open when increment() rejects (Redis down since boot 500-ed every /api/* request)");
assert.ok(globalLimiterOptions.includes("// adpanel:store-fallback-valid-hits"),
"the globalLimiter documents the passOnStoreError constraint under the same tag");
assert.ok(ownerSource.includes("sendCommand: redisSendCommand,"),
"the pin targets the limiter actually wired to the fallback wrapper (the store construction diales through the injected hardened sendCommand closure)");
// And index.js must inject the SAME hardened closure the old safeRedisStore
// used — no second client wrapper.
assert.ok(indexSource.includes("redisSendCommand: safeRedisSendCommand,"),
"index.js must inject the hardened safeRedisSendCommand closure into the owner");
});
test("every inline and extracted rateLimit construction carries passOnStoreError: true (coverage matrix)", () => {
const sources = [
["index.js", indexSource],
["services/global-rate-limit-owner.js", fs.readFileSync(path.join(ROOT, "services", "global-rate-limit-owner.js"), "utf8")],
["utils/login-throttle.js", loginThrottleSource],
];
let constructions = 0;
for (const [file, source] of sources) {
for (const match of source.matchAll(/rateLimit\(\{/g)) {
constructions += 1;
const open = source.indexOf("{", match.index);
const options = source.slice(open, findBalancedClose(source, open) + 1);
assert.ok(!/passOnStoreError:\s*false/.test(options), `${file}: no limiter may disable the fail-open store policy`);
if (/^\{\s*\.\.\.options,/.test(options)) {
assert.equal(file, "utils/login-throttle.js", "only the shared account factory may inherit the common options");
const commonStart = source.indexOf("const options = {", source.indexOf("function createAccountOperationLimiter("));
const commonOpen = source.indexOf("{", commonStart);
const common = source.slice(commonOpen, findBalancedClose(source, commonOpen) + 1);
assert.match(common, /passOnStoreError:\s*true,/, "both account tiers inherit the common fail-open policy");
} else {
assert.equal((options.match(/passOnStoreError:\s*true/g) || []).length, 1, `${file}: every limiter must declare exactly one fail-open store option`);
}
}
}
assert.ok(constructions >= 50, `expected the full inline and extracted limiter fleet, found ${constructions}`);
assert.ok(indexSource.includes("const settingsRateLimiters = createSettingsRateLimiters("), "the application must bind the extracted settings policies");
const settingsSource = fs.readFileSync(path.join(ROOT, "services", "settings-rate-limiters.js"), "utf8");
assert.ok(settingsSource.includes("createAccountOperationLimiter({"), "settings policies must use the shared account factory, not private counters");
});
test("the login-request limiter in utils/login-throttle.js also fails open on store errors", () => {
// The login request budget and both account-verification tiers use
// middleware; the credential reservation still owns its fail-closed
// 0-on-error arithmetic separately.
assert.ok(loginThrottleSource.includes("passOnStoreError: true, // abuse brake, not an auth control"),
"createLoginRequestLimiter must fail open on store errors");
assert.strictEqual((loginThrottleSource.match(/rateLimit\(\{/g) || []).length, 3,
"the module constructs the request budget and the two shared verification tiers");
const verificationStart = loginThrottleSource.indexOf("function createAccountOperationLimiter(");
const verificationEnd = loginThrottleSource.indexOf("function createLoginThrottle(", verificationStart);
assert.ok(verificationStart >= 0 && verificationEnd > verificationStart);
const verification = loginThrottleSource.slice(verificationStart, verificationEnd);
assert.match(verification, /passOnStoreError:\s*true,/);
for (const tier of ["accountLimiter", "sessionLimiter"]) {
assert.match(verification, new RegExp(`const ${tier} = rateLimit\\(\\{\\s*\\.\\.\\.options,`),
`${tier} must inherit the common store-error policy`);
}
});
// ---------------------------------------------------------------------------
// Behavior pins — the SHIPPED fallback bodies exercised through the real
// rate-limit-redis RedisStore.
// ---------------------------------------------------------------------------
test("shared factory (default): mid-run Redis error resolves totalHits 1 with a relative-ms resetTime", async () => {
const objText = extractStoreObject("const buildSharedRateLimitRedisStore = ");
// SCRIPT LOAD succeeds at construction; the mid-run EVALSHA dies on a
// connection-class error -> the wrapper's fallback answers.
const client = makeRedisStub({ SCRIPT: () => "stubsha", EVALSHA: connectionError, default: connectionError });
const store = evalStoreObject(objText, { prefix: "t:", fallbackWindowMs: FALLBACK_WINDOW_MS, client, fallbackHits: 1 });
silenceBootScriptRejections(store);
store.init({ windowMs: FALLBACK_WINDOW_MS });
const reply = await store.increment("k1");
assert.strictEqual(reply.totalHits, 1, "the error fallback must read as ONE transient hit (validation-valid, still allowed)");
const delta = reply.resetTime.getTime() - Date.now();
assert.ok(delta > 0 && delta < 2 * FALLBACK_WINDOW_MS,
`resetTime must be now + the fallback window (relative ms), got +${delta}ms — an epoch-ms reply would land near year-2083`);
});
test("shared factory (fallbackHits=0, the login-throttle shape): the error reply stays the 0 sentinel", async () => {
const objText = extractStoreObject("const buildSharedRateLimitRedisStore = ");
const client = makeRedisStub({ SCRIPT: () => "stubsha", EVALSHA: connectionError, default: connectionError });
const store = evalStoreObject(objText, { prefix: "login-fail-ip:", fallbackWindowMs: FALLBACK_WINDOW_MS, client, fallbackHits: 0 });
silenceBootScriptRejections(store);
store.init({ windowMs: FALLBACK_WINDOW_MS });
const reply = await store.increment("k1");
assert.strictEqual(reply.totalHits, 0,
"the throttle's reservation counters must keep reading the store error as 0 (its fail-closed sentinel)");
});
test("NOSCRIPT is still rethrown so retryableIncrement self-heals (script cache flushed, keys intact)", async () => {
const objText = extractStoreObject("const buildSharedRateLimitRedisStore = ");
let evals = 0;
const client = makeRedisStub({
SCRIPT: () => "stubsha",
EVALSHA: async () => {
evals += 1;
if (evals === 1) noscriptError();
return [3, FALLBACK_WINDOW_MS];
},
default: connectionError,
});
const store = evalStoreObject(objText, { prefix: "t:", fallbackWindowMs: FALLBACK_WINDOW_MS, client, fallbackHits: 1 });
silenceBootScriptRejections(store);
store.init({ windowMs: FALLBACK_WINDOW_MS });
const reply = await store.increment("k1");
assert.strictEqual(reply.totalHits, 3, "the retry after SCRIPT LOAD must land the real counter");
assert.ok(evals >= 2, "the NOSCRIPT EVALSHA must have been retried, not swallowed by the fallback");
});
test("shared factory with Redis down since boot: increment() REJECTS (the shape only passOnStoreError can absorb)", async () => {
const objText = extractStoreObject("const buildSharedRateLimitRedisStore = ");
const client = makeRedisStub({ default: connectionError });
const store = evalStoreObject(objText, { prefix: "t:", fallbackWindowMs: FALLBACK_WINDOW_MS, client, fallbackHits: 1 });
silenceBootScriptRejections(store);
store.init({ windowMs: FALLBACK_WINDOW_MS });
await assert.rejects(() => store.increment("k1"), (err) => err instanceof TypeError,
"with the script never loaded the retry chain throws out of increment() — exactly the shape passOnStoreError exists for");
});
test("assistant limiter factory: mid-run Redis error resolves totalHits 1, relative-ms resetTime", async () => {
const objText = extractStoreObject("const buildAssistantRedisStore = () => ");
const redisClient = makeRedisStub({ SCRIPT: () => "stubsha", EVALSHA: connectionError, default: connectionError });
const store = evalStoreObject(objText, { redisClient });
silenceBootScriptRejections(store);
store.init({ windowMs: FALLBACK_WINDOW_MS });
const reply = await store.increment("assistant-completion-account:user@example.com");
assert.strictEqual(reply.totalHits, 1, "the assistant wrappers share the validation-valid placeholder");
const delta = reply.resetTime.getTime() - Date.now();
assert.ok(delta > 0 && delta < 2 * FALLBACK_WINDOW_MS, `resetTime must stay relative-ms, got +${delta}ms`);
});
test("safeRedisStore sendCommand: a connection error answers [1, 120000]; NOSCRIPT propagates", async () => {
// The /api global limiter's wrapper declares its sendCommand as the named
// const safeRedisSendCommand (extracted and evaluated below), then hands it
// to the store by reference — exercise the SHIPPED arrow wired into the
// SHIPPED store object.
const markerAt = indexOfOrThrow("const safeRedisSendCommand = ");
const arrowAt = indexSource.indexOf("async (...args) =>", markerAt);
assert.ok(arrowAt > markerAt && arrowAt < markerAt + 120, "safeRedisSendCommand must be an async (...args) arrow");
const open = indexSource.indexOf("{", arrowAt);
const close = findBalancedClose(indexSource, open);
const arrowSource = indexSource.slice(arrowAt, close + 1);
const makeSendCommand = new Function("redisClient", "security", "console", `return (${arrowSource});`);
const throwingClient = makeRedisStub({ default: connectionError });
const sendCommand = makeSendCommand(throwingClient, { window_seconds: "120" }, { error() {} });
const reply = await sendCommand("EVALSHA", "sha", "1", "k", "0", "120000");
assert.deepStrictEqual(reply, [1, 120000],
"the /api global limiter's fallback must answer one hit over the security.window_seconds window");
const noscriptClient = makeRedisStub({ EVALSHA: noscriptError, default: noscriptError });
const healingSendCommand = makeSendCommand(noscriptClient, { window_seconds: "120" }, { error() {} });
await assert.rejects(() => healingSendCommand("EVALSHA", "sha", "1", "k", "0", "120000"),
/NOSCRIPT/, "NOSCRIPT must reach retryableIncrement for its self-heal, never the fallback");
});
// ---------------------------------------------------------------------------
// Behavior pins — end-to-end through the REAL express-rate-limit middleware:
// the fallback keeps the request allowed WITHOUT the ERR_ERL_INVALID_HITS
// throw, and the old 0-reply shape demonstrably threw (the regression this
// fix removes).
// ---------------------------------------------------------------------------
function makeRequestRecorder() {
const out = { nextCalled: false, error: undefined, rateLimit: undefined };
const next = (err) => { out.nextCalled = true; out.error = err; };
const res = { headersSent: false, statusCode: 200 };
return { out, next, res };
}
function buildMiddleware(store, logger) {
return expressRateLimit({
windowMs: FALLBACK_WINDOW_MS,
limit: 10,
standardHeaders: false,
legacyHeaders: false,
store,
keyGenerator: (req) => req.keyOverride,
passOnStoreError: true,
logger,
// Keep ONLY positiveHits enabled: the pin must exercise the exact
// validation whose ERR_ERL_INVALID_HITS fired on the old 0-reply.
validate: { default: false, positiveHits: true },
});
}
function buildMiddlewareStore(storeObjText, freeVars) {
const store = evalStoreObject(storeObjText, freeVars);
silenceBootScriptRejections(store);
store.init({ windowMs: FALLBACK_WINDOW_MS });
return store;
}
test("middleware end-to-end: a mid-run Redis error passes the request with rateLimit.used = 1 and no error", async () => {
const objText = extractStoreObject("const buildSharedRateLimitRedisStore = ");
const client = makeRedisStub({ SCRIPT: () => "stubsha", EVALSHA: connectionError, default: connectionError });
const store = buildMiddlewareStore(objText, { prefix: "t:", fallbackWindowMs: FALLBACK_WINDOW_MS, client, fallbackHits: 1 });
const logged = [];
const middleware = buildMiddleware(store, { error: (e) => logged.push(e?.code || String(e)), warn() {} });
const { out, next, res } = makeRequestRecorder();
const req = { keyOverride: "t:req-1", ip: "192.0.2.1", method: "GET", path: "/" };
await middleware(req, res, next);
assert.ok(out.nextCalled, "the request must be allowed (designed fail-open, now validation-clean)");
assert.strictEqual(out.error, undefined, "positiveHits(1) must NOT throw — the old fallback logged ERR_ERL_INVALID_HITS per request");
assert.deepStrictEqual(logged, [], "the shipped fallback must be SILENT — no validation error, no log amplification");
assert.strictEqual(req.rateLimit.used, 1, "the fallback counts as the single transient hit");
assert.strictEqual(req.rateLimit.remaining, 9, "1 <= max keeps the limiter's arithmetic intact");
});
test("middleware end-to-end: Redis down since boot passes through passOnStoreError (no 500, no error)", async () => {
const objText = extractStoreObject("const buildSharedRateLimitRedisStore = ");
const client = makeRedisStub({ default: connectionError });
const store = buildMiddlewareStore(objText, { prefix: "t:", fallbackWindowMs: FALLBACK_WINDOW_MS, client, fallbackHits: 1 });
const middleware = buildMiddleware(store);
const { out, next, res } = makeRequestRecorder();
await middleware({ keyOverride: "t:req-2", ip: "192.0.2.1", method: "GET", path: "/" }, res, next);
assert.ok(out.nextCalled, "increment() rejecting must fail open through passOnStoreError: true");
assert.strictEqual(out.error, undefined, "no error may reach next() — without the option this rejection 500-ed the route");
});
test("middleware end-to-end (regression direction): the old 0-reply amplifies ERR_ERL_INVALID_HITS into the logs on every degraded request", async () => {
// The OLD fake-success shape: the store RESOLVES with totalHits 0. In
// express-rate-limit v8.5.2 positiveHits throws ERR_ERL_INVALID_HITS and
// the validation wrapper CATCHES AND LOGS it (the audit's residual (a)):
// one amplified error log per request per limiter on a degraded worker,
// poisoning the reply shape too (used 0). The shipped 1-reply fallback is
// the log-free fail-open pinned above.
const client = makeRedisStub({ SCRIPT: () => "stubsha", EVALSHA: () => [0, FALLBACK_WINDOW_MS], default: () => [0, FALLBACK_WINDOW_MS] });
const store = new RealRateLimitRedisStore({
prefix: "t:",
sendCommand: async (...args) => client.sendCommand(args),
});
silenceBootScriptRejections(store);
store.init({ windowMs: FALLBACK_WINDOW_MS });
const logged = [];
const middleware = buildMiddleware(store, { error: (e) => logged.push(e?.code || String(e)), warn() {} });
const { out, next, res } = makeRequestRecorder();
const req = { keyOverride: "t:req-3", ip: "192.0.2.1", method: "GET", path: "/" };
await middleware(req, res, next);
assert.ok(out.nextCalled, "the request still passes (fail-open) — but noisily");
assert.deepStrictEqual(logged, ["ERR_ERL_INVALID_HITS"],
"the 0-reply is exactly what positiveHits rejects — the audited log-amplification mechanism");
assert.strictEqual(req.rateLimit.used, 0, "the degraded reply also breaks the limiter's own accounting (used reads 0)");
});
// ---------------------------------------------------------------------------
// Behavior pin — the login throttle's reservation against the SAME wrapper:
// a degraded store must refuse admission (fail closed) and refund everything.
// ---------------------------------------------------------------------------
test("login throttle reserve path on a degraded store: refuses with reason 'store' (fail-closed posture unchanged)", async () => {
const objText = extractStoreObject("const buildSharedRateLimitRedisStore = ");
const client = makeRedisStub({ default: connectionError });
const throttle = createLoginThrottle({
// The shipped loginThrottleStoreFactory wiring: the 0-sentinel override
// over the ONE shared wrapper.
buildStore: (prefix, windowMs) => {
const store = evalStoreObject(objText, { prefix, fallbackWindowMs: windowMs, client, fallbackHits: 0 });
silenceBootScriptRejections(store);
return store;
},
MemoryStore,
ipKeyGenerator,
logger: { warn() {} },
});
const reservation = await throttle.reserveCredentialAttempt("203.0.113.9", "user@example.com", null);
assert.strictEqual(reservation.admitted, false, "a degraded store must refuse admission (fail closed)");
assert.strictEqual(reservation.reason, "store", "the refusal must carry the store-error reason");
assert.strictEqual(reservation.ipThresholdReached, false, "no threshold telemetry on a refused reservation");
assert.strictEqual(reservation.accountThresholdReached, false, "no threshold telemetry on a refused reservation");
// The read checks keep their designed fail-open posture on the same
// degraded store (a lost read reads as not blocked).
assert.strictEqual(await throttle.isIpBlocked("203.0.113.9"), false, "read checks fail open by design");
assert.strictEqual(await throttle.isAccountBlocked("user@example.com"), false, "read checks fail open by design");
});