187 lines
7.4 KiB
TypeScript
187 lines
7.4 KiB
TypeScript
import { afterEach, beforeEach, describe, expect, it } from "vitest";
|
|
import { createSharedStore } from "@hivegrid/shared-store";
|
|
|
|
import {
|
|
checkMfaChallengeRateLimit,
|
|
mfaChallengeRateLimitKey,
|
|
recordFailedMfaChallengeAttempt,
|
|
resetMfaChallengeRateLimit,
|
|
resetMfaChallengeRateLimiterForTests,
|
|
__resetMfaChallengeRateLimitStoreForTests,
|
|
__setMfaChallengeRateLimitStoreForTests,
|
|
} from "./challenge-rate-limit.server";
|
|
|
|
beforeEach(() => {
|
|
__setMfaChallengeRateLimitStoreForTests(createSharedStore({ namespace: "test-mfa-challenge" }));
|
|
});
|
|
|
|
afterEach(async () => {
|
|
await resetMfaChallengeRateLimiterForTests();
|
|
__resetMfaChallengeRateLimitStoreForTests();
|
|
});
|
|
|
|
const toKey = (userId: string, ip: string) => ({ userId, perIp: `${userId}:${ip}` });
|
|
|
|
describe("MFA challenge rate limiter", () => {
|
|
it("keys attempts by a Cloudflare client IP only behind a verified Cloudflare peer", () => {
|
|
const request = new Request("https://admin.example.test/mfa-challenge", {
|
|
headers: {
|
|
"x-forwarded-for": "1.2.3.4, 173.245.48.10",
|
|
"cf-connecting-ip": "203.0.113.5",
|
|
},
|
|
});
|
|
|
|
expect(mfaChallengeRateLimitKey(request, "user_1")).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.5" });
|
|
});
|
|
|
|
it("falls back to the Traefik-appended XFF or X-Real-IP peer and then unknown", () => {
|
|
expect(
|
|
mfaChallengeRateLimitKey(
|
|
new Request("https://admin.example.test/mfa-challenge", {
|
|
headers: { "x-real-ip": "198.51.100.7" },
|
|
}),
|
|
"user_1",
|
|
),
|
|
).toEqual({ userId: "user_1", perIp: "user_1:198.51.100.7" });
|
|
expect(
|
|
mfaChallengeRateLimitKey(
|
|
new Request("https://admin.example.test/mfa-challenge", { headers: { "x-forwarded-for": "203.0.113.9" } }),
|
|
"user_1",
|
|
),
|
|
).toEqual({ userId: "user_1", perIp: "user_1:203.0.113.9" });
|
|
expect(mfaChallengeRateLimitKey(new Request("https://admin.example.test/mfa-challenge"), "user_1")).toEqual({
|
|
userId: "user_1",
|
|
perIp: "user_1:unknown",
|
|
});
|
|
});
|
|
|
|
it("blocks after repeated failed attempts and can be reset", async () => {
|
|
const key = toKey("user_1", "203.0.113.5");
|
|
const now = new Date("2026-05-11T12:00:00.000Z");
|
|
|
|
for (let index = 0; index < 5; index += 1) {
|
|
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
|
await recordFailedMfaChallengeAttempt(key, now);
|
|
}
|
|
|
|
const blocked = await checkMfaChallengeRateLimit(key, now);
|
|
expect(blocked.allowed).toBe(false);
|
|
if (!blocked.allowed) {
|
|
expect(blocked.retryAfterSeconds).toBe(300);
|
|
}
|
|
|
|
await resetMfaChallengeRateLimit(key);
|
|
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
|
});
|
|
|
|
it("enforces the per-user cap even when the attacker rotates the client IP", async () => {
|
|
const now = new Date("2026-05-11T12:00:00.000Z");
|
|
// Attacker changes the trusted IP every attempt, so no per-IP bucket ever
|
|
// fills — but the per-user bucket (keyed on userId alone) still bounds them.
|
|
for (let index = 0; index < 15; index += 1) {
|
|
const key = toKey("victim", `203.0.113.${index}`);
|
|
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
|
await recordFailedMfaChallengeAttempt(key, now);
|
|
}
|
|
|
|
const blocked = await checkMfaChallengeRateLimit(toKey("victim", "203.0.113.99"), now);
|
|
expect(blocked.allowed).toBe(false);
|
|
if (!blocked.allowed) {
|
|
expect(blocked.retryAfterSeconds).toBe(900);
|
|
}
|
|
});
|
|
|
|
it("treats non-numeric stored counters as zero remaining attempts", async () => {
|
|
const store = createSharedStore({ namespace: "test-mfa-challenge-nan" });
|
|
__setMfaChallengeRateLimitStoreForTests(store);
|
|
const key = toKey("user_1", "203.0.113.5");
|
|
const now = new Date("2026-05-11T12:00:00.000Z");
|
|
await store.set(`rl:fixed:mfa-challenge:${key.perIp}`, "NaN", { ttlSeconds: 300 });
|
|
|
|
await expect(checkMfaChallengeRateLimit(key, now)).resolves.toEqual({
|
|
allowed: true,
|
|
remaining: 4,
|
|
resetAt: new Date("2026-05-11T12:05:00.000Z"),
|
|
});
|
|
});
|
|
|
|
it("resetMfaChallengeRateLimiterForTests clears cached fixed-window keys", async () => {
|
|
const key = toKey("user_1", "203.0.113.5");
|
|
const now = new Date("2026-05-11T12:00:00.000Z");
|
|
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
|
|
|
await resetMfaChallengeRateLimiterForTests();
|
|
|
|
const freshStore = createSharedStore({ namespace: "test-mfa-challenge" });
|
|
__setMfaChallengeRateLimitStoreForTests(freshStore);
|
|
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
|
});
|
|
|
|
it("atomically caps parallel TOTP verifiers", async () => {
|
|
const key = toKey("parallel-user", "198.51.100.88");
|
|
const results = await Promise.all(
|
|
Array.from({ length: 20 }, () => checkMfaChallengeRateLimit(key)),
|
|
);
|
|
|
|
expect(results.filter((result) => result.allowed)).toHaveLength(5);
|
|
expect(results.filter((result) => !result.allowed)).toHaveLength(15);
|
|
});
|
|
|
|
it("does not let a blocked source keep consuming the per-user budget", async () => {
|
|
const blockedKey = toKey("victim", "198.51.100.89");
|
|
for (let index = 0; index < 5; index += 1) {
|
|
expect((await checkMfaChallengeRateLimit(blockedKey)).allowed).toBe(true);
|
|
}
|
|
for (let index = 0; index < 20; index += 1) {
|
|
expect((await checkMfaChallengeRateLimit(blockedKey)).allowed).toBe(false);
|
|
}
|
|
|
|
expect((await checkMfaChallengeRateLimit(toKey("victim", "198.51.100.90"))).allowed).toBe(true);
|
|
});
|
|
|
|
it("swallows scan failures while clearing cached rate-limit keys (best-effort cleanup)", async () => {
|
|
const store = createSharedStore({ namespace: "test-mfa-scan-throw" });
|
|
// Force the cleanup scan to reject so the best-effort catch path runs.
|
|
(store.adapter as unknown as { scan: () => AsyncIterable<string> }).scan = async function* () {
|
|
throw new Error("scan boom");
|
|
};
|
|
__setMfaChallengeRateLimitStoreForTests(store);
|
|
// Populate the cached limiter so the reset has a previous store to scan.
|
|
await checkMfaChallengeRateLimit(toKey("user_scan", "203.0.113.9"));
|
|
|
|
await expect(resetMfaChallengeRateLimiterForTests()).resolves.toBeUndefined();
|
|
});
|
|
|
|
it("falls back to the process shared store after the test override is reset", async () => {
|
|
// Drops the injected store and reverts storeFactory to the default web store.
|
|
__resetMfaChallengeRateLimitStoreForTests();
|
|
|
|
const result = await checkMfaChallengeRateLimit(toKey("default-factory-user", "9.9.9.9"));
|
|
expect(result.allowed).toBe(true);
|
|
});
|
|
|
|
it("uses the redis adapter when REDIS_URL is set", () => {
|
|
const originalRedisUrl = process.env.REDIS_URL;
|
|
try {
|
|
process.env.REDIS_URL = "redis://does-not-exist:6379";
|
|
const store = createSharedStore({ namespace: "mfa-redis-selection", redisUrl: process.env.REDIS_URL });
|
|
expect(store.adapter.constructor.name).toBe("RedisAdapter");
|
|
void store.close();
|
|
} finally {
|
|
if (originalRedisUrl === undefined) delete process.env.REDIS_URL;
|
|
else process.env.REDIS_URL = originalRedisUrl;
|
|
}
|
|
});
|
|
|
|
it("uses the memory adapter when REDIS_URL is unset", () => {
|
|
const originalRedisUrl = process.env.REDIS_URL;
|
|
delete process.env.REDIS_URL;
|
|
try {
|
|
const store = createSharedStore({ namespace: "mfa-memory-selection" });
|
|
expect(store.adapter.constructor.name).toBe("MemoryAdapter");
|
|
} finally {
|
|
if (originalRedisUrl !== undefined) process.env.REDIS_URL = originalRedisUrl;
|
|
}
|
|
});
|
|
});
|