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,488 @@
|
||||
"use strict";
|
||||
|
||||
// adpanel:limiter-ipv6-bucketing — source + behavior pins for pre-auth
|
||||
// limiter IP keying. Reads index.js as text, like the other audit tests.
|
||||
//
|
||||
// Constraint under test: EVERY pre-auth budget keyed on the source IP must
|
||||
// bucket with ipKeyGenerator exactly like the login throttle
|
||||
// (utils/login-throttle.js — IPv6 /56). A raw getRequestIp key lets one IPv6
|
||||
// host rotate /64s and mint a fresh counter per address, multiplying its
|
||||
// budget; ipKeyGenerator collapses those to one /56 key while leaving IPv4
|
||||
// keys byte-identical to the raw form (so IPv4 behavior, and every IPv4
|
||||
// counter window, is unchanged). The key-shape change resets existing IPv6
|
||||
// counter windows once on deploy — acceptable for an always-on abuse brake.
|
||||
//
|
||||
// Second finding pinned here (adpanel:preauth-500-no-proxy-detail): the
|
||||
// pre-auth POST /login 500 for a pinned SESSION_COOKIE_SECURE + non-HTTPS
|
||||
// request must keep the reverse-proxy/XFP diagnostic server-side
|
||||
// (console.error) and return the handler's generic body — the misconfiguration
|
||||
// text disclosed proxy-trust detail to unauthenticated callers.
|
||||
|
||||
const test = require("node:test");
|
||||
const assert = require("node:assert");
|
||||
const fs = require("node:fs");
|
||||
const path = require("node:path");
|
||||
|
||||
const ROOT = path.join(__dirname, "..");
|
||||
const INDEX_JS = path.join(ROOT, "index.js");
|
||||
const indexSource = fs.readFileSync(INDEX_JS, "utf8");
|
||||
const { ipKeyGenerator } = require("express-rate-limit");
|
||||
|
||||
function indexOfOrThrow(needle, from = 0) {
|
||||
const idx = indexSource.indexOf(needle, from);
|
||||
assert.ok(idx >= 0, `expected source pin not found: ${needle}`);
|
||||
return idx;
|
||||
}
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
// The canonical wrapping shape lives in utils/login-throttle.js; the
|
||||
// pre-auth limiters must wrap identically (modulo the request identifier).
|
||||
const loginThrottleSource = fs.readFileSync(path.join(ROOT, "utils", "login-throttle.js"), "utf8");
|
||||
|
||||
// Extract a limiter's keyGenerator arrow from the index.js source text and
|
||||
// evaluate it against the REAL ipKeyGenerator so the behavior pins exercise
|
||||
// the shipped source, not a re-typed copy of it.
|
||||
function extractKeyGenerator(prefix) {
|
||||
const marker = `keyGenerator: (req) => \`${prefix}:`;
|
||||
const start = indexOfOrThrow(marker);
|
||||
const close = indexSource.indexOf("`,", start);
|
||||
assert.ok(close > start, `keyGenerator for ${prefix} must end with \`,`);
|
||||
const fnSource = indexSource.slice(start + "keyGenerator: ".length, close + 1);
|
||||
return new Function(
|
||||
"ipKeyGenerator",
|
||||
"getRequestIp",
|
||||
`return ${fnSource};`
|
||||
)(ipKeyGenerator, (req) => req.sourceIp);
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FIX 1 — source pins: both pre-auth limiters bucket exactly like the login
|
||||
// throttle, the raw shapes are gone, and the change is documented.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("both pre-auth limiters key on ipKeyGenerator(getRequestIp(...)) in the login-throttle shape", () => {
|
||||
// The shared import index.js already relies on (also pinned by
|
||||
// tests/login-throttle-wiring.test.js).
|
||||
indexOfOrThrow('const { ipKeyGenerator, MemoryStore } = require("express-rate-limit");');
|
||||
const captchaLine = 'keyGenerator: (req) => `captcha-verify:${ipKeyGenerator(String(getRequestIp(req) || "unknown"))}`,';
|
||||
const brandingLine = 'keyGenerator: (req) => `branding-asset:${ipKeyGenerator(String(getRequestIp(req) || "unknown"))}`,';
|
||||
indexOfOrThrow(captchaLine);
|
||||
indexOfOrThrow(brandingLine);
|
||||
// Same wrapping expression as the canonical login limiter (utils/login-throttle.js),
|
||||
// modulo the request identifier (req vs request).
|
||||
const canonical = 'ipKeyGenerator(String(getRequestIp(request) || "unknown"))';
|
||||
assert.ok(
|
||||
loginThrottleSource.includes(`login-req:\${${canonical}}`),
|
||||
"utils/login-throttle.js must keep the canonical bucketed login-req shape"
|
||||
);
|
||||
const normalized = captchaLine.replace("(req)", "(request)").replace("getRequestIp(req)", "getRequestIp(request)");
|
||||
assert.ok(
|
||||
normalized.includes(canonical),
|
||||
"the captcha limiter's wrapping expression must equal the login throttle's (identifier-normalized)"
|
||||
);
|
||||
// The raw getRequestIp keys must be gone everywhere (no sibling re-drift).
|
||||
assert.strictEqual(countOccurrences("`captcha-verify:${getRequestIp(req)}`"), 0, "raw captcha key must be gone");
|
||||
assert.strictEqual(countOccurrences("`branding-asset:${getRequestIp(req)}`"), 0, "raw branding key must be gone");
|
||||
});
|
||||
|
||||
test("both limiters carry the adpanel:limiter-ipv6-bucketing constraint comment", () => {
|
||||
assert.ok(
|
||||
countOccurrences("// adpanel:limiter-ipv6-bucketing") >= 4,
|
||||
"each re-keyed limiter documents the bucketing constraint (captcha, branding, status, activity)"
|
||||
);
|
||||
// The comment must note the one-time counter-window reset (deploy note).
|
||||
assert.ok(
|
||||
indexSource.includes("existing counter windows reset once on deploy"),
|
||||
"the key-shape change must be documented as resetting existing counter windows"
|
||||
);
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FIX 1 — behavior pins via the extracted keyGenerator + the real
|
||||
// ipKeyGenerator: IPv6 /56 bucketing, IPv4 passthrough, prefixes preserved.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("captcha limiter: IPv6 addresses in one /56 share a key; different /56s differ", () => {
|
||||
const keyGen = extractKeyGenerator("captcha-verify");
|
||||
const same56a = keyGen({ sourceIp: "2001:db8::1" });
|
||||
const same56b = keyGen({ sourceIp: "2001:db8::ffff" });
|
||||
assert.strictEqual(same56a, same56b, "2001:db8::1 and 2001:db8::ffff must share one /56 bucket");
|
||||
assert.strictEqual(same56a, "captcha-verify:2001:db8::/56", "the /56 bucket lands in the key with the prefix preserved");
|
||||
const other56 = keyGen({ sourceIp: "2001:db8:0:100::1" });
|
||||
assert.notStrictEqual(same56a, other56, "a different /56 must be a different key");
|
||||
});
|
||||
|
||||
test("captcha limiter: IPv4 keys pass through unchanged (identical to the old raw keying)", () => {
|
||||
const keyGen = extractKeyGenerator("captcha-verify");
|
||||
assert.strictEqual(keyGen({ sourceIp: "192.0.2.1" }), "captcha-verify:192.0.2.1", "IPv4 key is byte-identical to the raw form");
|
||||
assert.notStrictEqual(
|
||||
keyGen({ sourceIp: "192.0.2.1" }),
|
||||
keyGen({ sourceIp: "192.0.2.99" }),
|
||||
"distinct IPv4 hosts stay distinct keys"
|
||||
);
|
||||
});
|
||||
|
||||
test("branding limiter: same /56 bucketing, IPv4 passthrough, prefix preserved", () => {
|
||||
const keyGen = extractKeyGenerator("branding-asset");
|
||||
assert.strictEqual(
|
||||
keyGen({ sourceIp: "2001:db8::1" }),
|
||||
keyGen({ sourceIp: "2001:db8::ffff" }),
|
||||
"one /56, one key"
|
||||
);
|
||||
assert.strictEqual(keyGen({ sourceIp: "2001:db8::1" }), "branding-asset:2001:db8::/56");
|
||||
assert.notStrictEqual(
|
||||
keyGen({ sourceIp: "2001:db8::1" }),
|
||||
keyGen({ sourceIp: "2001:db8:0:100::1" }),
|
||||
"different /56s differ"
|
||||
);
|
||||
assert.strictEqual(keyGen({ sourceIp: "192.0.2.1" }), "branding-asset:192.0.2.1", "IPv4 passthrough");
|
||||
});
|
||||
|
||||
test("the two limiters keep distinct key prefixes (no cross-surface counter sharing)", () => {
|
||||
const captcha = extractKeyGenerator("captcha-verify")({ sourceIp: "2001:db8::1" });
|
||||
const branding = extractKeyGenerator("branding-asset")({ sourceIp: "2001:db8::1" });
|
||||
assert.ok(captcha.startsWith("captcha-verify:"), "captcha prefix preserved");
|
||||
assert.ok(branding.startsWith("branding-asset:"), "branding prefix preserved");
|
||||
assert.notStrictEqual(captcha, branding, "same source must not consume both budgets through one key");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// The status/activity pair: these limiters are mounted BEFORE their handlers
|
||||
// authenticate inline, so unauthenticated callers are budgeted on their IP
|
||||
// component alone. Their keys are IP+session composites — only the IP part
|
||||
// moves to the bucketed shape; the session-user component keeps its exact
|
||||
// shape, separator and position (adpanel:limiter-ipv6-bucketing).
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("status/activity limiters wrap the IP inside their existing IP+session templates", () => {
|
||||
const statusLine = 'keyGenerator: (req) => `status:${ipKeyGenerator(String(getRequestIp(req) || "unknown"))}:${req.session?.user || \'anon\'}`,';
|
||||
const activityLine = 'keyGenerator: (req) => `activity:${ipKeyGenerator(String(getRequestIp(req) || "unknown"))}:${req.session?.user || \'anon\'}`,';
|
||||
indexOfOrThrow(statusLine);
|
||||
indexOfOrThrow(activityLine);
|
||||
// Same wrapping expression as the canonical login limiter
|
||||
// (utils/login-throttle.js), identifier-normalized (req vs request).
|
||||
const canonical = 'ipKeyGenerator(String(getRequestIp(request) || "unknown"))';
|
||||
for (const [prefix, line] of [["status", statusLine], ["activity", activityLine]]) {
|
||||
const normalized = line.replace("(req)", "(request)").replace("getRequestIp(req)", "getRequestIp(request)");
|
||||
assert.ok(
|
||||
normalized.includes(canonical),
|
||||
`the ${prefix} limiter's wrapping expression must equal the login throttle's (identifier-normalized)`
|
||||
);
|
||||
}
|
||||
// The raw getRequestIp keys must be gone everywhere (no sibling re-drift).
|
||||
assert.strictEqual(countOccurrences("`status:${getRequestIp(req)}:`"), 0, "raw status key must be gone");
|
||||
assert.strictEqual(countOccurrences("`activity:${getRequestIp(req)}:`"), 0, "raw activity key must be gone");
|
||||
});
|
||||
|
||||
// Shared behavior pins: the extracted keyGenerator runs against the REAL
|
||||
// ipKeyGenerator, exercising the shipped source. Anonymous = no session
|
||||
// (the template's own `|| 'anon'` marker); authenticated = a session-user-ish
|
||||
// req per the actual template.
|
||||
function assertIpSessionBucketing(prefix) {
|
||||
const keyGen = extractKeyGenerator(prefix);
|
||||
const anon = (sourceIp) => keyGen({ sourceIp, session: undefined });
|
||||
// Anonymous IPv6 /64 rotation: one /56, one key.
|
||||
assert.strictEqual(
|
||||
anon("2001:db8::1"), anon("2001:db8::ffff"),
|
||||
`${prefix}: rotating IPv6 hosts inside one /56 must share one anonymous key`
|
||||
);
|
||||
assert.strictEqual(anon("2001:db8::1"), `${prefix}:2001:db8::/56:anon`, `${prefix}: prefix and anonymous marker preserved`);
|
||||
assert.notStrictEqual(
|
||||
anon("2001:db8::1"), anon("2001:db8:0:100::1"),
|
||||
`${prefix}: a different /56 must be a different key`
|
||||
);
|
||||
// IPv4 passthrough: byte-identical to the old raw keying.
|
||||
assert.strictEqual(anon("192.0.2.1"), `${prefix}:192.0.2.1:anon`, `${prefix}: IPv4 key is unchanged from the raw form`);
|
||||
// The session-user component keeps its exact shape, separator and position.
|
||||
assert.strictEqual(
|
||||
keyGen({ sourceIp: "192.0.2.1", session: { user: "ops@example.com" } }),
|
||||
`${prefix}:192.0.2.1:ops@example.com`,
|
||||
`${prefix}: session-user component preserved verbatim`
|
||||
);
|
||||
assert.strictEqual(
|
||||
keyGen({ sourceIp: "2001:db8::1", session: { user: "ops@example.com" } }),
|
||||
`${prefix}:2001:db8::/56:ops@example.com`,
|
||||
`${prefix}: authenticated IPv6 callers bucket with the user component intact`
|
||||
);
|
||||
// IP+session composition preserved: distinct users behind one bucket stay
|
||||
// distinct keys (the per-identity budget the limiters were built for).
|
||||
assert.notStrictEqual(
|
||||
keyGen({ sourceIp: "2001:db8::1", session: { user: "ops@example.com" } }),
|
||||
keyGen({ sourceIp: "2001:db8::1", session: { user: "other@example.com" } }),
|
||||
`${prefix}: distinct session users behind one bucket keep distinct keys`
|
||||
);
|
||||
}
|
||||
|
||||
test("status limiter: anonymous IPv6 /56 bucketing, IPv4 passthrough, session-user component verbatim", () => {
|
||||
assertIpSessionBucketing("status");
|
||||
});
|
||||
|
||||
test("activity limiter: anonymous IPv6 /56 bucketing, IPv4 passthrough, session-user component verbatim", () => {
|
||||
assertIpSessionBucketing("activity");
|
||||
});
|
||||
|
||||
test("the status/activity pair keeps distinct key prefixes (no cross-surface counter sharing)", () => {
|
||||
const status = extractKeyGenerator("status")({ sourceIp: "2001:db8::1", session: undefined });
|
||||
const activity = extractKeyGenerator("activity")({ sourceIp: "2001:db8::1", session: undefined });
|
||||
assert.ok(status.startsWith("status:"), "status prefix preserved");
|
||||
assert.ok(activity.startsWith("activity:"), "activity prefix preserved");
|
||||
assert.notStrictEqual(status, activity, "same source must not consume both budgets through one key");
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// FIX 2 — the pre-auth login 500 keeps proxy/XFP diagnostics server-side.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
test("the SESSION_COOKIE_SECURE 500 logs the diagnostic and returns the generic body", () => {
|
||||
const branchStart = indexOfOrThrow("if (SESSION_COOKIE_SECURE_EXPLICIT && SESSION_COOKIE_SECURE && !isActuallySecure) {");
|
||||
const branchEnd = indexSource.indexOf("\n }", branchStart);
|
||||
assert.ok(branchEnd > branchStart, "the config-error branch must close within the handler");
|
||||
const branch = indexSource.slice(branchStart, branchEnd);
|
||||
assert.ok(branch.includes('console.error("[login] config problem:'), "the full diagnostic must go to the server log");
|
||||
assert.ok(branch.includes('return sendError(500, "Internal login error.");'), "the client body must be the handler's generic 500 (status unchanged)");
|
||||
assert.ok(branch.includes("// adpanel:preauth-500-no-proxy-detail"), "the branch documents the disclosure constraint");
|
||||
});
|
||||
|
||||
test("no client-visible body carries the proxy/XFP diagnostic anywhere in index.js", () => {
|
||||
// The old capital-C "Config problem: ..." client string must be gone, and
|
||||
// the diagnostic must exist exactly once — on a console.error line.
|
||||
assert.strictEqual(countOccurrences("Config problem: SESSION_COOKIE_SECURE"), 0, "the old client-visible diagnostic string must be gone");
|
||||
assert.strictEqual(countOccurrences("set proxy trust correctly"), 1, "the diagnostic survives exactly once, server-side");
|
||||
const idx = indexSource.indexOf("set proxy trust correctly");
|
||||
const lineStart = indexSource.lastIndexOf("\n", idx) + 1;
|
||||
const lineEnd = indexSource.indexOf("\n", idx);
|
||||
const line = indexSource.slice(lineStart, lineEnd === -1 ? undefined : lineEnd).trim();
|
||||
assert.ok(line.startsWith("console.error("), `the diagnostic line must be a console.error, got: ${line.slice(0, 60)}`);
|
||||
for (const fragment of ["X-Forwarded-Proto: https or set proxy trust", "Check reverse proxy to send X-Forwarded-Proto"]) {
|
||||
const at = indexSource.indexOf(fragment);
|
||||
assert.ok(at >= 0, `diagnostic fragment expected in the server log: ${fragment}`);
|
||||
const fragLineStart = indexSource.lastIndexOf("\n", at) + 1;
|
||||
const fragLine = indexSource.slice(fragLineStart, indexSource.indexOf("\n", at)).trim();
|
||||
assert.ok(fragLine.startsWith("console.error("), `diagnostic fragment must be log-only: ${fragment}`);
|
||||
}
|
||||
// And no sendError call site anywhere contains the diagnostic fragments.
|
||||
for (const fragment of ["Config problem", "set proxy trust correctly"]) {
|
||||
let pos = 0;
|
||||
for (;;) {
|
||||
const sendErrIdx = indexSource.indexOf("sendError(", pos);
|
||||
if (sendErrIdx < 0) break;
|
||||
const callSlice = indexSource.slice(sendErrIdx, sendErrIdx + 400);
|
||||
assert.ok(!callSlice.includes(fragment), `no sendError body may carry "${fragment}"`);
|
||||
pos = sendErrIdx + 1;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// adpanel:limiter-ipv6-bucketing (app-wide in-memory limiter) +
|
||||
// adpanel:limiter-map-full-429 — the app-wide rateLimiterMiddleware keys on
|
||||
// the same /56-bucketed form the Redis-backed globalLimiter's default
|
||||
// express-rate-limit keyGenerator applies, and its map-full path refuses NEW
|
||||
// clients with the limiter's own 429 shape (Retry-After + plain-text body),
|
||||
// never the old 503 "Service Busy" (server-error semantics: load balancers
|
||||
// and monitors read it as backend-down and flap the pod out of rotation
|
||||
// while the flood persists). Disabled-by-default (security.rate_limiting),
|
||||
// the trusted-subnet bypass, the exempt-path skip list and the Redis /api
|
||||
// delegation are untouched.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Extract a full top-level function declaration by brace matching (skipping
|
||||
// line/block comments and string literals), so behavior pins evaluate the
|
||||
// SHIPPED rateLimiterMiddleware body rather than a re-typed copy of it.
|
||||
function extractFunction(name) {
|
||||
const start = indexOfOrThrow(`function ${name}(`);
|
||||
let i = indexSource.indexOf("{", start);
|
||||
let depth = 0;
|
||||
let inLine = false;
|
||||
let inBlock = false;
|
||||
let quote = null;
|
||||
for (; i < indexSource.length; i++) {
|
||||
const c = indexSource[i];
|
||||
const n = indexSource[i + 1];
|
||||
if (inLine) {
|
||||
if (c === "\n") inLine = false;
|
||||
continue;
|
||||
}
|
||||
if (inBlock) {
|
||||
if (c === "*" && n === "/") { inBlock = false; i++; }
|
||||
continue;
|
||||
}
|
||||
if (quote) {
|
||||
if (c === "\\") { i++; continue; }
|
||||
if (c === quote) quote = null;
|
||||
continue;
|
||||
}
|
||||
if (c === "/" && n === "/") { inLine = true; i++; continue; }
|
||||
if (c === "/" && n === "*") { inBlock = true; i++; continue; }
|
||||
if (c === "'" || c === '"' || c === "`") { quote = c; continue; }
|
||||
if (c === "{") depth++;
|
||||
else if (c === "}") {
|
||||
depth--;
|
||||
if (depth === 0) return indexSource.slice(start, i + 1);
|
||||
}
|
||||
}
|
||||
throw new Error(`unbalanced braces while extracting ${name}`);
|
||||
}
|
||||
|
||||
const rateLimiterSource = extractFunction("rateLimiterMiddleware");
|
||||
|
||||
test("the app-wide in-memory limiter keys on the bucketed form and the 503 map-full path is gone", () => {
|
||||
assert.ok(
|
||||
rateLimiterSource.includes('const ip = ipKeyGenerator(String(getRequestIp(req) || "unknown"));'),
|
||||
"rateLimiterMiddleware must derive its key through the canonical bucketed wrapper"
|
||||
);
|
||||
assert.ok(
|
||||
!rateLimiterSource.includes("const ip = getRequestIp(req);"),
|
||||
"the raw key derivation must be gone"
|
||||
);
|
||||
assert.strictEqual(
|
||||
(rateLimiterSource.match(/getRequestIp\(req\)/g) || []).length,
|
||||
1,
|
||||
"the middleware derives the key exactly once, through the wrapper"
|
||||
);
|
||||
assert.ok(
|
||||
rateLimiterSource.includes('res.status(429).send("429 Too Many Requests")'),
|
||||
"the limiter's own 429 shape survives"
|
||||
);
|
||||
assert.ok(
|
||||
!rateLimiterSource.includes("res.status(503)"),
|
||||
"the map-full path must not answer 503 (the word survives only inside the documenting comment; other surfaces' 503s are out of scope)"
|
||||
);
|
||||
// Disabled-by-default, trusted-subnet bypass, and exempt-path guards stay
|
||||
// intact. Redis delegation is checked by request behavior below.
|
||||
for (const guard of [
|
||||
"if (!security || security.rate_limiting !== true) return next();",
|
||||
"if (isRequestFromTrustedSubnet(req)) return next();",
|
||||
"if (isRateLimitExempt(req.path, req.method)) return next();",
|
||||
]) {
|
||||
assert.ok(rateLimiterSource.includes(guard), `untouched guard must survive verbatim: ${guard}`);
|
||||
}
|
||||
// The map-full branch carries its documenting tag and the Retry-After hint.
|
||||
assert.ok(rateLimiterSource.includes("// adpanel:limiter-map-full-429"), "the map-full branch documents the 429 constraint");
|
||||
assert.ok(rateLimiterSource.includes("// adpanel:limiter-ipv6-bucketing"), "the key derivation documents the bucketing constraint");
|
||||
const mapFullBranch = rateLimiterSource.slice(
|
||||
rateLimiterSource.indexOf("if (!rateRequests.has(ip) && rateRequests.size >= RATE_MAX_TRACKED_IPS)"),
|
||||
rateLimiterSource.indexOf("let arr = rateRequests.get(ip)")
|
||||
);
|
||||
assert.ok(mapFullBranch.includes('res.setHeader("Retry-After"'), "the map-full 429 carries a Retry-After hint");
|
||||
assert.ok(mapFullBranch.includes('res.status(429).send("429 Too Many Requests")'), "the map-full branch mirrors the limiter's own 429 shape");
|
||||
});
|
||||
|
||||
// Behavior pins on the SHIPPED middleware body: injected security/map/clock,
|
||||
// real ipKeyGenerator.
|
||||
function buildRateLimiterHarness({ security, maxTrackedIps, redis = null }) {
|
||||
const rateRequests = new Map();
|
||||
const middleware = new Function(
|
||||
"security", "isRequestFromTrustedSubnet", "redisApiLimiterMounted", "redisClient",
|
||||
"isRateLimitExempt", "rateRequests", "RATE_MAX_TRACKED_IPS", "getRequestIp", "ipKeyGenerator", "Date",
|
||||
`${rateLimiterSource}
|
||||
return rateLimiterMiddleware;`
|
||||
)(
|
||||
security,
|
||||
() => false,
|
||||
redis !== null,
|
||||
redis,
|
||||
() => false,
|
||||
rateRequests,
|
||||
maxTrackedIps,
|
||||
(req) => req.sourceIp,
|
||||
ipKeyGenerator,
|
||||
Date
|
||||
);
|
||||
return {
|
||||
rateRequests,
|
||||
request(sourceIp, path = "/dashboard") {
|
||||
const out = { headers: {}, status: null, body: null, nextCalled: false };
|
||||
const res = {
|
||||
setHeader: (k, v) => { out.headers[k] = v; },
|
||||
status(code) { out.status = code; return { send(body) { out.body = body; } }; },
|
||||
};
|
||||
middleware({ sourceIp, path }, res, () => { out.nextCalled = true; });
|
||||
return out;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const ENABLED_SECURITY = { rate_limiting: true, window_seconds: 120, limit: 25 };
|
||||
|
||||
test("app-wide limiter: a ready Redis mount owns all API spellings; its fallback still works", () => {
|
||||
const ip = "192.0.2.1";
|
||||
const redis = { isReady: true };
|
||||
const h = buildRateLimiterHarness({ security: { ...ENABLED_SECURITY, limit: 1 }, maxTrackedIps: 10, redis });
|
||||
for (const path of ["/api/settings/security", "/API/Settings/Security", "/Api"]) {
|
||||
assert.ok(h.request(ip, path).nextCalled);
|
||||
assert.strictEqual(h.rateRequests.size, 0, `${path} must not consume a second budget`);
|
||||
}
|
||||
assert.ok(h.request(ip, "/api-docs").nextCalled);
|
||||
assert.strictEqual(h.request(ip, "/settings").status, 429, "non-API pages still count in memory");
|
||||
redis.isReady = false;
|
||||
const fallbackIp = "192.0.2.2";
|
||||
assert.ok(h.request(fallbackIp, "/API/Settings/Security").nextCalled);
|
||||
assert.strictEqual(h.request(fallbackIp, "/api/settings/security").status, 429);
|
||||
});
|
||||
|
||||
test("app-wide limiter: IPv6 rotation inside one /56 shares one counter; IPv4 keys pass through", () => {
|
||||
const h = buildRateLimiterHarness({ security: ENABLED_SECURITY, maxTrackedIps: 50000 });
|
||||
for (let i = 0; i < 5; i++) {
|
||||
const out = h.request(`2001:db8::${i + 1}`);
|
||||
assert.ok(out.nextCalled, `rotating request ${i + 1} must pass (one shared budget)`);
|
||||
}
|
||||
assert.strictEqual(h.rateRequests.size, 1, "five rotating addresses collapse to ONE tracked key");
|
||||
assert.ok(h.rateRequests.has("2001:db8::/56"), "the tracked key is the /56 bucket");
|
||||
assert.notStrictEqual(
|
||||
h.request("2001:db8:0:100::1").nextCalled,
|
||||
false,
|
||||
"a different /56 is a different budget"
|
||||
);
|
||||
assert.strictEqual(h.rateRequests.get("2001:db8::/56").length, 5, "the /56 bucket counts the whole rotation");
|
||||
const v4 = h.request("192.0.2.1");
|
||||
assert.ok(v4.nextCalled, "IPv4 passes");
|
||||
assert.ok(h.rateRequests.has("192.0.2.1"), "IPv4 tracked byte-identical to the raw form");
|
||||
assert.ok(h.rateRequests.has("2001:db8:0:100::/56"), "the second /56 tracked under its bucket");
|
||||
});
|
||||
|
||||
test("app-wide limiter: over-limit still answers the limiter's own 429 shape", () => {
|
||||
const h = buildRateLimiterHarness({ security: ENABLED_SECURITY, maxTrackedIps: 50000 });
|
||||
let last = null;
|
||||
for (let i = 0; i < 26; i++) last = h.request("192.0.2.1");
|
||||
assert.strictEqual(last.status, 429, "the 26th request is refused");
|
||||
assert.strictEqual(last.body, "429 Too Many Requests", "the 429 body shape is unchanged");
|
||||
assert.ok(last.headers["Retry-After"], "the over-limit 429 carries Retry-After");
|
||||
assert.ok(!last.nextCalled, "the refused request does not reach next()");
|
||||
});
|
||||
|
||||
test("app-wide limiter: map-full refuses NEW clients with 429 (never 503) and keeps serving tracked keys", () => {
|
||||
const h = buildRateLimiterHarness({ security: ENABLED_SECURITY, maxTrackedIps: 2 });
|
||||
// Fill the map to capacity with two distinct keys.
|
||||
assert.ok(h.request("192.0.2.1").nextCalled);
|
||||
assert.ok(h.request("192.0.2.99").nextCalled);
|
||||
assert.strictEqual(h.rateRequests.size, 2);
|
||||
// A NEW client at map-full: rate-limit refusal, not a server error.
|
||||
const fresh = h.request("203.0.113.7");
|
||||
assert.strictEqual(fresh.status, 429, "map-full must answer 429, not the old 503");
|
||||
assert.strictEqual(fresh.body, "429 Too Many Requests", "the map-full body mirrors the limiter's own 429 shape");
|
||||
assert.strictEqual(fresh.headers["Retry-After"], "120", "Retry-After is one full window (no tracked record to derive a horizon from)");
|
||||
assert.ok(!fresh.nextCalled);
|
||||
// An ALREADY-TRACKED key keeps being served, as before.
|
||||
const tracked = h.request("192.0.2.1");
|
||||
assert.ok(tracked.nextCalled, "tracked keys keep being served at map-full");
|
||||
assert.strictEqual(tracked.status, null, "tracked keys get no refusal status");
|
||||
});
|
||||
|
||||
test("app-wide limiter: disabled by default the middleware stays out of the way entirely", () => {
|
||||
const h = buildRateLimiterHarness({ security: {}, maxTrackedIps: 0 });
|
||||
const out = h.request("192.0.2.1");
|
||||
assert.ok(out.nextCalled, "disabled limiter passes everything");
|
||||
assert.strictEqual(h.rateRequests.size, 0, "disabled limiter writes no counters");
|
||||
assert.strictEqual(out.status, null, "disabled limiter never refuses");
|
||||
});
|
||||
Reference in new issue
Block a user