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,487 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:admin-create-throttle-identity — the account-creation budget on
|
||||
// POST /api/admin/user/create must be keyed on a STABLE account/session
|
||||
// identity, not resettable by changing the real source IP.
|
||||
//
|
||||
// The single limiter this replaces keyed
|
||||
// admin-user-create:<raw IP>:<email>:<sid>
|
||||
// so the SAME authenticated admin session minted a fresh 6-attempt budget
|
||||
// from every rotated IPv6 address (including within the same /56 — the audit
|
||||
// finding) and on every re-login (new sid). It is now TWO chained budgets on
|
||||
// the same route (both must pass; each with its OWN store instance and
|
||||
// distinct key prefix):
|
||||
// 1. adminUserCreateAccountRateLimiter — the OPERATION budget: 6 per
|
||||
// 10 min per account (email key; /56-bucketed IP fallback when the
|
||||
// limiter sees the request before the route's 401).
|
||||
// 2. adminUserCreateIpRateLimiter — the host bucket: 24 per 10 min per
|
||||
// /56, NAT-tolerant, mirroring the account-wide verification budget.
|
||||
// Nothing is broadly raised: the COST of each creation (the password-first
|
||||
// step-up) is still charged separately to sessionRevoke2faSessionRateLimiter
|
||||
// (8/session) and sessionRevoke2faEmailRateLimiter (24/account), which these
|
||||
// pins also lock.
|
||||
//
|
||||
// index.js boots servers on require, so this file pins the SHIPPED source:
|
||||
// limiter definitions and keyGenerators are extracted from index.js text and
|
||||
// evaluated against the REAL ipKeyGenerator from node_modules (same harness
|
||||
// as tests/limiter-ipv6-bucketing.test.js), plus behavior runs against a
|
||||
// fake Redis store injected through the definition's own
|
||||
// buildSharedRateLimitRedisStore seam.
|
||||
|
||||
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, rateLimit } = require("express-rate-limit");
|
||||
|
||||
const ACCOUNT_LIMITER = "adminUserCreateAccountRateLimiter";
|
||||
const IP_LIMITER = "adminUserCreateIpRateLimiter";
|
||||
const SHARED_HANDLER = "adminUserCreateRateLimitExceeded";
|
||||
const CLIENT_429_TEXT = "Too many account creation attempts. Please wait 10 minutes before trying again.";
|
||||
|
||||
function countOccurrences(needle) {
|
||||
return indexSource.split(needle).length - 1;
|
||||
}
|
||||
|
||||
function indexOfOrThrow(needle, from = 0) {
|
||||
const idx = indexSource.indexOf(needle, from);
|
||||
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
|
||||
return idx;
|
||||
}
|
||||
|
||||
// Brace matcher that skips line/block comments and string literals (quote-
|
||||
// aware, so `"unknown"` inside a template literal does not close it), the
|
||||
// same scanning discipline as tests/limiter-ipv6-bucketing.test.js.
|
||||
function matchBrace(source, openIdx) {
|
||||
let depth = 0;
|
||||
let inLine = false;
|
||||
let inBlock = false;
|
||||
let quote = null;
|
||||
for (let i = openIdx; i < source.length; i++) {
|
||||
const c = source[i];
|
||||
const n = source[i + 1];
|
||||
if (inLine) {
|
||||
if (c === "\n") inLine = false;
|
||||
continue;
|
||||
}
|
||||
if (inBlock) {
|
||||
if (c === "*" && n === "/") { inBlock = false; i++; }
|
||||
continue;
|
||||
}
|
||||
if (quote) {
|
||||
if (c === "\\") { i++; continue; }
|
||||
if (c === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
||||
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
||||
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") {
|
||||
depth--;
|
||||
if (depth === 0) return i;
|
||||
}
|
||||
}
|
||||
throw new Error(`unbalanced braces at offset ${openIdx}`);
|
||||
}
|
||||
|
||||
// Extract `rateLimit({ ... })` for a limiter const, comment- and string-aware.
|
||||
function extractRateLimitExpression(constName) {
|
||||
const anchor = `const ${constName} = rateLimit(`;
|
||||
const start = indexOfOrThrow(anchor);
|
||||
const openBrace = indexSource.indexOf("{", start + anchor.length);
|
||||
assert.ok(openBrace > start, `${constName}: rateLimit({ not found`);
|
||||
const closeBrace = matchBrace(indexSource, openBrace);
|
||||
assert.strictEqual(indexSource[closeBrace + 1], ")", `${constName}: the rateLimit call must close right after the object literal`);
|
||||
return indexSource.slice(start + "const ".length + constName.length + " = ".length, closeBrace + 2);
|
||||
}
|
||||
|
||||
// Extract a limiter's keyGenerator function source (block-body or single-line
|
||||
// arrow) from inside its rateLimit({...}) expression and evaluate it against
|
||||
// the REAL ipKeyGenerator, so behavior pins exercise the shipped source.
|
||||
function extractKeyGenerator(constName, deps = {}) {
|
||||
const expr = extractRateLimitExpression(constName);
|
||||
const marker = "keyGenerator: ";
|
||||
const at = expr.indexOf(marker);
|
||||
assert.ok(at >= 0, `${constName}: no keyGenerator found`);
|
||||
const exprStart = at + marker.length;
|
||||
let fnSource;
|
||||
if (expr.startsWith("(req) => {", exprStart)) {
|
||||
const openBrace = exprStart + "(req) => ".length;
|
||||
const closeBrace = matchBrace(expr, openBrace);
|
||||
fnSource = expr.slice(exprStart, closeBrace + 1);
|
||||
} else {
|
||||
const lineEnd = expr.indexOf("\n", exprStart);
|
||||
const oneLine = expr.slice(exprStart, lineEnd);
|
||||
assert.ok(oneLine.endsWith(","), `${constName}: single-line keyGenerator must end with ,`);
|
||||
fnSource = oneLine.slice(0, -1);
|
||||
}
|
||||
return new Function(
|
||||
"ipKeyGenerator",
|
||||
"getRequestIp",
|
||||
`return ${fnSource};`
|
||||
)(ipKeyGenerator, deps.getRequestIp || ((req) => req.sourceIp));
|
||||
}
|
||||
|
||||
// Extract the shared 429 handler arrow (the client-visible contract) from
|
||||
// index.js and evaluate it with a capturing securityLog.
|
||||
function extractSharedHandler(log) {
|
||||
const anchor = `const ${SHARED_HANDLER} = (req, res, budget) => {`;
|
||||
const start = indexOfOrThrow(anchor);
|
||||
const openBrace = indexSource.indexOf("{", start + anchor.length - 1);
|
||||
const closeBrace = matchBrace(indexSource, openBrace);
|
||||
const fnSource = indexSource.slice(start + `const ${SHARED_HANDLER} = `.length, closeBrace + 1);
|
||||
return new Function("securityLog", `return ${fnSource};`)(log);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Behavior harness: evaluate BOTH shipped limiter definitions with a fake
|
||||
// Redis store injected through their buildSharedRateLimitRedisStore seam
|
||||
// (one store instance per limiter, distinct prefix — the AGENTS.md rule),
|
||||
// then run requests through them chained exactly like the route does.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
class FakeRedisStore {
|
||||
constructor(prefix) {
|
||||
this.prefix = prefix;
|
||||
this.counts = new Map();
|
||||
this.keyOrder = [];
|
||||
}
|
||||
async init() {}
|
||||
async increment(key) {
|
||||
const cur = (this.counts.get(key) || 0) + 1;
|
||||
if (!this.counts.has(key)) this.keyOrder.push(key);
|
||||
this.counts.set(key, cur);
|
||||
return { totalHits: cur, resetTime: new Date(Date.now() + 10 * 60 * 1000) };
|
||||
}
|
||||
async decrement(key) {
|
||||
this.counts.set(key, Math.max(0, (this.counts.get(key) || 1) - 1));
|
||||
}
|
||||
async resetKey(key) {
|
||||
this.counts.delete(key);
|
||||
}
|
||||
async resetAll() {
|
||||
this.counts.clear();
|
||||
}
|
||||
}
|
||||
|
||||
function buildHarness() {
|
||||
const stores = [];
|
||||
const log = [];
|
||||
const securityLog = (msg) => log.push(msg);
|
||||
const fakeHandler = extractSharedHandler(securityLog);
|
||||
const deps = {
|
||||
rateLimit,
|
||||
// Truthy so each definition takes its `redisClient ? store : undefined`
|
||||
// branch and the builder hands out ONE distinct instance per limiter.
|
||||
redisClient: { isReady: true },
|
||||
buildSharedRateLimitRedisStore: (prefix) => {
|
||||
const store = new FakeRedisStore(prefix);
|
||||
stores.push(store);
|
||||
return store;
|
||||
},
|
||||
securityLog,
|
||||
getRequestIp: (req) => req.sourceIp,
|
||||
ipKeyGenerator,
|
||||
[SHARED_HANDLER]: fakeHandler
|
||||
};
|
||||
const account = new Function(
|
||||
"rateLimit", "buildSharedRateLimitRedisStore", "redisClient",
|
||||
"securityLog", "getRequestIp", "ipKeyGenerator", SHARED_HANDLER,
|
||||
`return (${extractRateLimitExpression(ACCOUNT_LIMITER)});`
|
||||
)(deps.rateLimit, deps.buildSharedRateLimitRedisStore, deps.redisClient, deps.securityLog, deps.getRequestIp, deps.ipKeyGenerator, deps[SHARED_HANDLER]);
|
||||
const ip = new Function(
|
||||
"rateLimit", "buildSharedRateLimitRedisStore", "redisClient",
|
||||
"securityLog", "getRequestIp", "ipKeyGenerator", SHARED_HANDLER,
|
||||
`return (${extractRateLimitExpression(IP_LIMITER)});`
|
||||
)(deps.rateLimit, deps.buildSharedRateLimitRedisStore, deps.redisClient, deps.securityLog, deps.getRequestIp, deps.ipKeyGenerator, deps[SHARED_HANDLER]);
|
||||
|
||||
async function run({ sourceIp, sessionUser, sessionID }) {
|
||||
return new Promise((resolve, reject) => {
|
||||
const out = { status: null, body: null, headers: {}, nexted: false };
|
||||
const res = {
|
||||
setHeader: (k, v) => { out.headers[k] = v; },
|
||||
on() { return this; },
|
||||
status(code) {
|
||||
out.status = code;
|
||||
return { json(b) { out.body = b; resolve(out); } };
|
||||
}
|
||||
};
|
||||
const req = {
|
||||
sourceIp,
|
||||
session: sessionUser === undefined ? undefined : { user: sessionUser },
|
||||
sessionID: sessionID || "s0",
|
||||
headers: {},
|
||||
method: "POST",
|
||||
url: "/api/admin/user/create",
|
||||
ip: sourceIp,
|
||||
socket: { remoteAddress: sourceIp }
|
||||
};
|
||||
// The route's chain: account budget first, then the host bucket.
|
||||
account(req, res, () => ip(req, res, () => { out.nexted = true; resolve(out); }));
|
||||
setTimeout(() => reject(new Error("limiter did not settle")), 1000);
|
||||
});
|
||||
}
|
||||
|
||||
const storeFor = (prefix) => {
|
||||
const s = stores.find((st) => st.prefix === prefix);
|
||||
assert.ok(s, `no fake store was built for prefix ${prefix}`);
|
||||
return s;
|
||||
};
|
||||
return { run, storeFor, stores, log };
|
||||
}
|
||||
|
||||
const IP_ROTATION = [
|
||||
"192.0.2.1", // IPv4
|
||||
"2001:db8::1", // IPv6 /56 A
|
||||
"2001:db8::ffff", // IPv6 /56 A (rotated within the /56)
|
||||
"2001:db8:0:100::1", // IPv6 /56 B (rotated across /56s)
|
||||
"198.51.100.9", // IPv4
|
||||
"203.0.113.7", // IPv4
|
||||
"2001:db8:0:200::9" // IPv6 /56 C
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Source pins: the old limiter is fully replaced, both new budgets exist.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the old IP+email+sid limiter is fully replaced (no dead third limiter)", () => {
|
||||
assert.strictEqual(
|
||||
countOccurrences("const adminUserCreateRateLimiter = rateLimit({"),
|
||||
0,
|
||||
"the old single-budget definition must be gone"
|
||||
);
|
||||
assert.strictEqual(
|
||||
countOccurrences("adminUserCreateRateLimiter"),
|
||||
0,
|
||||
"no reference to the old limiter identifier may survive (note: the new names contain 'Account'/'Ip' so a substring hit means a stale reference)"
|
||||
);
|
||||
assert.strictEqual(
|
||||
countOccurrences("admin-user-create:${ip}:${email}:${sid}"),
|
||||
0,
|
||||
"the raw unbucketed-IP key template must be gone"
|
||||
);
|
||||
});
|
||||
|
||||
test("both new limiters exist with the mandated budgets and no skip", () => {
|
||||
const acctExpr = extractRateLimitExpression(ACCOUNT_LIMITER);
|
||||
const ipExpr = extractRateLimitExpression(IP_LIMITER);
|
||||
for (const [name, expr, max] of [[ACCOUNT_LIMITER, acctExpr, "max: 6"], [IP_LIMITER, ipExpr, "max: 24"]]) {
|
||||
assert.ok(expr.includes("windowMs: 10 * 60 * 1000"), `${name}: windowMs must stay 10 minutes`);
|
||||
assert.ok(expr.includes(max), `${name}: ${max}`);
|
||||
assert.ok(expr.includes("standardHeaders: true") && expr.includes("legacyHeaders: false"), `${name}: header posture unchanged`);
|
||||
assert.ok(expr.includes("passOnStoreError: true"), `${name}: store outage must not lock admins out`);
|
||||
assert.ok(
|
||||
!/\bskip\s*:/.test(expr),
|
||||
`${name}: must NOT skip — it runs before the route's 401, so unauthenticated hits still count`
|
||||
);
|
||||
}
|
||||
assert.ok(
|
||||
acctExpr.includes('buildSharedRateLimitRedisStore("admin-user-create-acct:")'),
|
||||
"account limiter: its OWN store instance with its distinct prefix"
|
||||
);
|
||||
assert.ok(
|
||||
ipExpr.includes('buildSharedRateLimitRedisStore("admin-user-create-ip:")'),
|
||||
"ip limiter: its OWN store instance with its distinct prefix"
|
||||
);
|
||||
});
|
||||
|
||||
test("the adpanel:admin-create-throttle-identity comment documents the arithmetic and identity-vs-cost rationale", () => {
|
||||
assert.ok(
|
||||
countOccurrences("// adpanel:admin-create-throttle-identity") >= 2,
|
||||
"both limiter definitions carry the constraint tag"
|
||||
);
|
||||
// The stable-identity rationale (the audit finding itself).
|
||||
for (const fragment of [
|
||||
"including within the same /56",
|
||||
"re-login",
|
||||
"OPERATION budget",
|
||||
"sessionRevoke2faSessionRateLimiter",
|
||||
"sessionRevoke2faEmailRateLimiter",
|
||||
"nothing is broadly raised"
|
||||
]) {
|
||||
assert.ok(indexSource.includes(fragment), `the doctrine comment must explain: ${fragment}`);
|
||||
}
|
||||
});
|
||||
|
||||
test("one shared 429 handler; the client-visible text is byte-identical and appears once", () => {
|
||||
assert.strictEqual(
|
||||
countOccurrences(`res.status(429).json({ error: "${CLIENT_429_TEXT}" });`),
|
||||
1,
|
||||
"the pre-existing 429 wording must exist exactly once (the shared handler) — settings.js renders data.error verbatim"
|
||||
);
|
||||
const acctExpr = extractRateLimitExpression(ACCOUNT_LIMITER);
|
||||
const ipExpr = extractRateLimitExpression(IP_LIMITER);
|
||||
assert.ok(acctExpr.includes(`${SHARED_HANDLER}(req, res, "account")`), "account limiter routes through the shared handler");
|
||||
assert.ok(ipExpr.includes(`${SHARED_HANDLER}(req, res, "ip")`), "ip limiter routes through the shared handler");
|
||||
});
|
||||
|
||||
test("the route chains both new limiters in order, before auth, with the step-up chain byte-unchanged", () => {
|
||||
indexOfOrThrow(
|
||||
`app.post("/api/admin/user/create", ${ACCOUNT_LIMITER}, ${IP_LIMITER}, async (req, res) => {`
|
||||
);
|
||||
// The route's guard chain, action-token gate and step-up fields are
|
||||
// byte-unchanged (this fix touches ONLY the limiter chain).
|
||||
indexOfOrThrow('if (!req.session || !req.session.user) {\n return res.status(401).json({ error: "Not authenticated" });');
|
||||
indexOfOrThrow('if (!await requireActionTokenOr403(req, res, "POST /api/admin/user/create")) return;');
|
||||
indexOfOrThrow("const { email, password, confirmPassword, role: rawRole, adminPassword, adminTwoFactorCode } = req.body || {};");
|
||||
// Step-up stays scoped to the admin role only (user creation deliberately
|
||||
// has no step-up beyond session+admin+action-token).
|
||||
const routeStart = indexOfOrThrow('app.post("/api/admin/user/create"');
|
||||
const routeWindow = indexSource.slice(routeStart, routeStart + 6000);
|
||||
assert.ok(routeWindow.includes('if (role === "admin") {'), "step-up must stay inside the admin-role branch");
|
||||
indexOfOrThrow("verifyAdminProvisioningStepUp(req, currentAdmin, adminPassword, adminTwoFactorCode)");
|
||||
indexOfOrThrow("async function verifyAdminProvisioningStepUp(req, adminUser, adminPassword, adminTwoFactorCode) {");
|
||||
indexOfOrThrow('bcrypt.compare(String(adminPassword), String(adminUser.password || ""))');
|
||||
});
|
||||
|
||||
test("the step-up verification limiters keep their separate budgets (creation is the operation budget, not the verification cost)", () => {
|
||||
const sessionExpr = extractRateLimitExpression("sessionRevoke2faSessionRateLimiter");
|
||||
const emailExpr = extractRateLimitExpression("sessionRevoke2faEmailRateLimiter");
|
||||
assert.ok(sessionExpr.includes("max: 8") && sessionExpr.includes("session-revoke-verify:${email}:${sid}"), "8/session verification budget untouched");
|
||||
assert.ok(emailExpr.includes("max: 24") && emailExpr.includes("session-revoke-verify-email:${email}"), "24/account verification budget untouched");
|
||||
assert.ok(sessionExpr.includes("skip: (req) => !hasDestructiveActionCredentialPayload(req)"), "session verification limiter still counts only credential-bearing requests");
|
||||
assert.ok(emailExpr.includes("skip: (req) => !hasDestructiveActionCredentialPayload(req)"), "account verification limiter still counts only credential-bearing requests");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// KeyGenerator behavior pins (shipped source + real ipKeyGenerator).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("THE AUDIT HOLE — the old raw-IP key reset the budget on address rotation; the account key does not", () => {
|
||||
// Re-typed copy of the OLD keyGenerator, used only to demonstrate the hole
|
||||
// this fix closes (the shipped raw shape is pinned gone above; every
|
||||
// behavior pin below runs the SHIPPED account keyGenerator).
|
||||
const oldKeyGen = new Function(
|
||||
"ipKeyGenerator",
|
||||
"getRequestIp",
|
||||
"return (req) => {\n const ip = getRequestIp(req);\n const email = String(req.session?.user || \"anon\").trim().toLowerCase();\n const sid = String(req.sessionID || \"no-session\");\n return `admin-user-create:${ip}:${email}:${sid}`;\n};"
|
||||
)(ipKeyGenerator, (req) => req.sourceIp);
|
||||
const oldKeys = new Set(IP_ROTATION.map((ip) => oldKeyGen({ sourceIp: ip, session: { user: "ops@example.com" }, sessionID: "s1" })));
|
||||
assert.strictEqual(oldKeys.size, IP_ROTATION.length, "old shape: every rotated address minted a fresh 6-attempt budget");
|
||||
|
||||
const keyGen = extractKeyGenerator(ACCOUNT_LIMITER);
|
||||
const newKeys = new Set(IP_ROTATION.map((ip) => keyGen({ sourceIp: ip, session: { user: "ops@example.com" }, sessionID: "s1" })));
|
||||
assert.strictEqual(newKeys.size, 1, "shipped account key: identical across IPv4, intra-/56 and cross-/56 rotation");
|
||||
assert.ok(newKeys.has("admin-user-create-acct:ops@example.com"), "the account key is the stable email identity");
|
||||
});
|
||||
|
||||
test("re-login (new sid) leaves the account key unchanged", () => {
|
||||
const keyGen = extractKeyGenerator(ACCOUNT_LIMITER);
|
||||
assert.strictEqual(
|
||||
keyGen({ sourceIp: "192.0.2.1", session: { user: "ops@example.com" }, sessionID: "before-relogin" }),
|
||||
keyGen({ sourceIp: "192.0.2.1", session: { user: "ops@example.com" }, sessionID: "after-relogin" }),
|
||||
"the account budget survives session churn (no sid in the key)"
|
||||
);
|
||||
});
|
||||
|
||||
test("IP limiter: same /56 one bucket, different /56 different bucket, IPv4 passthrough", () => {
|
||||
const keyGen = extractKeyGenerator(IP_LIMITER);
|
||||
assert.strictEqual(keyGen({ sourceIp: "2001:db8::1" }), keyGen({ sourceIp: "2001:db8::ffff" }), "one /56, one host bucket");
|
||||
assert.strictEqual(keyGen({ sourceIp: "2001:db8::1" }), "admin-user-create-ip:2001:db8::/56", "the /56 bucket lands in the key with the prefix preserved");
|
||||
assert.notStrictEqual(keyGen({ sourceIp: "2001:db8::1" }), keyGen({ sourceIp: "2001:db8:0:100::1" }), "a different /56 is a different bucket");
|
||||
assert.strictEqual(keyGen({ sourceIp: "192.0.2.1" }), "admin-user-create-ip:192.0.2.1", "IPv4 passthrough (byte-identical to raw form)");
|
||||
});
|
||||
|
||||
test("anon (no session): both keys fall back to IP-bucket identity and are never empty", () => {
|
||||
const acctKeyGen = extractKeyGenerator(ACCOUNT_LIMITER);
|
||||
const ipKeyGen = extractKeyGenerator(IP_LIMITER);
|
||||
assert.strictEqual(acctKeyGen({ sourceIp: "2001:db8::1", session: undefined }), "admin-user-create-acct:ip:2001:db8::/56", "anon account hits count on the /56-bucketed fallback");
|
||||
assert.strictEqual(ipKeyGen({ sourceIp: "2001:db8::1", session: undefined }), "admin-user-create-ip:2001:db8::/56", "anon ip-limiter key is the /56 bucket");
|
||||
for (const keyGen of [acctKeyGen, ipKeyGen]) {
|
||||
const missingIp = keyGen({ sourceIp: undefined, session: undefined });
|
||||
const emptyIp = keyGen({ sourceIp: "", session: undefined });
|
||||
assert.ok(missingIp.length > 0 && emptyIp.length > 0, "keys must never be empty (v8 validation)");
|
||||
assert.ok(missingIp.endsWith("unknown") && emptyIp.endsWith("unknown"), "missing/blank source IP falls back to the non-empty unknown bucket");
|
||||
}
|
||||
// Whitespace-only session user must not mint an empty email component.
|
||||
assert.strictEqual(
|
||||
acctKeyGen({ sourceIp: "192.0.2.1", session: { user: " " } }),
|
||||
"admin-user-create-acct:ip:192.0.2.1",
|
||||
"a whitespace session user takes the IP-bucket fallback, never an empty key"
|
||||
);
|
||||
// The email key and the anon fallback namespace stay disjoint, and the two
|
||||
// limiter prefixes stay disjoint (no cross-surface counter sharing).
|
||||
assert.notStrictEqual(
|
||||
acctKeyGen({ sourceIp: "192.0.2.1", session: undefined }),
|
||||
ipKeyGen({ sourceIp: "192.0.2.1", session: undefined }),
|
||||
"account fallback and host bucket are distinct keys"
|
||||
);
|
||||
assert.notStrictEqual(
|
||||
acctKeyGen({ sourceIp: "192.0.2.1", session: { user: "192.0.2.1" } }),
|
||||
ipKeyGen({ sourceIp: "192.0.2.1" }),
|
||||
"an email that echoes the IP text still keys differently from the host bucket"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Behavior pins against a fake Redis store through the shipped seam.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("6 account-budget creations pass across rotating IPs; the 7th from a fresh IP is refused", async () => {
|
||||
const h = buildHarness();
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const out = await h.run({ sourceIp: IP_ROTATION[i], sessionUser: "ops@example.com", sessionID: "s1" });
|
||||
assert.ok(out.nexted, `creation ${i + 1} from ${IP_ROTATION[i]} must pass`);
|
||||
assert.strictEqual(out.status, null, `creation ${i + 1} must not be refused`);
|
||||
}
|
||||
// Each presented a DIFFERENT source IP — the old limiter would have 6 keys.
|
||||
const acctStore = h.storeFor("admin-user-create-acct:");
|
||||
assert.strictEqual(acctStore.counts.size, 1, "all six rotating addresses share ONE account counter");
|
||||
assert.strictEqual(acctStore.counts.get("admin-user-create-acct:ops@example.com"), 6, "the account counter charged every attempt");
|
||||
const out7 = await h.run({ sourceIp: IP_ROTATION[6], sessionUser: "ops@example.com", sessionID: "s1" });
|
||||
assert.strictEqual(out7.status, 429, "the 7th creation is refused even from a yet another fresh IP");
|
||||
assert.strictEqual(out7.body.error, CLIENT_429_TEXT, "the 429 body is the byte-identical pre-existing wording");
|
||||
assert.ok(!out7.nexted, "the refused request does not reach the route");
|
||||
assert.strictEqual(acctStore.counts.get("admin-user-create-acct:ops@example.com"), 7, "the refused attempt is still charged to the account");
|
||||
// The host bucket only saw the six admitted requests (the 7th was stopped
|
||||
// by the account limiter first).
|
||||
const ipStore = h.storeFor("admin-user-create-ip:");
|
||||
const ipTotal = [...ipStore.counts.values()].reduce((a, b) => a + b, 0);
|
||||
assert.strictEqual(ipTotal, 6, "the IP bucket counted exactly the admitted requests");
|
||||
});
|
||||
|
||||
test("re-login + IP rotation together cannot reset the account budget", async () => {
|
||||
const h = buildHarness();
|
||||
// Six attempts, each with a DIFFERENT session id (re-login churn) AND a
|
||||
// different source IP — the old key had a fresh budget for every one.
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const out = await h.run({ sourceIp: IP_ROTATION[i], sessionUser: "ops@example.com", sessionID: `session-${i}` });
|
||||
assert.ok(out.nexted, `churned attempt ${i + 1} must pass`);
|
||||
}
|
||||
const out7 = await h.run({ sourceIp: IP_ROTATION[6], sessionUser: "ops@example.com", sessionID: "session-6" });
|
||||
assert.strictEqual(out7.status, 429, "the 7th attempt after full session churn is still refused");
|
||||
const acctStore = h.storeFor("admin-user-create-acct:");
|
||||
assert.strictEqual(acctStore.counts.size, 1, "one account counter across all sessions and addresses");
|
||||
});
|
||||
|
||||
test("the IP bucket admits 24 different accounts from one host, then refuses the 25th (NAT-tolerant)", async () => {
|
||||
const h = buildHarness();
|
||||
for (let i = 0; i < 24; i++) {
|
||||
const out = await h.run({ sourceIp: "2001:db8::1", sessionUser: `admin${i}@example.com`, sessionID: `sid-${i}` });
|
||||
assert.ok(out.nexted, `account ${i + 1} behind the shared host must pass`);
|
||||
}
|
||||
const out25 = await h.run({ sourceIp: "2001:db8::1", sessionUser: "admin24@example.com", sessionID: "sid-24" });
|
||||
assert.strictEqual(out25.status, 429, "the 25th distinct account from one host hits the host bucket");
|
||||
assert.strictEqual(out25.body.error, CLIENT_429_TEXT, "the host-bucket 429 reuses the same wording");
|
||||
const ipStore = h.storeFor("admin-user-create-ip:");
|
||||
assert.strictEqual(ipStore.counts.size, 1, "one host-bucket counter for the whole /56");
|
||||
assert.strictEqual(ipStore.counts.get("admin-user-create-ip:2001:db8::/56"), 25, "the host bucket charged all 25 attempts");
|
||||
const acctStore = h.storeFor("admin-user-create-acct:");
|
||||
assert.strictEqual(acctStore.counts.size, 25, "each account was charged its own single attempt");
|
||||
});
|
||||
|
||||
test("distinct hosts keep distinct IP budgets; IPv4 hosts are unmerged", async () => {
|
||||
const h = buildHarness();
|
||||
const hosts = ["2001:db8::1", "2001:db8:0:100::1", "192.0.2.1", "198.51.100.9"];
|
||||
for (const host of hosts) {
|
||||
const out = await h.run({ sourceIp: host, sessionUser: `ops-${host}@example.com`, sessionID: "s1" });
|
||||
assert.ok(out.nexted, `a different host starts with its own budget: ${host}`);
|
||||
}
|
||||
const ipStore = h.storeFor("admin-user-create-ip:");
|
||||
assert.strictEqual(ipStore.counts.size, 4, "four hosts, four counters (intra-/56 rotation would merge, these differ)");
|
||||
});
|
||||
Reference in new issue
Block a user