Initial upload to Gitea
This commit is contained in:
1 parent
78193254ad
commit
8478998cae
1485 files changed
+461025
-42348
No files matched your search
@@ -0,0 +1,687 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:login-request-limit — unit pins for the /login request limiter
|
||||
// factory. rateLimit is an injected dependency, so these tests hand the
|
||||
// factory a capturing stub and exercise the produced options directly: the
|
||||
// real express-rate-limit ipKeyGenerator is injected to prove the IPv6 /56
|
||||
// bucketing (the constraint that keeps one host from minting fresh buckets
|
||||
// and satisfies the ERR_ERL_KEY_GEN_IPV6 source check), and the 429 handler
|
||||
// is exercised against a fake response to pin its JSON/text negotiation.
|
||||
//
|
||||
// adpanel:login-failure-throttle — behavior tests for createLoginThrottle run
|
||||
// against the express-rate-limit MemoryStore fallback (the no-Redis path) and
|
||||
// pin the constraints the brute-force control depends on: /56 source
|
||||
// bucketing, block-at-threshold-not-before, cross-source account lockout, the
|
||||
// deliberate ABSENCE of a source/account reset API (success must never wipe a
|
||||
// budget), fail-open on store errors, and per-source TOTP key isolation.
|
||||
//
|
||||
// adpanel:account-throttle-collation-parity — the per-account budget is
|
||||
// enforced on TWO keys: the folded-email key (foldAccountEmail inside
|
||||
// hashAccount — the pre-lookup approximation of utf8mb4_unicode_ci) and the
|
||||
// resolved user id (sha256("acct-id:" + id), the post-lookup identity the
|
||||
// collation cannot diverge). The pins below cover the fold's behavioral
|
||||
// classes, dual-key recording (resolved → both, unknown → fold only) and the
|
||||
// bypass-closure regression: fold-distinct variants of one account share ONE
|
||||
// id budget.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const { ipKeyGenerator, MemoryStore } = require("express-rate-limit");
|
||||
|
||||
const { createLoginRequestLimiter, createLoginThrottle, createAccountVerificationLimiter, sendLoginRateLimited, wantsJsonLoginResponse, foldAccountEmail } = require("./login-throttle");
|
||||
|
||||
function makeFakeResponse() {
|
||||
const captured = {
|
||||
headers: {},
|
||||
statusCode: null,
|
||||
jsonBody: null,
|
||||
sentType: null,
|
||||
sentBody: null,
|
||||
};
|
||||
return {
|
||||
captured,
|
||||
setHeader(name, value) { captured.headers[String(name).toLowerCase()] = value; },
|
||||
status(code) { captured.statusCode = code; return this; },
|
||||
json(body) { captured.jsonBody = body; return this; },
|
||||
type(t) { captured.sentType = t; return this; },
|
||||
send(body) { captured.sentBody = body; return this; },
|
||||
};
|
||||
}
|
||||
|
||||
// Capturing rateLimit stub: records the options the factory computed and
|
||||
// returns an inert middleware (the tests drive the options directly).
|
||||
function buildWith({ env = {}, buildStore = null, securityLog = () => {} } = {}) {
|
||||
let capturedOptions = null;
|
||||
let storeCalls = [];
|
||||
const limiter = createLoginRequestLimiter({
|
||||
rateLimit: (options) => {
|
||||
capturedOptions = options;
|
||||
return function stubLimiterMiddleware(_req, _res, next) { next(); };
|
||||
},
|
||||
buildStore: buildStore
|
||||
? (prefix, windowMs) => { storeCalls.push({ prefix, windowMs }); return buildStore(prefix, windowMs); }
|
||||
: undefined,
|
||||
ipKeyGenerator,
|
||||
getRequestIp: (req) => (req ? req.stubIp : "unknown"),
|
||||
securityLog,
|
||||
env,
|
||||
});
|
||||
assert.ok(typeof limiter === "function", "factory must return a middleware");
|
||||
assert.ok(capturedOptions, "factory must call the injected rateLimit exactly once");
|
||||
return { options: capturedOptions, storeCalls };
|
||||
}
|
||||
|
||||
function makeFakeRequest({ ip, headers = {} } = {}) {
|
||||
const lowerHeaders = {};
|
||||
for (const [k, v] of Object.entries(headers)) lowerHeaders[String(k).toLowerCase()] = v;
|
||||
return {
|
||||
stubIp: ip,
|
||||
get(name) { return lowerHeaders[String(name).toLowerCase()]; },
|
||||
};
|
||||
}
|
||||
|
||||
test("account verification limiters keep independent shared stores and stable account keys", () => {
|
||||
const definitions = [];
|
||||
const stores = [];
|
||||
for (const kind of ["credential", "totp"]) {
|
||||
createAccountVerificationLimiter({
|
||||
kind,
|
||||
rateLimit: (options) => { definitions.push(options); return (_req, _res, next) => next(); },
|
||||
buildStore: (prefix, windowMs) => { const store = { prefix, windowMs }; stores.push(store); return store; },
|
||||
securityLog: () => {},
|
||||
});
|
||||
}
|
||||
assert.equal(new Set(stores.map((store) => store.prefix)).size, 4, "every tier has a distinct Redis namespace");
|
||||
assert.equal(new Set(stores).size, 4, "store instances are never shared between limiters");
|
||||
for (const offset of [0, 2]) {
|
||||
const account = definitions[offset];
|
||||
const perSession = definitions[offset + 1];
|
||||
assert.equal(account.max, 30);
|
||||
assert.equal(perSession.max, 10);
|
||||
assert.equal(account.windowMs, 10 * 60 * 1000);
|
||||
const first = { session: { user: "owner@example.test", accountId: 7 }, sessionID: "old-sid" };
|
||||
const restored = { session: { user: "new-email@example.test", accountId: 7 }, sessionID: "restored-sid" };
|
||||
assert.equal(account.keyGenerator(first), account.keyGenerator(restored), "SID and email changes do not change the account budget");
|
||||
assert.notEqual(account.keyGenerator(first), account.keyGenerator({ session: { user: first.session.user, accountId: 8 } }));
|
||||
assert.notEqual(perSession.keyGenerator(first), perSession.keyGenerator(restored));
|
||||
assert.equal(account.skip({ session: {} }), true);
|
||||
assert.equal(account.skip(first), false);
|
||||
const legacy = { session: { user: "OWNER@example.test" } };
|
||||
assert.equal(account.keyGenerator(legacy), account.keyGenerator({ session: { user: "owner@example.test" } }), "legacy sessions retain a stable email budget");
|
||||
}
|
||||
});
|
||||
|
||||
test("the key buckets two IPv6 addresses in the same /56 together and prefixes the login-req namespace", () => {
|
||||
const { options } = buildWith();
|
||||
const keyOf = (req) => options.keyGenerator(req);
|
||||
const keyA = keyOf(makeFakeRequest({ ip: "2001:db8:aaaa:aa01::1" }));
|
||||
const keyB = keyOf(makeFakeRequest({ ip: "2001:db8:aaaa:aafe::2" }));
|
||||
const keyC = keyOf(makeFakeRequest({ ip: "2001:db8:aaaa:ab01::1" }));
|
||||
assert.strictEqual(keyA, keyB, "IPv6 addresses sharing a /56 must share one bucket");
|
||||
assert.notStrictEqual(keyA, keyC, "IPv6 addresses in different /56s must not share a bucket");
|
||||
assert.ok(keyA.startsWith("login-req:"), `key must carry the distinct login-req: prefix, got ${keyA}`);
|
||||
});
|
||||
|
||||
test("IPv4 addresses are keyed unchanged and a missing IP falls back to a stable key", () => {
|
||||
const { options } = buildWith();
|
||||
const keyA = options.keyGenerator(makeFakeRequest({ ip: "203.0.113.7" }));
|
||||
assert.strictEqual(keyA, "login-req:203.0.113.7");
|
||||
const missing = options.keyGenerator(makeFakeRequest({ ip: "" }));
|
||||
assert.strictEqual(missing, options.keyGenerator(makeFakeRequest({ ip: "" })), "missing IP must still produce a usable key");
|
||||
});
|
||||
|
||||
test("the handler answers 429 JSON to JSON-indicating requests and 429 text otherwise, with no-store", () => {
|
||||
const securityCalls = [];
|
||||
const { options } = buildWith({
|
||||
securityLog: (msg) => securityCalls.push(msg),
|
||||
});
|
||||
assert.strictEqual(options.windowMs, 60 * 1000, "window must be one minute");
|
||||
|
||||
// JSON path (fetch from login.ejs sends Accept: application/json).
|
||||
const jsonRes = makeFakeResponse();
|
||||
options.handler(makeFakeRequest({ ip: "203.0.113.7", headers: { accept: "application/json" } }), jsonRes);
|
||||
assert.strictEqual(jsonRes.captured.statusCode, 429);
|
||||
assert.deepStrictEqual(jsonRes.captured.jsonBody, { ok: false, error: "Too many requests. Try again later." });
|
||||
assert.strictEqual(jsonRes.captured.headers["cache-control"], "no-store");
|
||||
assert.strictEqual(jsonRes.captured.sentBody, null, "JSON responses must not also send a text body");
|
||||
|
||||
// XHR-only path.
|
||||
const xhrRes = makeFakeResponse();
|
||||
options.handler(makeFakeRequest({ ip: "203.0.113.7", headers: { "x-requested-with": "XMLHttpRequest" } }), xhrRes);
|
||||
assert.strictEqual(xhrRes.captured.statusCode, 429);
|
||||
assert.deepStrictEqual(xhrRes.captured.jsonBody, { ok: false, error: "Too many requests. Try again later." });
|
||||
|
||||
// Content-Type-only JSON client (adpanel:login-rate-limit-shape): the
|
||||
// handler's error bodies have always negotiated on the Content-Type leg,
|
||||
// so the shared 429 responder must too — one surface, one negotiation.
|
||||
const ctRes = makeFakeResponse();
|
||||
options.handler(makeFakeRequest({ ip: "203.0.113.7", headers: { "content-type": "application/json" } }), ctRes);
|
||||
assert.strictEqual(ctRes.captured.statusCode, 429);
|
||||
assert.deepStrictEqual(ctRes.captured.jsonBody, { ok: false, error: "Too many requests. Try again later." });
|
||||
|
||||
// Browser navigation path: plain text, never JSON.
|
||||
const textRes = makeFakeResponse();
|
||||
options.handler(makeFakeRequest({ ip: "203.0.113.7", headers: { accept: "text/html" } }), textRes);
|
||||
assert.strictEqual(textRes.captured.statusCode, 429);
|
||||
assert.strictEqual(textRes.captured.jsonBody, null);
|
||||
assert.strictEqual(textRes.captured.sentType, "text/plain");
|
||||
assert.strictEqual(textRes.captured.sentBody, "Too many requests. Try again later.");
|
||||
assert.strictEqual(textRes.captured.headers["cache-control"], "no-store");
|
||||
|
||||
assert.ok(securityCalls.includes("Login request rate limit exceeded"), "every 429 must reach securityLog");
|
||||
});
|
||||
|
||||
// adpanel:login-rate-limit-shape — the shared responder the request limiter
|
||||
// and the attack middleware both call: identical negotiation, body strings
|
||||
// and no-store as the limiter handler has always had, so the two refusal
|
||||
// sites cannot drift.
|
||||
test("sendLoginRateLimited negotiates the same 429 JSON/text shapes and no-store for the attack-detector refusal", () => {
|
||||
const securityCalls = [];
|
||||
// JSON path (login.ejs fetch sends Accept: application/json).
|
||||
const jsonRes = makeFakeResponse();
|
||||
sendLoginRateLimited(
|
||||
makeFakeRequest({ ip: "203.0.113.9", headers: { accept: "application/json" } }),
|
||||
jsonRes,
|
||||
(msg, req) => securityCalls.push([msg, req]),
|
||||
"Login attack-mode rate limit exceeded"
|
||||
);
|
||||
assert.strictEqual(jsonRes.captured.statusCode, 429);
|
||||
assert.deepStrictEqual(jsonRes.captured.jsonBody, { ok: false, error: "Too many requests. Try again later." });
|
||||
assert.strictEqual(jsonRes.captured.headers["cache-control"], "no-store");
|
||||
assert.strictEqual(jsonRes.captured.sentBody, null, "JSON responses must not also send a text body");
|
||||
// Browser navigation path: plain text, never JSON.
|
||||
const textRes = makeFakeResponse();
|
||||
sendLoginRateLimited(
|
||||
makeFakeRequest({ ip: "203.0.113.9", headers: { accept: "text/html" } }),
|
||||
textRes,
|
||||
() => {},
|
||||
"Login attack-mode rate limit exceeded"
|
||||
);
|
||||
assert.strictEqual(textRes.captured.statusCode, 429);
|
||||
assert.strictEqual(textRes.captured.jsonBody, null);
|
||||
assert.strictEqual(textRes.captured.sentType, "text/plain");
|
||||
assert.strictEqual(textRes.captured.sentBody, "Too many requests. Try again later.");
|
||||
assert.strictEqual(textRes.captured.headers["cache-control"], "no-store");
|
||||
// XHR-only path also gets JSON.
|
||||
const xhrRes = makeFakeResponse();
|
||||
sendLoginRateLimited(
|
||||
makeFakeRequest({ ip: "203.0.113.9", headers: { "x-requested-with": "XMLHttpRequest" } }),
|
||||
xhrRes,
|
||||
() => {},
|
||||
"Login attack-mode rate limit exceeded"
|
||||
);
|
||||
assert.deepStrictEqual(xhrRes.captured.jsonBody, { ok: false, error: "Too many requests. Try again later." });
|
||||
assert.deepStrictEqual(securityCalls.map(([msg]) => msg), ["Login attack-mode rate limit exceeded"], "the refusal reason must reach securityLog with the request");
|
||||
assert.strictEqual(securityCalls[0][1].stubIp, "203.0.113.9");
|
||||
});
|
||||
|
||||
// adpanel:login-rate-limit-shape — wantsJsonLoginResponse is the ONE
|
||||
// negotiation predicate for the whole login surface: the 429 responder above
|
||||
// AND the POST /login handler's error/success bodies consume it, so a client
|
||||
// cannot get JSON from one login response and plain text from another. It is
|
||||
// the superset of the two historical predicates (the limiter's Accept+XHR
|
||||
// legs and the handler's Accept+XHR+Content-Type legs); the shipped
|
||||
// login.ejs fetch always sends Accept AND X-Requested-With (with a
|
||||
// form-urlencoded Content-Type), so the unified predicate changes nothing
|
||||
// for the UI.
|
||||
test("wantsJsonLoginResponse is the single three-leg login negotiation predicate", () => {
|
||||
const wants = (headers) => wantsJsonLoginResponse(makeFakeRequest({ ip: "203.0.113.1", headers }));
|
||||
assert.strictEqual(wants({ accept: "application/json" }), true, "Accept leg");
|
||||
assert.strictEqual(wants({ "x-requested-with": "XMLHttpRequest" }), true, "XHR leg");
|
||||
assert.strictEqual(wants({ "content-type": "application/json" }), true, "Content-Type leg (the handler's historical third leg — limiter 429s must not diverge from handler errors)");
|
||||
assert.strictEqual(wants({ accept: "application/json, text/plain" }), true, "partial Accept strings still match");
|
||||
assert.strictEqual(wants({ accept: "text/html" }), false, "browser navigation stays text");
|
||||
assert.strictEqual(wants({ "content-type": "application/x-www-form-urlencoded;charset=UTF-8" }), false, "a form-post Content-Type alone does not request JSON");
|
||||
assert.strictEqual(wants({ "content-type": "text/plain" }), false);
|
||||
assert.strictEqual(wants({}), false, "no indicating headers → text");
|
||||
});
|
||||
|
||||
test("sendLoginRateLimited answers JSON to a Content-Type-only JSON client (the two-home negotiation divergence is closed)", () => {
|
||||
const res = makeFakeResponse();
|
||||
sendLoginRateLimited(
|
||||
makeFakeRequest({ ip: "203.0.113.9", headers: { "content-type": "application/json" } }),
|
||||
res,
|
||||
() => {},
|
||||
"Login request rate limit exceeded"
|
||||
);
|
||||
assert.strictEqual(res.captured.statusCode, 429);
|
||||
assert.deepStrictEqual(res.captured.jsonBody, { ok: false, error: "Too many requests. Try again later." });
|
||||
assert.strictEqual(res.captured.headers["cache-control"], "no-store");
|
||||
assert.strictEqual(res.captured.sentBody, null, "JSON responses must not also send a text body");
|
||||
});
|
||||
|
||||
test("the per-minute budget comes from LOGIN_REQUEST_RATE_LIMIT_PER_MIN and is clamped 10..10000", () => {
|
||||
assert.strictEqual(buildWith({ env: {} }).options.max, 60, "unset env must give the documented default of 60/min");
|
||||
assert.strictEqual(buildWith({ env: { LOGIN_REQUEST_RATE_LIMIT_PER_MIN: "25" } }).options.max, 25);
|
||||
assert.strictEqual(buildWith({ env: { LOGIN_REQUEST_RATE_LIMIT_PER_MIN: "3" } }).options.max, 10, "below-floor values clamp to 10");
|
||||
assert.strictEqual(
|
||||
buildWith({ env: { LOGIN_REQUEST_RATE_LIMIT_PER_MIN: "99999" } }).options.max,
|
||||
10000,
|
||||
"above-ceiling values clamp to 10000"
|
||||
);
|
||||
assert.strictEqual(buildWith({ env: { LOGIN_REQUEST_RATE_LIMIT_PER_MIN: "junk" } }).options.max, 60);
|
||||
});
|
||||
|
||||
test("the limiter rides the shared Redis store factory under the distinct login-req: prefix, and fails open without one", () => {
|
||||
const built = [];
|
||||
const { storeCalls } = buildWith({
|
||||
buildStore: (prefix, windowMs) => { built.push({ prefix, windowMs }); return { sentinel: true }; },
|
||||
});
|
||||
assert.strictEqual(storeCalls.length, 1, "exactly one store instance (one store instance per limiter)");
|
||||
assert.strictEqual(storeCalls[0].prefix, "login-req:", "store prefix must be the distinct login-req: namespace");
|
||||
assert.strictEqual(storeCalls[0].windowMs, 60 * 1000);
|
||||
|
||||
const noRedis = buildWith({});
|
||||
assert.strictEqual(noRedis.options.store, undefined, "without Redis the limiter must fall back to express-rate-limit's own store");
|
||||
assert.strictEqual(noRedis.options.passOnStoreError, true, "an abuse brake must fail open on store errors");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// adpanel:login-failure-throttle — createLoginThrottle behavior (MemoryStore)
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
function makeThrottle({ env = {}, buildStore = null, logger = console } = {}) {
|
||||
return createLoginThrottle({ buildStore, MemoryStore, ipKeyGenerator, env, logger });
|
||||
}
|
||||
|
||||
test("IPv6 sources sharing a /56 draw one failure budget; IPv4 keys stay exact and IPv4-mapped addresses normalize to their IPv4 key", async () => {
|
||||
const t = makeThrottle();
|
||||
const srcA = t.ipKey("2001:db8:aaaa:aa01::1");
|
||||
const srcB = t.ipKey("2001:db8:aaaa:aafe::2");
|
||||
const srcC = t.ipKey("2001:db8:aaaa:ab01::1");
|
||||
assert.strictEqual(srcA, srcB, "addresses inside one /56 must share the bucket key");
|
||||
assert.notStrictEqual(srcA, srcC, "different /56s must not share a bucket");
|
||||
|
||||
// Ten admitted reservations from one address in the /56 exhaust the
|
||||
// bucket (each reservation stands as its failure record until finalized).
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const admission = await t.reserveCredentialAttempt(srcA, `ipv6-user-${i}@example.com`);
|
||||
assert.strictEqual(admission.admitted, true, `reservation ${i + 1} must admit under the fresh budget`);
|
||||
}
|
||||
assert.strictEqual(await t.isIpBlocked(srcB), true, "a sibling address in the same /56 must inherit the exhausted budget");
|
||||
assert.strictEqual(await t.isIpBlocked(srcC), false, "a different /56 must keep its own budget");
|
||||
|
||||
// IPv4 is keyed unchanged; an IPv4-mapped IPv6 address normalizes onto the
|
||||
// plain IPv4 bucket (double defense: address rotation AND mapped forms).
|
||||
assert.strictEqual(t.ipKey("203.0.113.7"), "203.0.113.7");
|
||||
assert.strictEqual(t.ipKey("::ffff:203.0.113.7"), "203.0.113.7", "IPv4-mapped IPv6 must normalize to the IPv4 key");
|
||||
const mappedSrc = t.ipKey("::ffff:198.51.100.9");
|
||||
for (let i = 0; i < 10; i++) await t.reserveCredentialAttempt(mappedSrc, `mapped-user-${i}@example.com`);
|
||||
assert.strictEqual(await t.isIpBlocked(t.ipKey("198.51.100.9")), true, "the plain IPv4 form must see the mapped form's failures");
|
||||
});
|
||||
|
||||
test("a source admits its 10th reservation with the crossing flag and refuses the 11th; the budget decays only with the window (no reset API to call)", async () => {
|
||||
const t = makeThrottle();
|
||||
const src = t.ipKey("203.0.113.5");
|
||||
for (let i = 0; i < 9; i++) await t.reserveCredentialAttempt(src, "target@example.com");
|
||||
assert.strictEqual(await t.isIpBlocked(src), false, "9 standing failures must not block (max 10)");
|
||||
const tenth = await t.reserveCredentialAttempt(src, "target@example.com");
|
||||
assert.strictEqual(tenth.admitted, true, "the 10th reservation admits (the budget is exceeded only past max)");
|
||||
assert.strictEqual(tenth.ipThresholdReached, true, "the 10th reservation reports the crossing");
|
||||
assert.strictEqual(await t.isIpBlocked(src), true, "10 standing failures block the source");
|
||||
const eleventh = await t.reserveCredentialAttempt(src, "target@example.com");
|
||||
assert.strictEqual(eleventh.admitted, false, "the 11th reservation is refused — the compare never runs");
|
||||
assert.strictEqual(eleventh.reason, "source");
|
||||
// The refused reservation left NOTHING standing: its account increments
|
||||
// were refunded with the source increment.
|
||||
assert.strictEqual(await t.isAccountBlocked("target@example.com"), false, "the over-source refusal must not fill the account budget");
|
||||
|
||||
// A "successful login" has no API to reset the source budget: the block
|
||||
// persists and only the window decay lifts it. This is the exact hole the
|
||||
// old resetLoginAttempts(clientIp) left open.
|
||||
assert.strictEqual(await t.isIpBlocked(src), true, "no exposed call may clear the source budget");
|
||||
});
|
||||
|
||||
test("an account is blocked after 20 admitted reservations spread across different sources, unknown emails included; an over-account reservation refunds the source", async () => {
|
||||
const t = makeThrottle();
|
||||
const victim = "victim@example.com";
|
||||
// 19 reservations, each from a fresh /56 so the per-source counter never
|
||||
// trips.
|
||||
for (let i = 0; i < 19; i++) {
|
||||
const src = t.ipKey(`198.51.100.${i + 1}`);
|
||||
const admission = await t.reserveCredentialAttempt(src, victim);
|
||||
assert.strictEqual(admission.admitted, true, `reservation ${i + 1} must admit`);
|
||||
assert.strictEqual(admission.ipThresholdReached, false, `source ${i + 1} must stay under its own budget`);
|
||||
}
|
||||
assert.strictEqual(await t.isAccountBlocked(victim), false, "19 failures must not block the account (max 20)");
|
||||
const last = await t.reserveCredentialAttempt(t.ipKey("198.51.100.200"), victim);
|
||||
assert.strictEqual(last.admitted, true);
|
||||
assert.strictEqual(last.accountThresholdReached, true, "the 20th reservation reports the account crossing");
|
||||
assert.strictEqual(await t.isAccountBlocked(victim), true, "20 cross-source failures block the account");
|
||||
assert.strictEqual(await t.isAccountBlocked("other@example.com"), false, "a different account must keep its own budget");
|
||||
// The counter is structural: unknown emails are counted exactly like known
|
||||
// ones, so probing it reveals nothing about account existence.
|
||||
assert.strictEqual(await t.isAccountBlocked(victim), true, "no exposed call may clear the account budget");
|
||||
|
||||
// adpanel:login-bcrypt-admission — the over-account refusal mirrors the
|
||||
// pre-lookup account block's semantics: the probe records NOTHING, so it
|
||||
// must not consume source budget either (both increments refund).
|
||||
const probeSrc = t.ipKey("198.51.100.250");
|
||||
const refused = await t.reserveCredentialAttempt(probeSrc, victim);
|
||||
assert.strictEqual(refused.admitted, false, "an over-account reservation is refused");
|
||||
assert.strictEqual(refused.reason, "account");
|
||||
assert.strictEqual(await t.isIpBlocked(probeSrc), false, "the refused probe's source increment must be refunded");
|
||||
});
|
||||
|
||||
// adpanel:login-bcrypt-admission — the amplification-kill regression test.
|
||||
// The pre-fix read-then-arm flow let all 60 parallel attempts through the
|
||||
// entry checks (they read pre-burst counters), paid 2^15 of bcrypt work per
|
||||
// attempt (~120 threadpool-seconds injected), and recorded all 60 failures
|
||||
// (~6x overshoot). The reservation is the atomic gate: the burst admits at
|
||||
// most source-max, and every refusal refunds BOTH counters — the rejected
|
||||
// requests never reach a compare in the handler
|
||||
// (tests/login-throttle-wiring.test.js pins that ordering in the source).
|
||||
// On the MemoryStore fallback the admission reads the standing total back
|
||||
// after the increments, so a fully-parallel burst may be refused IN FULL
|
||||
// (every increment refunded — strictly safer than admitting max); the bound
|
||||
// pinned here is the invariant: standing admissions never exceed max.
|
||||
test("60 parallel reservations from ONE /56 bucket admit at most source-max; the burst tail refunds to the pre-burst state", async () => {
|
||||
const t = makeThrottle();
|
||||
const src = t.ipKey("203.0.113.99");
|
||||
const results = await Promise.all(
|
||||
Array.from({ length: 60 }, (_, i) => t.reserveCredentialAttempt(src, `burst-${i}@example.com`))
|
||||
);
|
||||
const admitted = results.filter((r) => r.admitted);
|
||||
const refused = results.filter((r) => !r.admitted);
|
||||
assert.ok(admitted.length <= 10, `at most LOGIN_IP_MAX_FAILURES parallel admissions from one bucket (got ${admitted.length})`);
|
||||
assert.strictEqual(admitted.length + refused.length, 60);
|
||||
assert.strictEqual(refused.length, 60 - admitted.length, "the rest of the burst is refused before any compare could run");
|
||||
for (const r of refused) {
|
||||
assert.strictEqual(r.reason, "source", "the burst tail must be refused on the source budget");
|
||||
assert.strictEqual(r.ipThresholdReached, false, "a refused reservation reports no crossing");
|
||||
assert.strictEqual(r.accountThresholdReached, false);
|
||||
}
|
||||
// The refusals left NOTHING standing: every burst email's fold increment
|
||||
// was refunded, and the standing source count never overshoots max —
|
||||
// bounded, with no negative drift.
|
||||
for (let i = 0; i < 10; i++) {
|
||||
assert.strictEqual(await t.isAccountBlocked(`burst-${i}@example.com`), false, "a refused reservation must not fill the account budget");
|
||||
}
|
||||
assert.strictEqual(await t.isIpBlocked(src), admitted.length >= 10, "the standing source count equals the admitted count, capped at max");
|
||||
// The budget still binds after the burst: a further reservation admits
|
||||
// only if the burst admissions left room, and a refusal refunds itself.
|
||||
const extra = await t.reserveCredentialAttempt(src, "burst-after@example.com");
|
||||
assert.strictEqual(extra.admitted, admitted.length < 10, "the standing budget gates further admissions exactly at max");
|
||||
assert.strictEqual(await t.isAccountBlocked("burst-after@example.com"), false, "a refused extra reservation refunds too");
|
||||
});
|
||||
|
||||
test("refundCredentialAttempt releases an admitted reservation net-zero, floors at zero, and never touches the TOTP budget", async () => {
|
||||
const t = makeThrottle();
|
||||
const src = t.ipKey("203.0.113.42");
|
||||
const user = { id: 31 };
|
||||
const admission = await t.reserveCredentialAttempt(src, "login@example.com", user);
|
||||
assert.strictEqual(admission.admitted, true);
|
||||
assert.strictEqual(await t.isAccountBlockedById(31), false, "one standing reservation does not block (max 20)");
|
||||
// The attempt succeeds: refund -> net zero on EVERY counter the
|
||||
// reservation incremented (source, fold, id).
|
||||
await t.refundCredentialAttempt(src, "login@example.com", user);
|
||||
assert.strictEqual(await t.isIpBlocked(src), false, "the refunded source increment is gone");
|
||||
assert.strictEqual(await t.isAccountBlocked("login@example.com"), false, "the refunded fold increment is gone");
|
||||
assert.strictEqual(await t.isAccountBlockedById(31), false, "the refunded id increment is gone");
|
||||
// The reservation/refund pair never touches the TOTP counter: that budget
|
||||
// stays read-then-record on its own store (the reservation does not cover
|
||||
// it).
|
||||
for (let i = 0; i < 5; i++) await t.recordTotpAttempt("login@example.com", src);
|
||||
await t.refundCredentialAttempt(src, "login@example.com", user);
|
||||
assert.strictEqual(await t.isTotpBlocked("login@example.com", src), true, "a credential refund must not release the TOTP attempt records");
|
||||
|
||||
// Floor arithmetic on a fresh source: reserve once, refund TWICE (the
|
||||
// second must be a no-op), then the budget must behave exactly as from a
|
||||
// zero counter — the 10th admission crosses, the 11th is refused. A
|
||||
// negative drift from an unguarded decrement would shift both by one.
|
||||
const floorSrc = t.ipKey("203.0.113.43");
|
||||
await t.reserveCredentialAttempt(floorSrc, "floor-probe@example.com");
|
||||
await t.refundCredentialAttempt(floorSrc, "floor-probe@example.com");
|
||||
await t.refundCredentialAttempt(floorSrc, "floor-probe@example.com");
|
||||
let crossingSeen = false;
|
||||
for (let i = 0; i < 10; i++) {
|
||||
const r = await t.reserveCredentialAttempt(floorSrc, `floor-${i}@example.com`);
|
||||
assert.strictEqual(r.admitted, true, `floor reservation ${i + 1} admits`);
|
||||
if (r.ipThresholdReached) crossingSeen = true;
|
||||
}
|
||||
assert.strictEqual(crossingSeen, true, "the 10th reservation crosses exactly as from a zero counter");
|
||||
const over = await t.reserveCredentialAttempt(floorSrc, "floor-over@example.com");
|
||||
assert.strictEqual(over.admitted, false, "the 11th is refused — no phantom extra admission from a negative counter");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// adpanel:account-throttle-collation-parity — the fold layer and the id layer.
|
||||
// The account lookup matches on `WHERE LOWER(email) = LOWER(?)` over a
|
||||
// utf8mb4_unicode_ci column (live-probed with the app's own mysql2 driver:
|
||||
// fullwidth victim = victim, josé = jose, straße = strasse, fi = fi all
|
||||
// compare EQUAL), but the pre-fix key sha256(trim().toLowerCase()) put every
|
||||
// Unicode variant in a DISTINCT bucket — each variant minted a fresh
|
||||
// 20-failure budget. Two layers close it: foldAccountEmail (the JS-side
|
||||
// approximation inside hashAccount) and the resolved user id (enforced
|
||||
// post-lookup by the handler on an identity no collation can diverge).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("foldAccountEmail maps every collation-variant class onto one bucket string", () => {
|
||||
// The three live-probe variant classes plus the ligature: each pair folds
|
||||
// to the same string, or the pre-lookup bucket keeps a fresh-budget hole
|
||||
// the id layer would have to carry alone.
|
||||
assert.strictEqual(foldAccountEmail("victim@example.com"), foldAccountEmail("victim@example.com"), "fullwidth NFKC class");
|
||||
assert.strictEqual(foldAccountEmail("josé@example.com"), foldAccountEmail("jose@example.com"), "accent NFD/Mn-strip class");
|
||||
assert.strictEqual(foldAccountEmail("straße@example.com"), foldAccountEmail("strasse@example.com"), "eszett expansion class");
|
||||
assert.strictEqual(foldAccountEmail("ẞ@example.com"), foldAccountEmail("ss@example.com"), "capital eszett lowercases to ß first, so ß→ss covers both cases");
|
||||
assert.strictEqual(foldAccountEmail("ẞ@example.com"), foldAccountEmail("ß@example.com"), "ß→ss in both cases");
|
||||
assert.strictEqual(foldAccountEmail("file@example.com"), foldAccountEmail("file@example.com"), "ligature compatibility class");
|
||||
// Idempotence: the fold is stable under itself (a future edit that
|
||||
// oscillates between composed/decomposed forms would break hashing).
|
||||
for (const s of ["victim@example.com", "José@X.COM", "straße@x.com", "ẞ@x.com", "file@x.com", "mıchael@x.com", "plain@example.com", ""]) {
|
||||
assert.strictEqual(foldAccountEmail(foldAccountEmail(s)), foldAccountEmail(s), `fold must be idempotent on ${JSON.stringify(s)}`);
|
||||
}
|
||||
// Plain ASCII emails pass through with only the historical trim+lowercase
|
||||
// (the hashAccount input contract every pre-existing key was built on).
|
||||
assert.strictEqual(foldAccountEmail("plain@example.com"), "plain@example.com", "already-canonical ASCII is unchanged");
|
||||
assert.strictEqual(foldAccountEmail(" Victim@Example.com "), "victim@example.com", "ASCII keeps the historical trim+lowercase");
|
||||
// Empty/absent input keeps the historical sha256("") key shape.
|
||||
assert.strictEqual(foldAccountEmail(""), "");
|
||||
assert.strictEqual(foldAccountEmail(undefined), "");
|
||||
});
|
||||
|
||||
test("hashAccount folds: a fullwidth variant now spends the canonical address's bucket", async () => {
|
||||
const t = makeThrottle();
|
||||
// 20 reservations under the fullwidth variant, each from a fresh /56 so
|
||||
// the per-source counter never trips.
|
||||
for (let i = 0; i < 20; i++) await t.reserveCredentialAttempt(t.ipKey(`198.51.100.${i + 1}`), "victim@example.com");
|
||||
assert.strictEqual(await t.isAccountBlocked("victim@example.com"), true, "the canonical address inherits the variant's failures (pre-fix: fresh bucket)");
|
||||
});
|
||||
|
||||
test("a resolved user's reservation increments BOTH keys: the submitted email's fold key and the id key", async () => {
|
||||
const t = makeThrottle();
|
||||
const user = { id: 5 };
|
||||
for (let i = 0; i < 19; i++) await t.reserveCredentialAttempt(t.ipKey(`198.51.100.${i + 1}`), "acct@example.com", user);
|
||||
assert.strictEqual(await t.isAccountBlocked("acct@example.com"), false, "19 fold-key failures do not block yet");
|
||||
assert.strictEqual(await t.isAccountBlockedById(5), false, "19 id-key failures do not block yet");
|
||||
const crossing = await t.reserveCredentialAttempt(t.ipKey("198.51.100.200"), "acct@example.com", user);
|
||||
assert.strictEqual(crossing.admitted, true);
|
||||
assert.strictEqual(crossing.accountThresholdReached, true, "the 20th reservation reports the crossing");
|
||||
assert.strictEqual(await t.isAccountBlocked("acct@example.com"), true);
|
||||
assert.strictEqual(await t.isAccountBlockedById(5), true, "the id budget crossed with the fold budget — dual recording");
|
||||
});
|
||||
|
||||
test("an unknown-email reservation increments the fold key only (no id key exists to spend)", async () => {
|
||||
const t = makeThrottle();
|
||||
// User 5 already carries 19 resolved failures; unknown-email probes under
|
||||
// fresh fold keys and fresh sources must not push the id budget over.
|
||||
for (let i = 0; i < 19; i++) await t.reserveCredentialAttempt(t.ipKey(`203.0.113.${i + 1}`), "acct@example.com", { id: 5 });
|
||||
for (let i = 0; i < 30; i++) await t.reserveCredentialAttempt(t.ipKey(`192.0.2.${i + 1}`), `ghost${i}@example.com`);
|
||||
assert.strictEqual(await t.isAccountBlockedById(5), false, "unknown-email failures never touch an id budget");
|
||||
const crossing = await t.reserveCredentialAttempt(t.ipKey("203.0.113.200"), "acct@example.com", { id: 5 });
|
||||
assert.strictEqual(crossing.accountThresholdReached, true, "only the 20th RESOLVED failure crosses");
|
||||
assert.strictEqual(await t.isAccountBlockedById(5), true);
|
||||
});
|
||||
|
||||
test("bypass closure: two fold-distinct emails resolving to one user id share ONE budget (the finding's regression test)", async () => {
|
||||
const t = makeThrottle();
|
||||
// Pre-fix, variantA and variantB keyed to two DIFFERENT sha256 buckets —
|
||||
// exactly what a collation variant did to the per-account budget (20
|
||||
// guesses per variant = 40+ guesses against one account). findUserByEmail
|
||||
// resolves both variants to the same row, and the reservation threads
|
||||
// that row's id into every resolved attempt, so both spend the ONE id
|
||||
// budget.
|
||||
const variantA = "variant-a@example.com";
|
||||
const variantB = "variant-b@example.com";
|
||||
const resolved = { id: 77 };
|
||||
for (let i = 0; i < 20; i++) await t.reserveCredentialAttempt(t.ipKey(`198.51.100.${i + 1}`), variantA, resolved);
|
||||
// Variant B's own fold bucket is untouched — precisely the pre-fix hole.
|
||||
assert.strictEqual(await t.isAccountBlocked(variantB), false, "the fold key alone would not block variant B (the pre-fix behavior)");
|
||||
// The id budget the reservation enforces IS exhausted, so the reservation
|
||||
// refuses variant B before the credential compare.
|
||||
assert.strictEqual(await t.isAccountBlockedById(77), true, "the id-key budget blocks variant B — the bypass is closed");
|
||||
// Further variant-B attempts cannot reopen a budget for the identity: the
|
||||
// reservation is REFUSED (id over max) and refunds everything.
|
||||
const refused = await t.reserveCredentialAttempt(t.ipKey("198.51.100.201"), variantB, resolved);
|
||||
assert.strictEqual(refused.admitted, false, "the over-id reservation is refused before any compare");
|
||||
assert.strictEqual(refused.reason, "account");
|
||||
assert.strictEqual(await t.isIpBlocked(t.ipKey("198.51.100.201")), false, "the refusal refunds the source increment");
|
||||
assert.strictEqual(await t.isAccountBlockedById(77), true);
|
||||
assert.strictEqual(await t.isAccountBlocked(variantA), true, "variant A's own fold bucket is exhausted too");
|
||||
});
|
||||
|
||||
test("the id-keyed budget lives in the SAME login-fail-acct: store with the same max (no fourth store)", () => {
|
||||
const prefixes = [];
|
||||
createLoginThrottle({ buildStore: (prefix) => { prefixes.push(prefix); return new MemoryStore(); }, MemoryStore, ipKeyGenerator });
|
||||
assert.deepStrictEqual(prefixes.sort(), ["login-fail-acct:", "login-fail-ip:", "login-totp-src:"], "still exactly one store instance per counter, distinct prefixes");
|
||||
});
|
||||
|
||||
test("the id-keyed account budget obeys LOGIN_ACCOUNT_MAX_FAILURES (shared window/max with the fold-key budget)", async () => {
|
||||
const tight = makeThrottle({ env: { LOGIN_ACCOUNT_MAX_FAILURES: "6" } });
|
||||
for (let i = 0; i < 5; i++) await tight.reserveCredentialAttempt(tight.ipKey(`203.0.113.${i + 1}`), "acct@example.com", { id: 12 });
|
||||
assert.strictEqual(await tight.isAccountBlockedById(12), false, "5 failures under a max of 6 do not block");
|
||||
await tight.reserveCredentialAttempt(tight.ipKey("203.0.113.200"), "acct@example.com", { id: 12 });
|
||||
assert.strictEqual(await tight.isAccountBlockedById(12), true, "the id budget uses the account budget's max");
|
||||
});
|
||||
|
||||
test("the TOTP per-account component is enforced on the id key for resolved users; the source component stays per-source", async () => {
|
||||
const t = makeThrottle();
|
||||
const srcA = t.ipKey("203.0.113.10");
|
||||
const srcB = t.ipKey("203.0.113.11");
|
||||
for (let i = 0; i < 4; i++) await t.recordTotpAttemptById(9, srcA);
|
||||
assert.strictEqual(await t.isTotpBlockedById(9, srcA), false, "4 attempts must not block (max 5)");
|
||||
await t.recordTotpAttemptById(9, srcA);
|
||||
assert.strictEqual(await t.isTotpBlockedById(9, srcA), true, "5 id-keyed attempts block this source");
|
||||
assert.strictEqual(await t.isTotpBlockedById(9, srcB), false, "another source keeps its own TOTP budget");
|
||||
assert.strictEqual(await t.isTotpBlockedById(8, srcA), false, "another id keeps its own TOTP budget");
|
||||
// The fold-key budget of a variant email is an independent layer; only the
|
||||
// id budget bounds the aggregate for the resolved identity.
|
||||
assert.strictEqual(await t.isTotpBlocked("variant@example.com", srcA), false, "the fold-key budget is a separate layer");
|
||||
});
|
||||
|
||||
test("resetTotpSource clears BOTH keys when the resolved user is threaded in (a variant-filled id budget cannot lock the next login)", async () => {
|
||||
const t = makeThrottle();
|
||||
const src = t.ipKey("203.0.113.10");
|
||||
for (let i = 0; i < 5; i++) await t.recordTotpAttemptById(9, src);
|
||||
await t.recordTotpAttempt("variant@example.com", src);
|
||||
for (let i = 0; i < 5; i++) await t.recordTotpAttempt("other@example.com", src);
|
||||
assert.strictEqual(await t.isTotpBlockedById(9, src), true, "the id budget is exhausted before the reset");
|
||||
await t.resetTotpSource("variant@example.com", src, { id: 9 });
|
||||
assert.strictEqual(await t.isTotpBlockedById(9, src), false, "the id budget clears with the email budget");
|
||||
assert.strictEqual(await t.isTotpBlocked("variant@example.com", src), false, "the submitted email's budget clears");
|
||||
assert.strictEqual(await t.isTotpBlocked("other@example.com", src), true, "a DIFFERENT fold key stays blocked (no collateral reset)");
|
||||
});
|
||||
|
||||
test("the module exposes no source/account reset API and no per-process fallback state", async () => {
|
||||
const t = makeThrottle();
|
||||
const keys = Object.keys(t).sort();
|
||||
// adpanel:account-throttle-collation-parity — the surface carries the
|
||||
// id-keyed mirrors (isAccountBlockedById / isTotpBlockedById /
|
||||
// recordTotpAttemptById); still NO source/account reset API.
|
||||
// adpanel:login-bcrypt-admission — the counting site moved from the
|
||||
// removed recordCredentialFailure into the reserve/refund pair: the
|
||||
// reservation increments atomically at admission (before any compare),
|
||||
// the refund decrements floored at zero on every non-failure exit. Still
|
||||
// exactly one counting site for credential failures — the reservation.
|
||||
assert.deepStrictEqual(keys, [
|
||||
"config",
|
||||
"ipKey",
|
||||
"isAccountBlocked",
|
||||
"isAccountBlockedById",
|
||||
"isIpBlocked",
|
||||
"isTotpBlocked",
|
||||
"isTotpBlockedById",
|
||||
"recordTotpAttempt",
|
||||
"recordTotpAttemptById",
|
||||
"refundCredentialAttempt",
|
||||
"reserveCredentialAttempt",
|
||||
"resetTotpSource",
|
||||
], "the returned surface must be exactly the check/reserve/refund set plus the TOTP-only reset");
|
||||
for (const key of Object.keys(t)) {
|
||||
if (key === "resetTotpSource") continue;
|
||||
assert.ok(!/reset/i.test(key), `no reset-bearing API may exist outside the TOTP counter, found: ${key}`);
|
||||
}
|
||||
// The reset-on-success bypass was reachable precisely because a reset for
|
||||
// the source/account counters existed; its absence is the contract.
|
||||
assert.strictEqual(typeof t.resetTotpSource, "function", "the TOTP counter (code guessing) keeps its reset: a successful login proves the code");
|
||||
// adpanel:login-rate-limit-shape — sendLoginRateLimited (the shared 429
|
||||
// responder used by BOTH the request limiter and the attack middleware)
|
||||
// and wantsJsonLoginResponse (the ONE negotiation predicate it shares
|
||||
// with the POST /login handler bodies) join the exports, as does
|
||||
// foldAccountEmail (adpanel:account-throttle-collation-parity — the ONE
|
||||
// throttle-key home's fold, pinned below); the module still exposes NO
|
||||
// source/account reset API. adpanel:login-retry-after —
|
||||
// loginRetryAfterSeconds (the ONE reason→window Retry-After mapping the
|
||||
// POST /login 429s share) joins the exports too (conscious pin update).
|
||||
assert.deepStrictEqual(Object.keys(require("./login-throttle")).sort(), ["createAccountOperationLimiter", "createAccountVerificationLimiter", "createLoginRequestLimiter", "createLoginThrottle", "foldAccountEmail", "loginRetryAfterSeconds", "sendLoginRateLimited", "wantsJsonLoginResponse"]);
|
||||
});
|
||||
|
||||
test("a store whose methods throw: reads fail open, the reservation fails CLOSED, and errors log at most once a minute without throwing", async () => {
|
||||
const warnings = [];
|
||||
const fakeLogger = { warn: (...args) => warnings.push(args.join(" ")) };
|
||||
const brokenStore = {
|
||||
init() { },
|
||||
get() { throw new Error("redis down"); },
|
||||
increment() { throw new Error("redis down"); },
|
||||
resetKey() { throw new Error("redis down"); },
|
||||
};
|
||||
const t = makeThrottle({ buildStore: () => brokenStore, logger: fakeLogger });
|
||||
|
||||
assert.strictEqual(await t.isIpBlocked("src"), false, "get() failure must read as not blocked");
|
||||
assert.strictEqual(await t.isAccountBlocked("a@b.c"), false, "get() failure must read as not blocked");
|
||||
// adpanel:login-bcrypt-admission — the reservation's increments are the
|
||||
// authoritative admission: a store failure there must fail CLOSED (the
|
||||
// audit's finding is unbounded compare work; during a Redis outage logins
|
||||
// fail anyway through the shared session store), never admit unbounded.
|
||||
const admission = await t.reserveCredentialAttempt("src", "a@b.c");
|
||||
assert.deepStrictEqual(
|
||||
admission,
|
||||
{ admitted: false, reason: "store", ipThresholdReached: false, accountThresholdReached: false },
|
||||
"increment() failure must refuse admission (fail closed), reporting no threshold"
|
||||
);
|
||||
assert.strictEqual(await t.isTotpBlocked("a@b.c", "src"), false);
|
||||
await t.recordTotpAttempt("a@b.c", "src");
|
||||
await t.resetTotpSource("a@b.c", "src");
|
||||
assert.strictEqual(warnings.length, 1, `store errors must log at most once a minute, got: ${warnings.length}`);
|
||||
assert.ok(warnings[0].includes("failing open"), "the check-path log must say the throttle is failing open");
|
||||
// A later operation (past the 60s log gate) still fails open rather than throwing.
|
||||
const t2 = makeThrottle({ buildStore: () => brokenStore, logger: fakeLogger });
|
||||
assert.strictEqual(await t2.isIpBlocked("src"), false);
|
||||
});
|
||||
|
||||
test("TOTP attempt keys are isolated per source, and resetting one source leaves the other blocked", async () => {
|
||||
const t = makeThrottle();
|
||||
const email = "totp-user@example.com";
|
||||
const srcA = t.ipKey("203.0.113.10");
|
||||
const srcB = t.ipKey("203.0.113.11");
|
||||
for (let i = 0; i < 5; i++) await t.recordTotpAttempt(email, srcA);
|
||||
assert.strictEqual(await t.isTotpBlocked(email, srcA), true, "5 attempts (TOTP_ATTEMPT_MAX) block this source");
|
||||
assert.strictEqual(await t.isTotpBlocked(email, srcB), false, "another source must keep its own TOTP budget");
|
||||
assert.strictEqual(await t.isTotpBlocked("someone-else@example.com", srcA), false, "another account must keep its own TOTP budget");
|
||||
|
||||
for (let i = 0; i < 5; i++) await t.recordTotpAttempt(email, srcB);
|
||||
await t.resetTotpSource(email, srcA);
|
||||
assert.strictEqual(await t.isTotpBlocked(email, srcA), false, "the reset clears only its own source key");
|
||||
assert.strictEqual(await t.isTotpBlocked(email, srcB), true, "the reset must not leak to a sibling source");
|
||||
});
|
||||
|
||||
test("the failure budgets are configurable through the documented environment variables", () => {
|
||||
assert.strictEqual(makeThrottle().config.ip.max, 10, "LOGIN_IP_MAX_FAILURES default");
|
||||
assert.strictEqual(makeThrottle().config.account.max, 20, "LOGIN_ACCOUNT_MAX_FAILURES default");
|
||||
const tight = makeThrottle({ env: { LOGIN_IP_MAX_FAILURES: "4", LOGIN_ACCOUNT_MAX_FAILURES: "6" } });
|
||||
assert.strictEqual(tight.config.ip.max, 4);
|
||||
assert.strictEqual(tight.config.account.max, 6);
|
||||
const clamped = makeThrottle({ env: { LOGIN_IP_MAX_FAILURES: "1", LOGIN_ACCOUNT_MAX_FAILURES: "99999" } });
|
||||
assert.strictEqual(clamped.config.ip.max, 3, "below-floor clamps to 3");
|
||||
assert.strictEqual(clamped.config.account.max, 10000, "above-ceiling clamps to 10000");
|
||||
});
|
||||
Reference in new issue
Block a user