import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { clientIp, limitRequest, rateLimit, rateLimitStats } from "@/lib/rate-limit"; beforeEach(() => vi.useFakeTimers()); afterEach(() => vi.useRealTimers()); describe("rateLimit", () => { it("släpper igenom upp till gränsen och stoppar sedan", () => { const key = "test-limit"; expect(rateLimit(key, 3, 1000).ok).toBe(true); expect(rateLimit(key, 3, 1000).ok).toBe(true); expect(rateLimit(key, 3, 1000).ok).toBe(true); const blocked = rateLimit(key, 3, 1000); expect(blocked.ok).toBe(false); expect(blocked.retryAfter).toBeGreaterThanOrEqual(1); }); it("släpper igenom igen när tidsfönstret gått ut", () => { const key = "test-window"; for (let i = 0; i < 2; i++) rateLimit(key, 2, 1000); expect(rateLimit(key, 2, 1000).ok).toBe(false); vi.advanceTimersByTime(1001); expect(rateLimit(key, 2, 1000).ok).toBe(true); }); it("räknar varje nyckel för sig", () => { rateLimit("a", 1, 1000); expect(rateLimit("a", 1, 1000).ok).toBe(false); expect(rateLimit("b", 1, 1000).ok).toBe(true); }); it("räknar stoppade anrop", () => { const before = rateLimitStats.blocked; rateLimit("count", 1, 1000); rateLimit("count", 1, 1000); rateLimit("count", 1, 1000); expect(rateLimitStats.blocked).toBe(before + 2); }); }); describe("clientIp och limitRequest", () => { const request = (headers: Record) => new Request("http://localhost/x", { headers }); it("läser första adressen i x-forwarded-for", () => { expect(clientIp(request({ "x-forwarded-for": "1.2.3.4, 10.0.0.1" }))).toBe("1.2.3.4"); expect(clientIp(request({ "x-real-ip": "5.6.7.8" }))).toBe("5.6.7.8"); expect(clientIp(request({}))).toBe("unknown"); }); it("svarar 429 med Retry-After när gränsen är nådd", () => { const req = request({ "x-forwarded-for": "9.9.9.9" }); expect(limitRequest(req, "route", 1, 60_000)).toBeNull(); const response = limitRequest(req, "route", 1, 60_000); expect(response?.status).toBe(429); expect(Number(response?.headers.get("Retry-After"))).toBeGreaterThanOrEqual(1); }); it("begränsar per IP-adress", () => { expect(limitRequest(request({ "x-forwarded-for": "1.1.1.1" }), "ip-route", 1, 60_000)).toBeNull(); expect(limitRequest(request({ "x-forwarded-for": "2.2.2.2" }), "ip-route", 1, 60_000)).toBeNull(); expect(limitRequest(request({ "x-forwarded-for": "1.1.1.1" }), "ip-route", 1, 60_000)).not.toBeNull(); }); });