import { afterEach, beforeEach, describe, expect, it } from 'vitest'; import app, { RATE_LIMIT_MAX, resetRateLimitState, seedRateLimitState } from '../src/app'; import { CONFIG } from '../src/config'; // Trust proxy should gate whether forwarded IP headers affect rate limiting. describe('SUBSTRATE_TRUST_PROXY gating', () => { const originalTrust = CONFIG.TRUST_PROXY; beforeEach(() => { CONFIG.TRUST_PROXY = true; resetRateLimitState(); }); afterEach(() => { CONFIG.TRUST_PROXY = originalTrust; resetRateLimitState(); }); async function hit(ip?: string) { const headers: Record = { 'x-substrate-key': CONFIG.API_KEY }; if (ip) headers['x-forwarded-for'] = ip; return app.fetch(new Request('http://substrate.local/services', { headers })); } it('accepts the request regardless of trust flag (sanity)', async () => { const r = await hit(); expect([200, 500]).toContain(r.status); // services may or may not be initialised }); it('honours the flag toggle without crashing', async () => { CONFIG.TRUST_PROXY = false; const r = await hit('1.2.3.4'); expect([200, 500]).toContain(r.status); }); it('rate limits repeated unauthorized requests before auth succeeds', async () => { seedRateLimitState('1.2.3.4', RATE_LIMIT_MAX, Date.now() + 60_000); const response = await app.fetch(new Request('http://substrate.local/services', { headers: { 'x-forwarded-for': '1.2.3.4', }, })); expect(response.status).toBe(429); await expect(response.json()).resolves.toMatchObject({ error: 'Too many requests', }); }); });