38 lines
1.3 KiB
TypeScript
38 lines
1.3 KiB
TypeScript
import { describe, it, expect } from 'vitest';
|
|||
|
|
import { checkRateLimits, recordUsage } from '../src/lib/api/rateLimiter';
|
||
|
|
|
||
|
|
describe('Rate Limiter & Budget Circuit Breaker (PRD §7.11 API-08)', () => {
|
||
|
|
it('enforces visitor daily limit', () => {
|
||
|
|
const visitorId = 'test_visitor_' + Math.random();
|
||
|
|
const ip = '127.0.0.1';
|
||
|
|
const limits = { perVisitorPerDay: 2, perIpPerHour: 10, dailyBudgetCalls: 100 };
|
||
|
|
|
||
|
|
// Try 1
|
||
|
|
const check1 = checkRateLimits(visitorId, ip, limits);
|
||
|
|
expect(check1.allowed).toBe(true);
|
||
|
|
recordUsage(visitorId, ip);
|
||
|
|
|
||
|
|
// Try 2
|
||
|
|
const check2 = checkRateLimits(visitorId, ip, limits);
|
||
|
|
expect(check2.allowed).toBe(true);
|
||
|
|
recordUsage(visitorId, ip);
|
||
|
|
|
||
|
|
// Try 3 -> Should be blocked
|
||
|
|
const check3 = checkRateLimits(visitorId, ip, limits);
|
||
|
|
expect(check3.allowed).toBe(false);
|
||
|
|
expect(check3.reason).toBe('visitor_daily');
|
||
|
|
});
|
||
|
|
|
||
|
|
it('trips daily budget breaker when budget exhausted', () => {
|
||
|
|
const visitorId = 'budget_test_visitor';
|
||
|
|
const ip = '127.0.0.2';
|
||
|
|
const limits = { perVisitorPerDay: 100, perIpPerHour: 100, dailyBudgetCalls: 1 };
|
||
|
|
|
||
|
|
recordUsage(visitorId, ip);
|
||
|
|
|
||
|
|
const check = checkRateLimits('new_visitor', ip, limits);
|
||
|
|
expect(check.allowed).toBe(false);
|
||
|
|
expect(check.reason).toBe('budget_exhausted');
|
||
|
|
});
|
||
|
|
});
|