170 lines
6.8 KiB
TypeScript
170 lines
6.8 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 user and a TRUSTED client IP, ignoring spoofable X-Forwarded-For", () => {
|
|
const request = new Request("https://admin.example.test/mfa-challenge", {
|
|
headers: {
|
|
// Attacker-forged forwarded header must be ignored...
|
|
"x-forwarded-for": "1.2.3.4, 10.0.0.1",
|
|
// ...in favour of the Cloudflare-set trusted header.
|
|
"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 x-real-ip and then unknown, never to x-forwarded-for", () => {
|
|
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" });
|
|
// Only a spoofable X-Forwarded-For present -> not trusted -> unknown.
|
|
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:unknown" });
|
|
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: 5,
|
|
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");
|
|
await recordFailedMfaChallengeAttempt(key, now);
|
|
expect((await checkMfaChallengeRateLimit(key, now)).allowed).toBe(true);
|
|
|
|
await resetMfaChallengeRateLimiterForTests();
|
|
|
|
const freshStore = createSharedStore({ namespace: "test-mfa-challenge" });
|
|
__setMfaChallengeRateLimitStoreForTests(freshStore);
|
|
await recordFailedMfaChallengeAttempt(key, now);
|
|
expect((await checkMfaChallengeRateLimit(key, now)).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;
|
|
}
|
|
});
|
|
});
|