Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): derive authEnabled on the connect routes and guard an unconfigured registry URL
Jose Ramirezb816f1171a54
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex eb5c37b60..1edb84401 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.385",+ "version": "0.1.386","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.385",+ "version": "0.1.386","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 41d99b11c..8f4a4c6cd 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.385",+ "version": "0.1.386","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 d19905949..9391fb64b 100644--- a/control-api/src/routes/admin/registryConnect.ts+++ b/control-api/src/routes/admin/registryConnect.ts@@ -9,6 +9,7 @@ import { findAdminById } from '../../services/adminAuthService.js'import {deleteConnection,getRegistryConnection,+ isRegistryAuthActive,markConnected,upsertPendingConnection,} from '../../services/registryConnectionDb.js'@@ -137,6 +138,13 @@ export function createRegistryConnectRouter(): Router {res.status(409).json({ error: 'not_self_hosted' })return null}+ // Task 4 permits booting without a registry URL. Fail cleanly here rather+ // than letting base() build '/api/v1/deployments' and fetch() throw+ // TypeError: Failed to parse URL, which surfaces as a bare 500.+ if (config.registryUrl === '') {+ res.status(409).json({ error: 'registry_url_not_configured' })+ return null+ }const sub = (req as UiAuthedRequest).adminAuth?.subconst admin = sub ? await findAdminById(sub) : nullif (!admin || admin.status !== 'active') {@@ -198,8 +206,27 @@ export function createRegistryConnectRouter(): Router {const ctx = await requireSelfHostedAdmin(req, res)if (!ctx) returnconst 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: config.registryAuthEnabled })+ res.status(200).json({ state: 'disconnected', authEnabled })return}if (row.status === 'connected') {@@ -207,7 +234,7 @@ export function createRegistryConnectRouter(): Router {state: 'connected',deploymentId: row.deploymentId,org: row.orgName,- authEnabled: config.registryAuthEnabled,+ authEnabled,})return}@@ -233,7 +260,7 @@ export function createRegistryConnectRouter(): Router {state: 'connecting',deploymentId: row.deploymentId,requestedOrgName: row.requestedOrgName,- authEnabled: config.registryAuthEnabled,+ authEnabled,...(recoveryError ? { recoveryError } : {}),})return@@ -257,7 +284,7 @@ export function createRegistryConnectRouter(): Router {state,deploymentId: row.deploymentId,requestedOrgName: row.requestedOrgName,- authEnabled: config.registryAuthEnabled,+ authEnabled,})} catch (err) {next(err)@@ -424,11 +451,23 @@ export function createRegistryConnectRouter(): Router {claimToken: reg.claim_token as string,})if (outcome.kind === 'connected') {+ // The connect itself already succeeded (markConnected committed+ // inside redeemClaim) by the time we get here — a rejecting+ // isRegistryAuthActive() must not surface as an uncaught rejection+ // or a bare 500 for a request whose underlying mutation landed.+ // Same 502 the sibling admin registry routes use for this accessor.+ let authEnabled: boolean+ try {+ authEnabled = await isRegistryAuthActive()+ } catch {+ res.status(502).json({ error: 'registry_integration_error' })+ return+ }res.status(200).json({state: 'connected',org: outcome.org,deploymentId: reg.deployment_id,- authEnabled: config.registryAuthEnabled,+ authEnabled,})return}@@ -601,13 +640,25 @@ export function createRegistryConnectRouter(): Router {claimToken,})switch (outcome.kind) {- case 'connected':+ case 'connected': {+ // Same reasoning as the auto-claim branch in POST /request: the+ // recover has already succeeded (markConnected committed) by the+ // time we're here, so a rejecting isRegistryAuthActive() must+ // degrade to 502 rather than an uncaught rejection or a bare 500.+ let authEnabled: boolean+ try {+ authEnabled = await isRegistryAuthActive()+ } catch {+ res.status(502).json({ error: 'registry_integration_error' })+ return+ }res.status(200).json({state: 'connected',org: outcome.org,- authEnabled: config.registryAuthEnabled,+ authEnabled,})return+ }// Terminal: the client is disabled (operator suspension). Retrying// rotates forever against a deployment that was deliberately killed.case 'client_unavailable':diff --git a/control-api/test/routes.registryConnect.test.ts b/control-api/test/routes.registryConnect.test.tsindex f7e5f9abc..65896164f 100644--- a/control-api/test/routes.registryConnect.test.ts+++ b/control-api/test/routes.registryConnect.test.ts@@ -37,6 +37,14 @@ const connDb = vi.hoisted(() => ({upsertPendingConnection: vi.fn(),markConnected: vi.fn(),deleteConnection: vi.fn(),+ // The routes now derive authEnabled from credentials rather than reading+ // config.registryAuthEnabled directly. This whole-module mock replaces the+ // entire registryConnectionDb surface, so without this key `connDb` has no+ // `isRegistryAuthActive` property and the routes' `await+ // isRegistryAuthActive()` throws a TypeError in every handler. beforeEach+ // re-arms a cfg-mirroring default (see below); tests that need the derived+ // value to diverge from cfg override it per-test.+ isRegistryAuthActive: vi.fn(),}))vi.mock('../src/services/registryConnectionDb.js', () => connDb)@@ -88,8 +96,25 @@ beforeEach(() => {status: 'active',})connDb.markConnected.mockResolvedValue(true)+ // Mirrors the real accessor's derivation at call time rather than a+ // captured literal default (e.g. a static mockResolvedValue(true)), so+ // pre-existing tests that only flip cfg.registryAuthEnabled — without ever+ // touching this mock — still see it reflected in authEnabled (see 'GET+ // connected -> includes authEnabled reflecting config (false)' below,+ // which would otherwise get a stale `true`). vi.clearAllMocks() only clears+ // call history, not implementations, but afterEach's restoreAllMocks()+ // strips a prior test's mockResolvedValue/mockRejectedValue override, so+ // this re-arm still runs every time to guarantee the default is never+ // stale. Tests that need the derived value to diverge from cfg override it+ // per-test with their own mockResolvedValue/mockRejectedValue, which wins+ // for that test since it runs after this beforeEach.+ connDb.isRegistryAuthActive.mockImplementation(async () => cfg.registryAuthEnabled)cfg.registryConnectionMode = 'self-hosted'cfg.registryAuthEnabled = true+ // Reset every time: the registry_url_not_configured test below sets this to+ // '' to exercise the new guard; without resetting it here that empty+ // string would leak into every test that runs after it in this file.+ cfg.registryUrl = 'https://example.com'rateLimiter.checkAndIncrement.mockResolvedValue({allowed: true,remaining: 9,@@ -107,6 +132,33 @@ describe('registry connect flow', () => {expect(res.body.authEnabled).toBe(true)})+ // The discriminator: cfg.registryAuthEnabled is left at the beforeEach+ // default (true) and never touched here. Only the mocked accessor says+ // false. A route still reading config.registryAuthEnabled directly would+ // report authEnabled: true and fail this assertion.+ it('GET reports authEnabled false when no credentials exist', async () => {+ connDb.isRegistryAuthActive.mockResolvedValue(false)+ connDb.getRegistryConnection.mockResolvedValue(null)+ const res = await request(app()).get('/admin/registry/connect').expect(200)+ expect(res.body).toMatchObject({ state: 'disconnected', authEnabled: false })+ })++ // isRegistryAuthActive() can reject: self-hosted mode reaches a raw+ // pool.query (via getRegistryConnection, inside resolveMachineCreds) with+ // no try/catch of its own — see routes.adminRegistryKeys.test.ts's sibling+ // test for the admin registry routes' version of this same hazard. GET+ // already documents a "never 500 on a registry hiccup" guarantee for the+ // status poll (pollRegistryStatus); this extends the same clean-degrade+ // treatment to the newly-derived authEnabled read instead of letting the+ // rejection fall through to the router's generic catch -> next(err) -> a+ // bare 500.+ it('GET → 502 registry_integration_error when isRegistryAuthActive rejects (does not throw)', async () => {+ connDb.getRegistryConnection.mockResolvedValue(null)+ connDb.isRegistryAuthActive.mockRejectedValue(new Error('pg blip'))+ const res = await request(app()).get('/admin/registry/connect').expect(502)+ expect(res.body.error).toBe('registry_integration_error')+ })+it('GET connected → includes authEnabled reflecting config (true)', async () => {cfg.registryAuthEnabled = trueconnDb.getRegistryConnection.mockResolvedValue({@@ -135,6 +187,15 @@ describe('registry connect flow', () => {expect(res.body.error).toBe('not_self_hosted')})+ // Task 4 lets an unconfigured URL boot, so the connect routes must fail+ // cleanly rather than building a request against '' (fetch throws+ // TypeError: Failed to parse URL -> a bare 500).+ it('returns 409 registry_url_not_configured when no registry URL is set', async () => {+ cfg.registryUrl = ''+ const res = await request(app()).get('/admin/registry/connect').expect(409)+ expect(res.body.error).toBe('registry_url_not_configured')+ })+it('GET pending → polls the registry status endpoint and surfaces approval', async () => {connDb.getRegistryConnection.mockResolvedValue({status: 'pending',@@ -394,6 +455,29 @@ describe('registry connect flow', () => {expect(connDb.deleteConnection).toHaveBeenCalled()})+ // The disconnect transition: nothing currently re-reads state after a+ // DELETE. cfg.registryAuthEnabled is never touched in this test (stays+ // true throughout, per beforeEach) -- only the mocked accessor moves, so+ // this discriminates a route deriving authEnabled from+ // isRegistryAuthActive() from one still reading config.registryAuthEnabled.+ it('authEnabled flips back to false after disconnect', { retry: 0 }, async () => {+ connDb.getRegistryConnection.mockResolvedValue({+ status: 'connected',+ deploymentId: 'dep-1',+ orgName: 'acme',+ })+ connDb.isRegistryAuthActive.mockResolvedValue(true)+ const before = await request(app()).get('/admin/registry/connect').expect(200)+ expect(before.body.authEnabled).toBe(true)++ await request(app()).delete('/admin/registry/connect').expect(204)++ connDb.getRegistryConnection.mockResolvedValue(null)+ connDb.isRegistryAuthActive.mockResolvedValue(false)+ const after = await request(app()).get('/admin/registry/connect').expect(200)+ expect(after.body).toMatchObject({ state: 'disconnected', authEnabled: false })+ })+// The redeemClaim extraction must NOT convert a registry-unreachable failure// into a 502. It escapes the handler and the Express error handler makes it a// 500, exactly as before the refactor. Collapsing it to 502 would be a silent@@ -456,6 +540,31 @@ describe('register — auto-claim (201)', () => {})+ // By the time this branch runs, redeemClaim has already persisted the+ // credentials (markConnected succeeded) -- isRegistryAuthActive() rejecting+ // here must not crash the process. It degrades to the same 502 the sibling+ // admin registry routes use for this accessor (routes.adminRegistryKeys.test.ts),+ // rather than falling through to the router's generic catch -> next(err) ->+ // a bare 500 for a request whose underlying connect already succeeded.+ it('502 registry_integration_error when isRegistryAuthActive rejects after a successful auto-claim', async () => {+ connDb.getRegistryConnection.mockResolvedValue(null)+ connDb.markConnected.mockResolvedValue(true)+ connDb.isRegistryAuthActive.mockRejectedValue(new Error('pg blip'))+ routeFetch({+ '/register': () =>+ json(+ { deployment_id: 'dep-1', key_id: 'kid-1', status: 'approved', claim_token: 'tok-abc' },+ 201+ ),+ '/claim': () => json({ client_id: 'cid', client_secret: 'csecret', org: 'acme' }, 200),+ })+ const res = await request(app())+ .post('/admin/registry/connect/request')+ .send({ requested_org_name: 'acme', contact_email: '[email protected]' })+ .expect(502)+ expect(res.body.error).toBe('registry_integration_error')+ })+// The mocks return undefined, so `await x` and `void x` produce IDENTICAL// invocationCallOrder — an ordering assertion built on call order is green// against the exact mutation it exists to catch. Assert on an event log@@ -776,6 +885,29 @@ describe('POST recover', () => {expect(JSON.parse(String((claim[1] as RequestInit).body)).claim_token).toBe('tok-new')})+ // Same hazard as the auto-claim path: by the time 'connected' is reached+ // here, the rotate + redeemClaim have already succeeded (markConnected+ // committed). isRegistryAuthActive() rejecting must degrade to 502, not an+ // uncaught rejection or a bare 500, for a recovery that already succeeded.+ it('502 registry_integration_error when isRegistryAuthActive rejects after a successful recover', async () => {+ connDb.getRegistryConnection.mockResolvedValue({+ status: 'approved',+ deploymentId: 'dep-1',+ keyId: 'kid-1',+ privateKeyPem: pkForTest(),+ requestedOrgName: 'acme',+ })+ connDb.markConnected.mockResolvedValue(true)+ connDb.isRegistryAuthActive.mockRejectedValue(new Error('pg blip'))+ 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(502)+ expect(res.body.error).toBe('registry_integration_error')+ })+// 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