163 lines
7.0 KiB
JavaScript
163 lines
7.0 KiB
JavaScript
// Standalone verification harness for the account rate limiters added to
|
|
// index.js (accountCredentialRateLimiter / accountTotpRateLimiter).
|
|
// Replicates the exact limiter configs and drives them through a real
|
|
// express + express-session app to prove the security properties:
|
|
// 1. Bucket exhausts at max and returns the 429 JSON contract.
|
|
// 2. Different sessions (different victims) get independent buckets.
|
|
// 3. Rotating the source IP does NOT reset the bucket (the hijacked
|
|
// session is the key, not the network origin).
|
|
// 4. Unauthenticated requests are skipped (route handler 401s them).
|
|
// Run: node scripts/verify-account-rate-limiters.js
|
|
const assert = require("assert");
|
|
const crypto = require("crypto");
|
|
const express = require("express");
|
|
const session = require("express-session");
|
|
const http = require("http");
|
|
const { rateLimit } = require("express-rate-limit");
|
|
|
|
// ---- exact copies of the limiter configs from index.js ----
|
|
function accountCredentialRateLimiterFactory() {
|
|
return rateLimit({
|
|
windowMs: 10 * 60 * 1000,
|
|
max: 10,
|
|
standardHeaders: true,
|
|
legacyHeaders: false,
|
|
keyGenerator: (req) => {
|
|
const email = String(req.session?.user || "anon").trim().toLowerCase();
|
|
const sid = String(req.sessionID || "no-session");
|
|
return `account-cred-verify:${email}:${sid}`;
|
|
},
|
|
skip: (req) => !req.session?.user,
|
|
handler: (req, res) => {
|
|
res.status(429).json({ error: "Too many verification attempts. Please wait 10 minutes and try again.", code: "verification-rate-limit" });
|
|
}
|
|
});
|
|
}
|
|
function accountTotpRateLimiterFactory() {
|
|
return rateLimit({
|
|
windowMs: 10 * 60 * 1000,
|
|
max: 10,
|
|
standardHeaders: true,
|
|
legacyHeaders: false,
|
|
keyGenerator: (req) => {
|
|
const email = String(req.session?.user || "anon").trim().toLowerCase();
|
|
const sid = String(req.sessionID || "no-session");
|
|
return `account-totp:${email}:${sid}`;
|
|
},
|
|
skip: (req) => !req.session?.user,
|
|
handler: (req, res) => {
|
|
res.status(429).json({ error: "Too many 2FA verification attempts. Please wait 10 minutes and try again.", code: "verification-rate-limit" });
|
|
}
|
|
});
|
|
}
|
|
|
|
function buildApp() {
|
|
const app = express();
|
|
app.use(express.json());
|
|
app.use(session({ secret: crypto.randomBytes(32).toString("hex"), resave: false, saveUninitialized: true, cookie: { httpOnly: true } }));
|
|
// Login shim: seeds req.session.user the same way the panel's login does.
|
|
app.post("/test/login", (req, res) => {
|
|
req.session.user = req.body.email;
|
|
res.json({ ok: true });
|
|
});
|
|
app.post("/api/account/password/verify", accountCredentialRateLimiterFactory(), (req, res) => {
|
|
if (!req.session?.user) return res.status(401).json({ error: "Not authenticated" });
|
|
res.json({ ok: true });
|
|
});
|
|
app.post("/api/account/2fa/generate", accountTotpRateLimiterFactory(), (req, res) => {
|
|
if (!req.session?.user) return res.status(401).json({ error: "Not authenticated" });
|
|
res.json({ ok: true });
|
|
});
|
|
return app;
|
|
}
|
|
|
|
function startServer(app) {
|
|
return new Promise((resolve) => {
|
|
const server = app.listen(0, "127.0.0.1", () => resolve(server));
|
|
});
|
|
}
|
|
|
|
function request(server, path, { cookie, ip, body, method = "POST" } = {}) {
|
|
return new Promise((resolve, reject) => {
|
|
const { port } = server.address();
|
|
const data = body ? JSON.stringify(body) : null;
|
|
const req = http.request(
|
|
{ host: "127.0.0.1", port, path, method, headers: {
|
|
"content-type": "application/json",
|
|
...(cookie ? { cookie } : {}),
|
|
// x-forwarded-for must not influence the limiter key at all; each
|
|
// TOTP guess below uses a different value, like a rotating proxy.
|
|
...(ip ? { "x-forwarded-for": ip } : {}),
|
|
...(data ? { "content-length": Buffer.byteLength(data) } : {}),
|
|
} },
|
|
(res) => {
|
|
let buf = "";
|
|
res.on("data", (c) => (buf += c));
|
|
res.on("end", () => resolve({ status: res.statusCode, headers: res.headers, body: buf ? JSON.parse(buf) : null }));
|
|
}
|
|
);
|
|
req.on("error", reject);
|
|
if (data) req.write(data);
|
|
req.end();
|
|
});
|
|
}
|
|
|
|
async function main() {
|
|
const app = buildApp();
|
|
const server = await startServer(app);
|
|
const results = [];
|
|
|
|
// ---- Test 1: bucket exhausts at 10, 11th request is 429 with the contract body
|
|
{
|
|
let res = await request(server, "/test/login", { body: { email: "victim@example.com" } });
|
|
const cookie = res.headers["set-cookie"][0].split(";")[0];
|
|
|
|
const statuses = [];
|
|
for (let i = 0; i < 11; i++) {
|
|
res = await request(server, "/api/account/password/verify", { cookie, body: { currentPassword: "x" } });
|
|
statuses.push(res.status);
|
|
}
|
|
assert.deepStrictEqual(statuses.slice(0, 10), Array(10).fill(200), "first 10 attempts pass");
|
|
assert.strictEqual(statuses[10], 429, "11th attempt is rate limited");
|
|
assert.strictEqual(res.body.code, "verification-rate-limit");
|
|
assert.match(res.body.error, /Too many verification attempts/);
|
|
assert.ok(res.headers["ratelimit-limit"], "standard RateLimit headers present");
|
|
results.push("PASS bucket exhausts at 10 → 429 with contract body + standard headers");
|
|
}
|
|
|
|
// ---- Test 2: another session (different victim account) still gets 200
|
|
{
|
|
const res = await request(server, "/test/login", { body: { email: "other@example.com" } });
|
|
const cookie = res.headers["set-cookie"][0].split(";")[0];
|
|
const r = await request(server, "/api/account/password/verify", { cookie, body: { currentPassword: "x" } });
|
|
assert.strictEqual(r.status, 200, "independent session unaffected by exhausted bucket");
|
|
results.push("PASS separate session → separate bucket (no cross-victim lockout)");
|
|
}
|
|
|
|
// ---- Test 3: same hijacked session, attacker rotates source IPs → still 429
|
|
{
|
|
let res = await request(server, "/test/login", { body: { email: "totpvictim@example.com" } });
|
|
const cookie = res.headers["set-cookie"][0].split(";")[0];
|
|
for (let i = 0; i < 10; i++) {
|
|
res = await request(server, "/api/account/2fa/generate", { cookie, ip: `10.0.${Math.floor(i / 256)}.${i % 256}`, body: { currentCode: `00000${i % 10}` } });
|
|
assert.strictEqual(res.status, 200, `guess ${i + 1} from a fresh IP passes until the budget is gone`);
|
|
}
|
|
res = await request(server, "/api/account/2fa/generate", { cookie, ip: "10.9.9.9", body: { currentCode: "123456" } });
|
|
assert.strictEqual(res.status, 429, "IP rotation does not reset the bucket");
|
|
results.push("PASS TOTP grind capped at 10 guesses even with per-guess IP rotation");
|
|
}
|
|
|
|
// ---- Test 4: unauthenticated request skips the limiter (handler 401s)
|
|
{
|
|
const r = await request(server, "/api/account/password/verify", { body: { currentPassword: "x" } });
|
|
assert.strictEqual(r.status, 401, "no session → 401 from handler, not counted by limiter");
|
|
results.push("PASS unauthenticated requests skipped by the limiter");
|
|
}
|
|
|
|
server.close();
|
|
console.log(results.join("\n"));
|
|
console.log("\nALL LIMITER BEHAVIOR TESTS PASSED");
|
|
}
|
|
|
|
main().catch((err) => { console.error(err); process.exit(1); });
|