267 lines
12 KiB
TypeScript
267 lines
12 KiB
TypeScript
import { MemoryAdapter, createSharedStore } from "@hivegrid/shared-store";
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
|
|
|
vi.mock("@hivegrid/config", async () => {
|
|
const actual = await vi.importActual<typeof import("@hivegrid/config")>("@hivegrid/config");
|
|
return {
|
|
...actual,
|
|
loadRequiredWebConfig: () => ({ cryptoSecret: "test-auth-rate-limit-secret", sessionSecret: "test-session-secret" }),
|
|
};
|
|
});
|
|
|
|
import { __resetAuthRateLimitStoreForTests, __setAuthRateLimitStoreForTests, checkAuthRateLimit, getAuthRateLimitKey } from "./auth-rate-limit.server";
|
|
|
|
function cloudflareHeaders(clientIp: string) {
|
|
return { "cf-connecting-ip": clientIp, "x-forwarded-for": `${clientIp}, 173.245.48.10` };
|
|
}
|
|
|
|
describe("auth rate limiting", () => {
|
|
let adapter: MemoryAdapter;
|
|
|
|
beforeEach(() => {
|
|
vi.spyOn(Date, "now").mockReturnValue(new Date("2026-05-25T12:00:00.000Z").getTime());
|
|
adapter = new MemoryAdapter();
|
|
__setAuthRateLimitStoreForTests(createSharedStore({ namespace: "auth-rate-test", adapter }));
|
|
});
|
|
|
|
afterEach(() => {
|
|
__resetAuthRateLimitStoreForTests();
|
|
vi.restoreAllMocks();
|
|
});
|
|
|
|
it("builds stable pseudonymous keys from action, trusted client ip, and normalized identifier", () => {
|
|
const request = new Request("https://example.test/login", {
|
|
headers: cloudflareHeaders("203.0.113.10"),
|
|
});
|
|
|
|
const normalized = getAuthRateLimitKey({ request, action: "login", identifier: "ada@example.com" });
|
|
expect(getAuthRateLimitKey({ request, action: "login", identifier: " Ada@Example.COM " })).toBe(normalized);
|
|
expect(getAuthRateLimitKey({ request, action: "forgot-password", identifier: "ada@example.com" })).not.toBe(normalized);
|
|
expect(normalized).toMatch(/^[a-f0-9]{64}$/);
|
|
expect(normalized).not.toContain("ada@example.com");
|
|
expect(normalized).not.toContain("203.0.113.10");
|
|
});
|
|
|
|
it("keeps registration verification capabilities and client IPs out of rate-limit keys", () => {
|
|
const verificationToken = "raw-registration-verification-capability";
|
|
const clientIp = "203.0.113.27";
|
|
const request = new Request("https://example.test/verify/token", {
|
|
headers: cloudflareHeaders(clientIp),
|
|
});
|
|
|
|
const key = getAuthRateLimitKey({ request, action: "registration-verify", identifier: verificationToken });
|
|
|
|
expect(key).toMatch(/^[a-f0-9]{64}$/u);
|
|
expect(key).not.toContain(verificationToken);
|
|
expect(key).not.toContain(clientIp);
|
|
});
|
|
|
|
it("keeps invitation capabilities out of view and acceptance bucket keys", async () => {
|
|
const invitationToken = "raw-workspace-invitation-capability";
|
|
const request = new Request(`https://example.test/invitation/${invitationToken}`, {
|
|
headers: cloudflareHeaders("203.0.113.41"),
|
|
});
|
|
|
|
for (const action of ["invitation-view", "invitation-accept"] as const) {
|
|
const key = getAuthRateLimitKey({ request, action, identifier: invitationToken });
|
|
expect(key).toMatch(/^[a-f0-9]{64}$/u);
|
|
expect(key).not.toContain(invitationToken);
|
|
await expect(checkAuthRateLimit({ request, action, identifier: invitationToken, limit: 2, windowMs: 30_000 })).resolves.toEqual({ allowed: true });
|
|
}
|
|
|
|
const storedKeys = [];
|
|
for await (const key of adapter.scan("*")) storedKeys.push(key);
|
|
expect(JSON.stringify(storedKeys)).not.toContain(invitationToken);
|
|
});
|
|
|
|
it("does not key on a spoofed leftmost X-Forwarded-For or X-Client-IP", () => {
|
|
const first = new Request("https://example.test/login", {
|
|
headers: { "x-forwarded-for": "9.9.9.9, 198.51.100.7", "x-client-ip": "8.8.8.8" },
|
|
});
|
|
const rotated = new Request("https://example.test/login", {
|
|
headers: { "x-forwarded-for": "4.4.4.4, 198.51.100.7", "x-client-ip": "1.1.1.1" },
|
|
});
|
|
expect(getAuthRateLimitKey({ request: first, action: "login", identifier: "ada@example.com" })).toBe(
|
|
getAuthRateLimitKey({ request: rotated, action: "login", identifier: "ada@example.com" }),
|
|
);
|
|
});
|
|
|
|
it("allows requests up to the atomic limit and returns retry timing after the limit", async () => {
|
|
const request = new Request("https://example.test/login", {
|
|
headers: cloudflareHeaders("203.0.113.10"),
|
|
});
|
|
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 2, windowMs: 30_000 };
|
|
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
|
|
});
|
|
|
|
it("shares reservations between replicas using the same backing adapter", async () => {
|
|
const request = new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") });
|
|
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 1, windowMs: 30_000 };
|
|
const replicaA = createSharedStore({ namespace: "auth-rate-replicas", adapter });
|
|
const replicaB = createSharedStore({ namespace: "auth-rate-replicas", adapter });
|
|
|
|
__setAuthRateLimitStoreForTests(replicaA);
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
|
|
__setAuthRateLimitStoreForTests(replicaB);
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
|
|
});
|
|
|
|
it("permits exactly the configured number during a parallel burst", async () => {
|
|
const request = new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") });
|
|
const options = { request, action: "login" as const, identifier: "ada@example.com", limit: 5, windowMs: 30_000 };
|
|
|
|
const decisions = await Promise.all(Array.from({ length: 20 }, () => checkAuthRateLimit(options)));
|
|
expect(decisions.filter((decision) => decision.allowed)).toHaveLength(5);
|
|
expect(decisions.filter((decision) => !decision.allowed)).toHaveLength(15);
|
|
});
|
|
|
|
it("bounds one identifier across rotating trusted client addresses", async () => {
|
|
const decisions = [];
|
|
for (let index = 1; index <= 4; index += 1) {
|
|
decisions.push(
|
|
await checkAuthRateLimit({
|
|
request: new Request("https://example.test/login", { headers: cloudflareHeaders(`203.0.113.${index}`) }),
|
|
action: "login",
|
|
identifier: "ada@example.com",
|
|
limit: 1,
|
|
windowMs: 30_000,
|
|
})
|
|
);
|
|
}
|
|
|
|
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, true, false]);
|
|
});
|
|
|
|
it("honors an explicit global identifier cap across rotating trusted client addresses", async () => {
|
|
const decisions = [];
|
|
for (let index = 1; index <= 3; index += 1) {
|
|
decisions.push(
|
|
await checkAuthRateLimit({
|
|
request: new Request("https://example.test/register", { headers: cloudflareHeaders(`203.0.113.${index}`) }),
|
|
action: "register",
|
|
identifier: " Ada@Example.COM ",
|
|
limit: 5,
|
|
identifierLimit: 2,
|
|
windowMs: 60 * 60 * 1000,
|
|
})
|
|
);
|
|
}
|
|
|
|
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, false]);
|
|
const storedKeys = [];
|
|
for await (const key of adapter.scan("*")) storedKeys.push(key);
|
|
expect(JSON.stringify(storedKeys)).not.toContain("ada@example.com");
|
|
});
|
|
|
|
it("can disable the global identifier bucket while retaining client and pair limits", async () => {
|
|
const requestFor = (lastOctet: number) =>
|
|
new Request("https://example.test/register", {
|
|
headers: cloudflareHeaders(`203.0.113.${lastOctet}`),
|
|
});
|
|
const baseOptions = {
|
|
action: "register" as const,
|
|
identifier: "victim@example.test",
|
|
limit: 1,
|
|
identifierLimit: null,
|
|
windowMs: 60 * 60 * 1000,
|
|
};
|
|
|
|
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(1) })).resolves.toEqual({ allowed: true });
|
|
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(2) })).resolves.toEqual({ allowed: true });
|
|
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(3) })).resolves.toEqual({ allowed: true });
|
|
await expect(checkAuthRateLimit({ ...baseOptions, request: requestFor(1) })).resolves.toEqual({
|
|
allowed: false,
|
|
retryAfterSeconds: 60 * 60,
|
|
});
|
|
|
|
const storedKeys = [];
|
|
for await (const key of adapter.scan("*")) storedKeys.push(key);
|
|
expect(storedKeys.some((key) => key.includes(":identifier:"))).toBe(false);
|
|
});
|
|
|
|
it("caps identifier churn per trusted client to bound live Redis keys", async () => {
|
|
const decisions = [];
|
|
for (let index = 1; index <= 11; index += 1) {
|
|
decisions.push(
|
|
await checkAuthRateLimit({
|
|
request: new Request("https://example.test/login", { headers: cloudflareHeaders("203.0.113.10") }),
|
|
action: "login",
|
|
identifier: `generated-${index}@example.com`,
|
|
limit: 1,
|
|
windowMs: 30_000,
|
|
})
|
|
);
|
|
}
|
|
|
|
expect(decisions.map((decision) => decision.allowed)).toEqual([true, true, true, true, true, true, true, true, true, true, false]);
|
|
});
|
|
|
|
it("starts a new window after the shared counter expires", async () => {
|
|
const request = new Request("https://example.test/mfa", {
|
|
headers: cloudflareHeaders("203.0.113.10"),
|
|
});
|
|
const options = { request, action: "mfa" as const, identifier: "ada@example.com", limit: 1, windowMs: 10_000 };
|
|
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: false, retryAfterSeconds: 10 });
|
|
|
|
vi.mocked(Date.now).mockReturnValue(new Date("2026-05-25T12:00:11.000Z").getTime());
|
|
|
|
await expect(checkAuthRateLimit(options)).resolves.toEqual({ allowed: true });
|
|
});
|
|
|
|
it("fails closed with a bounded retry interval when the shared store fails", async () => {
|
|
vi.spyOn(adapter, "eval").mockRejectedValueOnce(new Error("redis unavailable"));
|
|
const request = new Request("https://example.test/login");
|
|
|
|
await expect(checkAuthRateLimit({ request, action: "login", identifier: "ada@example.com", limit: 2, windowMs: 30_000 })).resolves.toEqual({
|
|
allowed: false,
|
|
retryAfterSeconds: 30,
|
|
});
|
|
});
|
|
|
|
it("fails closed before an invitation lookup when the shared throttle store is unavailable", async () => {
|
|
vi.spyOn(adapter, "eval").mockRejectedValueOnce(new Error("redis unavailable"));
|
|
const invitationToken = "raw-workspace-invitation-capability";
|
|
const request = new Request(`https://example.test/invitation/${invitationToken}`);
|
|
|
|
await expect(
|
|
checkAuthRateLimit({
|
|
request,
|
|
action: "invitation-view",
|
|
identifier: invitationToken,
|
|
limit: 30,
|
|
windowMs: 15 * 60 * 1000,
|
|
})
|
|
).resolves.toEqual({ allowed: false, retryAfterSeconds: 15 * 60 });
|
|
});
|
|
|
|
it("fails closed for invalid limits and windows with bounded retry values", async () => {
|
|
const request = new Request("https://example.test/login");
|
|
|
|
await expect(checkAuthRateLimit({ request, action: "login", limit: 0, windowMs: 30_000 })).resolves.toEqual({
|
|
allowed: false,
|
|
retryAfterSeconds: 30,
|
|
});
|
|
await expect(checkAuthRateLimit({ request, action: "login", limit: 1, windowMs: Number.NaN })).resolves.toEqual({
|
|
allowed: false,
|
|
retryAfterSeconds: 1,
|
|
});
|
|
await expect(checkAuthRateLimit({ request, action: "login", limit: 10_001, windowMs: 24 * 60 * 60 * 1000 + 1 })).resolves.toEqual({
|
|
allowed: false,
|
|
retryAfterSeconds: 86_400,
|
|
});
|
|
});
|
|
|
|
it("uses the configured window when the store returns an invalid TTL", async () => {
|
|
vi.spyOn(adapter, "eval").mockResolvedValueOnce([0, 0, 3]);
|
|
|
|
await expect(
|
|
checkAuthRateLimit({ request: new Request("https://example.test/login"), action: "login", identifier: null, limit: 2, windowMs: 30_000 })
|
|
).resolves.toEqual({ allowed: false, retryAfterSeconds: 30 });
|
|
});
|
|
});
|