Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): rate-limit registry connect status + request routes
Jose Ramirezf51ffedd0b36
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 80a33eaa3..fe0977d40 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.390",+ "version": "0.1.391","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.390",+ "version": "0.1.391","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 a7e596286..d1acda856 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.390",+ "version": "0.1.391","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 9391fb64b..2585ba512 100644--- a/control-api/src/routes/admin/registryConnect.ts+++ b/control-api/src/routes/admin/registryConnect.ts@@ -201,100 +201,135 @@ export function createRegistryConnectRouter(): Router {// visible pre-claim (state ∈ disconnected|pending|connecting|approved|rejected|connected).// `connecting` is finished via POST /admin/registry/connect/recover, not by// pasting a token.- router.get('/admin/registry/connect', requireAuthForControlUI, async (req, res, next) => {- try {- const ctx = await requireSelfHostedAdmin(req, res)- if (!ctx) return- const row = await getRegistryConnection()- // Hoisted: every branch below reports authEnabled, and this call is- // cache-friendly here — getRegistryConnection() just populated (or hit)- // the process-local cache that isRegistryAuthActive()'s self-hosted- // path reads via resolveMachineCreds(), so this cannot trigger a fresh- // Postgres round-trip on its own. It CAN still reject (a bare- // pool.query with no try/catch of its own), so this is guarded the same- // way the sibling admin registry routes guard it- // (routes/admin/registry.ts's prepareKeysRequest/resolveSelfServiceOrg)- // rather than letting it fall through to the generic catch below and- // surface as a bare 500 — GET already documents a never-500-on-a-hiccup- // guarantee for the status poll, and this preserves that for the newly- // derived read too.- let authEnabled: boolean+ router.get(+ '/admin/registry/connect',+ requireAuthForControlUI,+ // Per-admin token bucket — this route is mounted by RegistryCatalog on+ // every Marketplace visit (control-ui/components/RegistryCatalog.tsx),+ // not just the connect panel, and is reachable by top-level cross-site+ // navigation (the session cookie is SameSite=Lax and this router has no+ // CSRF/origin check). Each call makes an outbound registry /status+ // fetch, so this bounds that outbound traffic under a CSRF-driven loop+ // while staying generous enough for normal navigation (Marketplace+ // mount, connect panel mount, refresh button).+ rateLimitMiddleware({+ bucketType: 'registry_connect_status',+ maxPerMinute: 30,+ getBucketKey: req => {+ const sub = (req as UiAuthedRequest).adminAuth?.sub+ return sub ? `registry_connect_status:${sub}` : null+ },+ }),+ async (req, res, next) => {try {- authEnabled = await isRegistryAuthActive()- } catch {- res.status(502).json({ error: 'registry_integration_error' })- return- }- if (!row) {- res.status(200).json({ state: 'disconnected', authEnabled })- return- }- if (row.status === 'connected') {- res.status(200).json({- state: 'connected',- deploymentId: row.deploymentId,- org: row.orgName,- authEnabled,- })- return- }- // A locally-'approved' row is a registry auto-approval whose claim has- // not landed. GET stays READ-ONLY: it reports state so the panel can- // offer the recover button. It must never rotate — GET is also called by- // RegistryCatalog on every Marketplace mount and is reachable by- // cross-site navigation (SameSite=Lax), so a mutation here would rotate- // claim tokens on catalog browsing and on CSRF.- if (row.status === 'approved') {+ const ctx = await requireSelfHostedAdmin(req, res)+ if (!ctx) return+ const row = await getRegistryConnection()+ // Hoisted: every branch below reports authEnabled, and this call is+ // cache-friendly here — getRegistryConnection() just populated (or hit)+ // the process-local cache that isRegistryAuthActive()'s self-hosted+ // path reads via resolveMachineCreds(), so this cannot trigger a fresh+ // Postgres round-trip on its own. It CAN still reject (a bare+ // pool.query with no try/catch of its own), so this is guarded the same+ // way the sibling admin registry routes guard it+ // (routes/admin/registry.ts's prepareKeysRequest/resolveSelfServiceOrg)+ // rather than letting it fall through to the generic catch below and+ // surface as a bare 500 — GET already documents a never-500-on-a-hiccup+ // guarantee for the status poll, and this preserves that for the newly+ // derived read too.+ let authEnabled: boolean+ try {+ authEnabled = await isRegistryAuthActive()+ } catch {+ res.status(502).json({ error: 'registry_integration_error' })+ return+ }+ if (!row) {+ res.status(200).json({ state: 'disconnected', authEnabled })+ return+ }+ if (row.status === 'connected') {+ res.status(200).json({+ state: 'connected',+ deploymentId: row.deploymentId,+ org: row.orgName,+ authEnabled,+ })+ return+ }+ // A locally-'approved' row is a registry auto-approval whose claim has+ // not landed. GET stays READ-ONLY: it reports state so the panel can+ // offer the recover button. It must never rotate — GET is also called by+ // RegistryCatalog on every Marketplace mount and is reachable by+ // cross-site navigation (SameSite=Lax), so a mutation here would rotate+ // claim tokens on catalog browsing and on CSRF.+ if (row.status === 'approved') {+ const poll = await pollRegistryStatus({+ deploymentId: row.deploymentId,+ keyId: row.keyId,+ privateKeyPem: row.privateKeyPem,+ adminId: ctx.adminId,+ })+ const recoveryError = poll?.claimed+ ? 'already_claimed'+ : poll?.suspended+ ? 'deployment_suspended'+ : undefined+ res.status(200).json({+ state: 'connecting',+ deploymentId: row.deploymentId,+ requestedOrgName: row.requestedOrgName,+ authEnabled,+ ...(recoveryError ? { recoveryError } : {}),+ })+ return+ }+ // Not yet connected — poll the registry so an operator approval (or+ // rejection) is reflected before the user attempts to claim.const poll = await pollRegistryStatus({deploymentId: row.deploymentId,keyId: row.keyId,privateKeyPem: row.privateKeyPem,adminId: ctx.adminId,})- const recoveryError = poll?.claimed- ? 'already_claimed'- : poll?.suspended- ? 'deployment_suspended'- : undefined+ const registryStatus = poll?.status ?? null+ const state =+ registryStatus === 'approved'+ ? 'approved'+ : registryStatus === 'rejected'+ ? 'rejected'+ : 'pending'res.status(200).json({- state: 'connecting',+ state,deploymentId: row.deploymentId,requestedOrgName: row.requestedOrgName,authEnabled,- ...(recoveryError ? { recoveryError } : {}),})- return+ } catch (err) {+ next(err)}- // Not yet connected — poll the registry so an operator approval (or- // rejection) is reflected before the user attempts to claim.- const poll = await pollRegistryStatus({- deploymentId: row.deploymentId,- keyId: row.keyId,- privateKeyPem: row.privateKeyPem,- adminId: ctx.adminId,- })- const registryStatus = poll?.status ?? null- const state =- registryStatus === 'approved'- ? 'approved'- : registryStatus === 'rejected'- ? 'rejected'- : 'pending'- res.status(200).json({- state,- deploymentId: row.deploymentId,- requestedOrgName: row.requestedOrgName,- authEnabled,- })- } catch (err) {- next(err)}- })+ )// POST request — generate keypair, register with the registry, persist pending.router.post('/admin/registry/connect/request',requireAuthForControlUI,+ // Per-admin token bucket — registration is a rare, deliberate,+ // once-in-a-deployment-lifetime action, and each call consumes one of+ // the shared registry's ~5/day per-IP registration attempts (and can+ // create a deployment row there). 3/min still allows a legitimate retry+ // after a transient failure (e.g. a typo'd org name) while capping how+ // much of that daily budget a looped admin can burn through in a single+ // minute.+ rateLimitMiddleware({+ bucketType: 'registry_connect_request',+ maxPerMinute: 3,+ getBucketKey: req => {+ const sub = (req as UiAuthedRequest).adminAuth?.sub+ return sub ? `registry_connect_request:${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 65896164f..c96e07635 100644--- a/control-api/test/routes.registryConnect.test.ts+++ b/control-api/test/routes.registryConnect.test.ts@@ -496,6 +496,75 @@ describe('registry connect flow', () => {.send({ claim_token: 'tok-abc' }).expect(500)})++ // GET is mounted by RegistryCatalog on every Marketplace visit and is+ // CSRF-reachable (SameSite=Lax, no origin check), so it too is now behind a+ // per-admin token bucket. This proves the middleware sits AFTER+ // requireAuthForControlUI (bucket keyed on adminAuth.sub) and BEFORE the+ // handler without breaking the normal success path.+ it('GET is rate-limited per admin, keyed on adminAuth.sub, and still succeeds when allowed', async () => {+ connDb.getRegistryConnection.mockResolvedValue(null)+ const res = await request(app()).get('/admin/registry/connect').expect(200)+ expect(res.body.state).toBe('disconnected')+ expect(checkAndIncrement).toHaveBeenCalledWith('registry_connect_status:admin-uuid-123', 30)+ expect(res.headers['x-ratelimit-limit']).toBe('30')+ })++ // Proves the limiter blocks BEFORE any DB/registry work: a denied admin+ // must not reach getRegistryConnection.+ it('GET 429s when the per-admin bucket is exceeded, without touching the registry', async () => {+ rateLimiter.checkAndIncrement.mockResolvedValue({+ allowed: false,+ remaining: 0,+ resetMs: Date.now() + 30000,+ })+ const res = await request(app()).get('/admin/registry/connect').expect(429)+ expect(res.body.error).toBe('Too Many Requests')+ expect(res.headers['retry-after']).toBeDefined()+ expect(connDb.getRegistryConnection).not.toHaveBeenCalled()+ })++ // POST request registers against the SHARED production registry — each call+ // consumes one of its ~5/day per-IP registration attempts. This proves the+ // middleware sits AFTER requireAuthForControlUI (bucket keyed on+ // adminAuth.sub) and BEFORE the handler without breaking the normal success+ // path.+ it('POST request is rate-limited per admin, keyed on adminAuth.sub, and still succeeds when allowed', async () => {+ connDb.getRegistryConnection.mockResolvedValue(null)+ vi.spyOn(globalThis, 'fetch').mockResolvedValue(+ new Response(JSON.stringify({ deployment_id: 'dep-9', key_id: 'kid-9', status: 'pending' }), {+ status: 202,+ })+ )+ const res = await request(app())+ .post('/admin/registry/connect/request')+ .send({ requested_org_name: 'acme', contact_email: '[email protected]' })+ .expect(202)+ expect(res.body.state).toBe('pending')+ expect(checkAndIncrement).toHaveBeenCalledWith('registry_connect_request:admin-uuid-123', 3)+ expect(res.headers['x-ratelimit-limit']).toBe('3')+ })++ // Proves the limiter blocks BEFORE any registry work: a denied admin must+ // not burn a registration attempt against the shared registry's small daily+ // per-IP quota.+ it('POST request 429s when the per-admin bucket is exceeded, without touching the registry', async () => {+ connDb.getRegistryConnection.mockResolvedValue(null)+ rateLimiter.checkAndIncrement.mockResolvedValue({+ allowed: false,+ remaining: 0,+ resetMs: Date.now() + 30000,+ })+ const spy = routeFetch({})+ const res = await request(app())+ .post('/admin/registry/connect/request')+ .send({ requested_org_name: 'acme', contact_email: '[email protected]' })+ .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)+ })})describe('register — auto-claim (201)', () => {