Rate limit dynamic client registration per source address
Replace the process-wide registration counter used without Redis with a shared per-key fixed-window limiter, so one requester can no longer exhaust the registration budget for every other client on the process. The in-memory fallback is bounded (expired windows are swept, then the oldest keys are shed) so memory stays constant under key churn. Also fixes checkMcpRateLimit inverting redis.rateLimit's result: it resolves true once the counter reaches its threshold, so with Redis the MCP endpoint was denying requests below the limit and allowing those above it. Both call sites now share the same limiter and semantics.
This commit is contained in:
1 parent
67449d76ef
commit
d2b4aa174e
5 files changed
+229
-60
No files matched your search
@@ -0,0 +1,70 @@
|
||||
import { beforeEach, expect, test, vi } from 'vitest';
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
parseRequest: vi.fn(),
|
||||
createOauthClient: vi.fn(),
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/request', () => ({
|
||||
parseRequest: mocks.parseRequest,
|
||||
}));
|
||||
|
||||
vi.mock('@/queries/prisma/oauth', () => ({
|
||||
createOauthClient: mocks.createOauthClient,
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/crypto', () => ({
|
||||
uuid: () => 'client-id',
|
||||
}));
|
||||
|
||||
vi.mock('@/lib/redis', () => ({
|
||||
default: { enabled: false, client: {} },
|
||||
}));
|
||||
|
||||
import { resetRateLimits } from '@/lib/rate-limit';
|
||||
import { POST } from './route';
|
||||
|
||||
const body = {
|
||||
client_name: 'Test client',
|
||||
redirect_uris: ['http://127.0.0.1:3000/callback'],
|
||||
};
|
||||
|
||||
function register(ip: string) {
|
||||
return POST(
|
||||
new Request('https://umami.example/api/oauth/register', {
|
||||
method: 'POST',
|
||||
headers: { 'x-forwarded-for': ip, 'content-type': 'application/json' },
|
||||
body: JSON.stringify(body),
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
resetRateLimits();
|
||||
delete process.env.OAUTH_DISABLED;
|
||||
delete process.env.OAUTH_DISABLE_DCR;
|
||||
delete process.env.DISABLE_LOGIN;
|
||||
|
||||
mocks.parseRequest.mockReset();
|
||||
mocks.createOauthClient.mockReset();
|
||||
|
||||
mocks.parseRequest.mockResolvedValue({ body });
|
||||
mocks.createOauthClient.mockImplementation(async input => ({
|
||||
...input,
|
||||
createdAt: new Date(),
|
||||
}));
|
||||
});
|
||||
|
||||
test('limits registrations per source address without affecting other sources', async () => {
|
||||
for (let i = 0; i < 20; i++) {
|
||||
expect((await register('203.0.113.1')).status).toBe(201);
|
||||
}
|
||||
|
||||
const limited = await register('203.0.113.1');
|
||||
|
||||
expect(limited.status).toBe(429);
|
||||
await expect(limited.json()).resolves.toMatchObject({ error: 'temporarily_unavailable' });
|
||||
|
||||
expect((await register('203.0.113.2')).status).toBe(201);
|
||||
expect(mocks.createOauthClient).toHaveBeenCalledTimes(21);
|
||||
});
|
||||
@@ -4,31 +4,14 @@ import { isDynamicRegistrationEnabled } from '@/lib/oauth/config';
|
||||
import { OAuthError, oauthErrorResponse, oauthJson } from '@/lib/oauth/errors';
|
||||
import { corsPreflight } from '@/lib/oauth/metadata';
|
||||
import { isAcceptableRedirectUri } from '@/lib/oauth/redirect';
|
||||
import redis from '@/lib/redis';
|
||||
import { checkRateLimit } from '@/lib/rate-limit';
|
||||
import { parseRequest } from '@/lib/request';
|
||||
import { notFound } from '@/lib/response';
|
||||
import { createOauthClient } from '@/queries/prisma/oauth';
|
||||
import { clientRegistrationRequestSchema } from '../schema';
|
||||
|
||||
const REGISTRATIONS_PER_HOUR = 20;
|
||||
const REGISTRATION_WINDOW_MS = 60 * 60 * 1000;
|
||||
let registrationWindow = { count: 0, expiresAt: 0 };
|
||||
|
||||
function isLocalRegistrationLimited() {
|
||||
const now = Date.now();
|
||||
|
||||
if (now >= registrationWindow.expiresAt) {
|
||||
registrationWindow = { count: 0, expiresAt: now + REGISTRATION_WINDOW_MS };
|
||||
}
|
||||
|
||||
// A process-wide cap keeps both registrations and limiter memory bounded without Redis.
|
||||
if (registrationWindow.count >= REGISTRATIONS_PER_HOUR) {
|
||||
return true;
|
||||
}
|
||||
|
||||
registrationWindow.count++;
|
||||
return false;
|
||||
}
|
||||
const REGISTRATION_WINDOW_SECONDS = 60 * 60;
|
||||
|
||||
export function OPTIONS() {
|
||||
return corsPreflight();
|
||||
@@ -55,15 +38,15 @@ export async function POST(request: Request) {
|
||||
}
|
||||
|
||||
try {
|
||||
const limited = redis.enabled
|
||||
? await redis.client.rateLimit(
|
||||
`oauth:register:${getIpAddress(request.headers) ?? 'unknown'}`,
|
||||
REGISTRATIONS_PER_HOUR + 1,
|
||||
REGISTRATION_WINDOW_MS / 1000,
|
||||
)
|
||||
: isLocalRegistrationLimited();
|
||||
// Budget is per source address so one requester cannot exhaust registration for every other
|
||||
// client. Enforced via Redis when available, otherwise a bounded per-key in-process window.
|
||||
const allowed = await checkRateLimit(
|
||||
`oauth:register:${getIpAddress(request.headers) ?? 'unknown'}`,
|
||||
REGISTRATIONS_PER_HOUR,
|
||||
REGISTRATION_WINDOW_SECONDS,
|
||||
);
|
||||
|
||||
if (limited) {
|
||||
if (!allowed) {
|
||||
throw new OAuthError('temporarily_unavailable', 'Too many registrations. Try again later.', {
|
||||
status: 429,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user