Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): rate-limit the registry connect recovery route
Jose Ramirez56ed33a8c6f6
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 948967183..18198fe98 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.375",+ "version": "0.1.376","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.375",+ "version": "0.1.376","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 9821d001b..643e068a3 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.375",+ "version": "0.1.376","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/admin/registryConnect.ts b/control-api/src/routes/admin/registryConnect.tsindex c71a32747..d19905949 100644--- a/control-api/src/routes/admin/registryConnect.ts+++ b/control-api/src/routes/admin/registryConnect.ts@@ -3,6 +3,7 @@ import type { Request, Response } from 'express'import { generateKeyPairSync } from 'node:crypto'import { config } from '../../config.js'import { type UiAuthedRequest, requireAuthForControlUI } from '../../middleware/controlUIAuth.js'+import { rateLimitMiddleware } from '../../middleware/rateLimitMiddleware.js'import { rootLogger } from '../../observability/logger.js'import { findAdminById } from '../../services/adminAuthService.js'import {@@ -506,6 +507,20 @@ export function createRegistryConnectRouter(): Router {router.post('/admin/registry/connect/recover',requireAuthForControlUI,+ // Per-admin token bucket — every call here rotates the deployment's+ // one-time claim token at the shared registry (/:id/claim-token), which+ // has no rate limiter of its own and emits a+ // deployment.claim_token_reissued audit event on each rotate. 10/min is+ // generous for a human-pressed recovery button while bounding registry+ // rotate/audit spam from a looped admin.+ rateLimitMiddleware({+ bucketType: 'registry_connect_recover',+ maxPerMinute: 10,+ getBucketKey: req => {+ const sub = (req as UiAuthedRequest).adminAuth?.sub+ return sub ? `registry_connect_recover:${sub}` : null+ },+ }),async (req, res, next) => {try {const ctx = await requireSelfHostedAdmin(req, res)diff --git a/control-api/test/routes.registryConnect.test.ts b/control-api/test/routes.registryConnect.test.tsindex 21e065218..f7e5f9abc 100644--- a/control-api/test/routes.registryConnect.test.ts+++ b/control-api/test/routes.registryConnect.test.ts@@ -4,6 +4,7 @@ import express from 'express'import { generateKeyPairSync } from 'node:crypto'import request from 'supertest'import { createRegistryConnectRouter } from '../src/routes/admin/registryConnect.js'+import { checkAndIncrement } from '../src/services/rateLimiterService.js'const { cfg } = vi.hoisted(() => ({cfg: {@@ -39,6 +40,13 @@ const connDb = vi.hoisted(() => ({}))vi.mock('../src/services/registryConnectionDb.js', () => connDb)+// The recover route is now behind rateLimitMiddleware, which calls+// checkAndIncrement (a real Postgres round-trip in production). Mock it so+// this suite stays hermetic; individual tests override the resolved value to+// exercise the allowed/denied branches.+const rateLimiter = vi.hoisted(() => ({ checkAndIncrement: vi.fn() }))+vi.mock('../src/services/rateLimiterService.js', () => rateLimiter)+function app(): express.Express {const a = express()a.use(express.json())@@ -82,6 +90,11 @@ beforeEach(() => {connDb.markConnected.mockResolvedValue(true)cfg.registryConnectionMode = 'self-hosted'cfg.registryAuthEnabled = true+ rateLimiter.checkAndIncrement.mockResolvedValue({+ allowed: true,+ remaining: 9,+ resetMs: Date.now() + 60000,+ })})afterEach(() => vi.restoreAllMocks())@@ -763,6 +776,54 @@ describe('POST recover', () => {expect(JSON.parse(String((claim[1] as RequestInit).body)).claim_token).toBe('tok-new')})+ // The route is rate-limited (each call rotates a one-time claim token at+ // the shared registry, which has no limiter of its own). This proves the+ // middleware sits AFTER requireAuthForControlUI (bucket keyed on+ // adminAuth.sub) and BEFORE the handler without breaking the normal+ // success path.+ it('is rate-limited per admin, keyed on adminAuth.sub, and still succeeds when allowed', async () => {+ connDb.getRegistryConnection.mockResolvedValue({+ status: 'approved',+ deploymentId: 'dep-1',+ keyId: 'kid-1',+ privateKeyPem: pkForTest(),+ requestedOrgName: 'acme',+ })+ connDb.markConnected.mockResolvedValue(true)+ routeFetch({+ '/status': () => json({ status: 'approved', suspended: false, claimed: false }, 200),+ 'claim-token': () => json({ claim_token: 'tok-new' }, 200),+ '/claim': () => json({ client_id: 'cid', client_secret: 'csecret', org: 'acme' }, 200),+ })+ const res = await request(app()).post('/admin/registry/connect/recover').expect(200)+ expect(res.body).toMatchObject({ state: 'connected', org: 'acme' })+ expect(checkAndIncrement).toHaveBeenCalledWith('registry_connect_recover:admin-uuid-123', 10)+ expect(res.headers['x-ratelimit-limit']).toBe('10')+ })++ // Proves the limiter actually blocks, and blocks BEFORE any registry work:+ // a denied admin must not burn a rotate or reach getRegistryConnection.+ it('429s when the per-admin bucket is exceeded, without touching the registry', async () => {+ connDb.getRegistryConnection.mockResolvedValue({+ status: 'approved',+ deploymentId: 'dep-1',+ keyId: 'kid-1',+ privateKeyPem: pkForTest(),+ requestedOrgName: 'acme',+ })+ rateLimiter.checkAndIncrement.mockResolvedValue({+ allowed: false,+ remaining: 0,+ resetMs: Date.now() + 30000,+ })+ const spy = routeFetch({})+ const res = await request(app()).post('/admin/registry/connect/recover').expect(429)+ expect(res.body.error).toBe('Too Many Requests')+ expect(res.headers['retry-after']).toBeDefined()+ expect(connDb.getRegistryConnection).not.toHaveBeenCalled()+ expect(spy.mock.calls.length).toBe(0)+ })+it('refuses when the local row is pending', async () => {connDb.getRegistryConnection.mockResolvedValue({status: 'pending',