import { afterEach, describe, expect, test, vi } from 'vitest' import { checkRateLimit, clientIp, consumeRateLimit, setRateLimitStore, setUnknownIpFactor, UNKNOWN_IP_FACTOR, } from '../src/modules/shared/rateLimit.js' const req = (headers: Record) => new Request('http://x/', { headers }) describe('clientIp', () => { afterEach(() => { vi.unstubAllEnvs() }) test('prefers cf-connecting-ip, then x-real-ip', () => { expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-real-ip': '2.2.2.2' }))).toBe('1.1.1.1') expect(clientIp(req({ 'x-forwarded-for': '9.9.9.9', 'x-real-ip': '2.2.2.2' }))).toBe('2.2.2.2') }) test('takes X-Forwarded-For from the right, so a spoofed left entry is ignored', () => { const r = req({ 'x-forwarded-for': '6.6.6.6, 3.3.3.3' }) expect(clientIp(r)).toBe('3.3.3.3') expect(clientIp(r, { trustedProxies: 2 })).toBe('6.6.6.6') expect(clientIp(r, { trustedProxies: 5 })).toBe('6.6.6.6') }) test('a pinned header is the only one read', () => { const r = req({ 'cf-connecting-ip': '1.1.1.1', 'x-real-ip': '2.2.2.2' }) expect(clientIp(r, { header: 'x-real-ip' })).toBe('2.2.2.2') expect(clientIp(r, { header: 'x-client-ip' })).toBe('') }) test('IAPL_IP_HEADER env pins the header', () => { vi.stubEnv('IAPL_IP_HEADER', 'x-forwarded-for') expect(clientIp(req({ 'cf-connecting-ip': '1.1.1.1', 'x-forwarded-for': '6.6.6.6, 4.4.4.4' }))).toBe('4.4.4.4') }) test('accepts Headers (server actions)', () => { expect(clientIp(new Headers({ 'x-real-ip': '5.5.5.5' }))).toBe('5.5.5.5') }) test('empty when nothing usable is present', () => { expect(clientIp(req({}))).toBe('') }) }) describe('checkRateLimit (in memory)', () => { test('allows up to max per window, then blocks', () => { const key = `k-${Math.random()}` for (let i = 0; i < 3; i++) {expect(checkRateLimit({ key, max: 3 })).toBe(true)} expect(checkRateLimit({ key, max: 3 })).toBe(false) }) test('scopes are independent', () => { const key = `k-${Math.random()}` expect(checkRateLimit({ key, max: 1, scope: 'a' })).toBe(true) expect(checkRateLimit({ key, max: 1, scope: 'b' })).toBe(true) expect(checkRateLimit({ key, max: 1, scope: 'a' })).toBe(false) }) test('a cost above max is refused outright', () => { expect(checkRateLimit({ cost: 4, key: `k-${Math.random()}`, max: 3 })).toBe(false) }) test('setUnknownIpFactor(0) restores the old free pass; the default comes back', () => { setUnknownIpFactor(0) expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(true) setUnknownIpFactor(UNKNOWN_IP_FACTOR) expect(checkRateLimit({ key: '', max: 0, scope: `z-${Math.random()}` })).toBe(false) }) test('no key → one shared bucket with a roomier limit, not a free pass', () => { const scope = `s-${Math.random()}` for (let i = 0; i < 2 * UNKNOWN_IP_FACTOR; i++) {expect(checkRateLimit({ key: '', max: 2, scope })).toBe(true)} expect(checkRateLimit({ key: '', max: 2, scope })).toBe(false) }) }) describe('consumeRateLimit', () => { afterEach(() => setRateLimitStore(null)) test('in memory: blocks after max and reports Retry-After', async () => { const key = `k-${Math.random()}` expect((await consumeRateLimit({ key, max: 1, windowMs: 30_000 })).ok).toBe(true) const blocked = await consumeRateLimit({ key, max: 1, windowMs: 30_000 }) expect(blocked.ok).toBe(false) expect(blocked.retryAfter).toBeGreaterThan(25) }) test('uses the configured store', async () => { const hit = vi.fn(async () => ({ count: 7, resetAt: Date.now() + 10_000 })) setRateLimitStore({ hit }) const result = await consumeRateLimit({ cost: 2, key: 'ip', max: 5, scope: 'mcp', windowMs: 10_000 }) expect(hit).toHaveBeenCalledWith('mcp:ip', 2, 10_000) expect(result.ok).toBe(false) }) test('a failing store lets the request through', async () => { const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}) setRateLimitStore({ hit: () => Promise.reject(new Error('redis down')) }) expect((await consumeRateLimit({ key: 'ip', max: 0 })).ok).toBe(true) warn.mockRestore() }) }) describe('IAPL_IP_HEADER', () => { afterEach(() => { vi.unstubAllEnvs() vi.restoreAllMocks() }) test('iaplEnvRules({ ipHeader }) requires it in production only', async () => { const { assertEnv } = await import('../src/modules/env/assertEnv.js') const { iaplEnvRules } = await import('../src/modules/env/iaplEnvRules.js') const base = { DATABASE_URI: 'x', NEXT_PUBLIC_SERVER_URL: 'https://acme.pl', PAYLOAD_SECRET: 'a-long-random-test-secret-of-32-chars' } vi.stubEnv('NODE_ENV', 'production') expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: base })).toThrow(/IAPL_IP_HEADER/) expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: { ...base, IAPL_IP_HEADER: 'cf-connecting-ip' } })).not.toThrow() vi.stubEnv('NODE_ENV', 'development') expect(() => assertEnv(iaplEnvRules({ ipHeader: true }), { env: base })).not.toThrow() }) })