Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): rate-limit internal mcp-oauth authorize-url and grant delete (codeql #1206/#1207)
Diego Zacarias9b83bb2cd412
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 1c219f88f..5af411a25 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.519",+ "version": "0.1.520","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.519",+ "version": "0.1.520","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/image-policy": "file:../packages/image-policy",diff --git a/control-api/package.json b/control-api/package.jsonindex 560a05f10..9c3a25f81 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.519",+ "version": "0.1.520","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.tsindex c7ea29862..4b76c8013 100644--- a/control-api/src/routes/internal/oauth.ts+++ b/control-api/src/routes/internal/oauth.ts@@ -3,6 +3,7 @@ import { config } from '../../config.js'import { pool } from '../../db.js'import { K8sGateway } from '../../k8s.js'import { requireInternalService } from '../../middleware/internalServiceAuth.js'+import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'import { buildAuthorizeUrl } from '../../oauth/authorizeUrlHelper.js'import {type McpServerOAuthReader,@@ -52,6 +53,32 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {const router = Router()const encryptionKey = deriveOAuthEncryptionKey(config.oauthEncryptionKey)+ // Rate limiter for the two U5 mcp-oauth internal routes (authorize-url mint ++ // grant delete). Both sit behind `requireInternalService('rpc-proxy')`, so the+ // sole caller is the already-trusted rpc-proxy; each request is user-driven (a+ // Connect / Disconnect click) and carries the initiator `userId`. Key the+ // bucket by that `userId` so one noisy user does not starve others on the+ // honest path — rpc-proxy derives `userId` from the session `auth.sub`, so this+ // is fairness among forwarded users, NOT a hard boundary against a compromised+ // rpc-proxy (that actor is already trusted by this seam). Fall back to the+ // service identity when no valid `userId` is present. Mirrors the custom+ // `rateLimitMiddleware` on the sibling broker routes (routes/mcpOauth.ts) — a+ // distributed, Postgres-backed limiter. Reuses the `oauthBrokerRlPerMin`+ // per-minute VALUE (default 60/min) but a SEPARATE bucket (`mcp_oauth_internal`+ // type + `mcp-oauth-internal:` key prefix), generous for click-driven traffic.+ const rpcOauthRateLimit = () =>+ rateLimitMiddleware({+ bucketType: 'mcp_oauth_internal',+ maxPerMinute: config.oauthBrokerRlPerMin,+ getBucketKey: req => {+ const uid =+ typeof req.body?.userId === 'string' && req.body.userId.length > 0+ ? req.body.userId+ : (req.internalService?.name ?? 'unknown')+ return `mcp-oauth-internal:${uid}`+ },+ })+const recipeReader: RecipeReader = {async read(name, namespace): Promise<RecipeWithOAuthClients | null> {try {@@ -126,6 +153,7 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {router.post('/internal/mcp-oauth/authorize-url',requireInternalService('rpc-proxy'),+ rpcOauthRateLimit(),async (req, res, next) => {try {const { mcpServerName, userId, contextId } = (req.body ?? {}) as {@@ -293,6 +321,7 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {router.delete('/internal/mcp-oauth/grant',requireInternalService('rpc-proxy'),+ rpcOauthRateLimit(),async (req, res, next) => {try {const { mcpServerName, userId, contextId } = (req.body ?? {}) as {diff --git a/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.tsindex e10a2f5b2..b1b430f3c 100644--- a/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts+++ b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts@@ -3,6 +3,7 @@ import request from 'supertest'import { createApp } from '../src/app.js'import { config } from '../src/config.js'import { verifyOAuthStateSignature } from '../src/oauth/state.js'+import { checkAndIncrement } from '../src/services/rateLimiterService.js'import { MockGateway } from './mockGateway.js'/**@@ -18,6 +19,21 @@ vi.mock('../src/db.js', () => ({pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },}))+// The route carries the repo's custom `rateLimitMiddleware`, whose real store+// (`checkAndIncrement`) hits Postgres and would otherwise count across the many+// same-`userId` requests in this suite. Mock it to always allow (mirrors the+// sibling routes.mcpOauth.test.ts); the "429 when denied" case below drives a+// one-shot deny to prove the limiter is actually mounted.+vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))+const MCP_NS = config.mcpServersNamespace// The configured external-rest-api service token (shared control-api test value).@@ -257,4 +273,26 @@ describe('POST /api/v1/internal/mcp-oauth/authorize-url (U5)', () => {expect(res.status).toBe(503)expect(res.body.error).toBe('integration_not_configured')})++ // The route is rate-limited (bucket keyed by the forwarded userId). When the+ // bucket is exhausted the middleware short-circuits with 429 BEFORE the+ // handler runs — no server read, no state mint.+ it('429 Too Many Requests when the rate limit is exceeded', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ vi.mocked(checkAndIncrement).mockResolvedValueOnce({+ allowed: false,+ remaining: 0,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 61,+ })+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'gdrive', userId: 'user-1' })+ expect(res.status).toBe(429)+ expect(res.body.error).toBe('Too Many Requests')+ // Denied before the handler — no membership lookup ran.+ expect(mockPoolQuery).not.toHaveBeenCalled()+ })})diff --git a/control-api/test/routes.internal.mcpOauthDisconnect.audit.test.ts b/control-api/test/routes.internal.mcpOauthDisconnect.audit.test.tsindex 5db6ca891..3522bb192 100644--- a/control-api/test/routes.internal.mcpOauthDisconnect.audit.test.ts+++ b/control-api/test/routes.internal.mcpOauthDisconnect.audit.test.ts@@ -23,6 +23,18 @@ vi.mock('../src/db.js', () => ({pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },}))+// The route carries the repo's custom `rateLimitMiddleware`; mock its store to+// always allow so the audit assertions here never race a real bucket.+vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))+// Capture every `req.log.info(...)` call. `req.log` is `rootLogger.child(...)`,// created per request AT RUNTIME — so a runtime spy on `rootLogger.child`// intercepts it without disturbing the import-time module children.diff --git a/control-api/test/routes.internal.mcpOauthDisconnect.test.ts b/control-api/test/routes.internal.mcpOauthDisconnect.test.tsindex 93c569e42..e9b43a1b9 100644--- a/control-api/test/routes.internal.mcpOauthDisconnect.test.ts+++ b/control-api/test/routes.internal.mcpOauthDisconnect.test.ts@@ -2,6 +2,7 @@ import { beforeEach, describe, expect, it, vi } from 'vitest'import request from 'supertest'import { createApp } from '../src/app.js'import { config } from '../src/config.js'+import { checkAndIncrement } from '../src/services/rateLimiterService.js'import { MockGateway } from './mockGateway.js'/**@@ -37,6 +38,20 @@ vi.mock('../src/db.js', () => ({pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },}))+// The route carries the repo's custom `rateLimitMiddleware`. Mock its real store+// (`checkAndIncrement`, Postgres-backed) to always allow so the many same-userId+// requests here don't trip a real bucket; the "429 when denied" case below+// drives a one-shot deny to prove the limiter is mounted.+vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))+const MCP_NS = config.mcpServersNamespaceconst URL = '/api/v1/internal/mcp-oauth/grant'@@ -236,4 +251,21 @@ describe('DELETE /api/v1/internal/mcp-oauth/grant (spec 11 U4)', () => {expect(res.body.error).toBe('context_mismatch')expect(deleteCalls()).toHaveLength(0)})++ // Rate-limited: an exhausted bucket short-circuits with 429 BEFORE the handler+ // runs — no server read, no grant delete.+ it('429 Too Many Requests when the rate limit is exceeded', async () => {+ seedOauthServer(gateway, { name: 'gdrive' })+ vi.mocked(checkAndIncrement).mockResolvedValueOnce({+ allowed: false,+ remaining: 0,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 61,+ })+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-1' })+ expect(res.status).toBe(429)+ expect(res.body.error).toBe('Too Many Requests')+ expect(mockPoolQuery).not.toHaveBeenCalled()+ })})