Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
90 changes: 90 additions & 0 deletions src/app/api/errors/report/__tests__/route.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { NextRequest } from 'next/server';
import { POST } from '../route';
import { RATE_LIMIT_TIERS } from '@/lib/ratelimit';

// Silence the logger so error reports don't pollute test output.
vi.mock('@/lib/logging', () => ({
createLogger: () => ({
error: vi.fn(),
warn: vi.fn(),
info: vi.fn(),
debug: vi.fn(),
}),
}));

const LIMIT = RATE_LIMIT_TIERS.REPORTING.limit;

let ipCounter = 0;
/** Fresh IP per call keeps each test isolated from the shared in-memory store. */
function makeRequest(body: unknown, ip = `203.0.113.${ipCounter++}`): NextRequest {
return new NextRequest('https://example.com/api/errors/report', {
method: 'POST',
headers: {
'content-type': 'application/json',
'x-forwarded-for': ip,
},
body: JSON.stringify(body),
});
}

const sampleReport = {
id: 'rep_1',
sessionId: 'sess_1',
userId: 'user_1',
url: 'https://example.com/page',
environment: 'production',
errorData: { message: 'Something broke', type: 'TypeError' },
};

describe('POST /api/errors/report rate limiting', () => {
beforeEach(() => {
ipCounter = 0;
});

it('accepts legitimate error reports within the limit', async () => {
const res = await POST(makeRequest(sampleReport));
expect(res.status).toBe(200);
await expect(res.json()).resolves.toEqual({ ok: true });
});

it('returns 429 once the per-IP limit is exceeded', async () => {
const ip = '198.51.100.1';

// Exhaust the allowed quota for this IP.
for (let i = 0; i < LIMIT; i++) {
const ok = await POST(makeRequest(sampleReport, ip));
expect(ok.status).toBe(200);
}

// The next request from the same IP is rate limited.
const blocked = await POST(makeRequest(sampleReport, ip));
expect(blocked.status).toBe(429);
});

it('includes a Retry-After header on the 429 response', async () => {
const ip = '198.51.100.2';

for (let i = 0; i < LIMIT; i++) {
await POST(makeRequest(sampleReport, ip));
}
const blocked = await POST(makeRequest(sampleReport, ip));

expect(blocked.status).toBe(429);
const retryAfter = blocked.headers.get('Retry-After');
expect(retryAfter).not.toBeNull();
expect(Number(retryAfter)).toBeGreaterThan(0);
});

it('does not let one IP exhaust another IP quota', async () => {
const noisy = '198.51.100.3';
for (let i = 0; i < LIMIT; i++) {
await POST(makeRequest(sampleReport, noisy));
}
expect((await POST(makeRequest(sampleReport, noisy))).status).toBe(429);

// A different IP is unaffected.
const other = await POST(makeRequest(sampleReport, '198.51.100.4'));
expect(other.status).toBe(200);
});
});
10 changes: 8 additions & 2 deletions src/app/api/errors/report/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server';
import { createLogger } from '@/lib/logging';
import { withRateLimit } from '@/lib/ratelimit';

const logger = createLogger('errors.report');

Expand All @@ -11,6 +12,11 @@ class ClientError extends Error {
}

export async function POST(request: NextRequest): Promise<NextResponse> {
// Rate limit per IP — this endpoint is called by client-side JS and is
// otherwise open to log-flooding DoS. Use the lower REPORTING tier (10/min).
const { addHeaders, rateLimitResponse } = withRateLimit(request, 'REPORTING');
if (rateLimitResponse) return rateLimitResponse;

try {
const report = await request.json();

Expand All @@ -30,9 +36,9 @@ export async function POST(request: NextRequest): Promise<NextResponse> {
error: clientError,
});

return NextResponse.json({ ok: true }, { status: 200 });
return addHeaders(NextResponse.json({ ok: true }, { status: 200 }));
} catch (err) {
logger.warn('Failed to process error report', { error: err });
return NextResponse.json({ ok: false }, { status: 400 });
return addHeaders(NextResponse.json({ ok: false }, { status: 400 }));
}
}
3 changes: 3 additions & 0 deletions src/lib/ratelimit.ts
Original file line number Diff line number Diff line change
Expand Up @@ -90,6 +90,9 @@ export const RATE_LIMIT_TIERS = {
AUTH: { limit: 5, windowMs: 60_000 },
WRITE: { limit: 30, windowMs: 60_000 },
READ: { limit: 60, windowMs: 60_000 },
// Lower tier for unauthenticated, client-driven endpoints (e.g. error
// reporting) that are prone to log-flooding abuse.
REPORTING: { limit: 10, windowMs: 60_000 },
} as const;

export type RateLimitTier = keyof typeof RATE_LIMIT_TIERS;
Expand Down
Loading