Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): harden self-hosted registry auth
Jose Ramirez943ca5f7e36a
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex fe0977d40..cb0f7a33b 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.391",+ "version": "0.1.392","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.391",+ "version": "0.1.392","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 d1acda856..6d18bd0d2 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.391",+ "version": "0.1.392","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/registryBootGuard.ts b/control-api/src/registryBootGuard.tsindex 6734c8cae..7b33f5878 100644--- a/control-api/src/registryBootGuard.ts+++ b/control-api/src/registryBootGuard.ts@@ -31,7 +31,6 @@ import type { RegistryConnectionRow } from './services/registryConnectionDb.js'*/export async function logRegistryConnectionState(): Promise<void> {if (config.registryConnectionMode !== 'self-hosted') return- if (config.registryUrl === '') returnlet row: RegistryConnectionRow | null = nulltry {row = await getRegistryConnection()diff --git a/control-api/src/routes/admin/registry.ts b/control-api/src/routes/admin/registry.tsindex e7e39552b..ea085ba9c 100644--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@ -2177,6 +2177,10 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {res.status(409).json({ error: 'registry_auth_disabled' })return null}+ if (config.registryConnectionMode === 'self-hosted' && 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') {@@ -2282,6 +2286,10 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {res.status(409).json({ error: 'registry_auth_disabled' })return null}+ if (config.registryConnectionMode === 'self-hosted' && config.registryUrl === '') {+ res.status(409).json({ error: 'registry_url_not_configured' })+ return null+ }const actingUserId = (req as UiAuthedRequest).adminAuth?.subif (!actingUserId) {res.status(401).json({ error: 'unauthorized' })diff --git a/control-api/src/routes/admin/registryConnect.ts b/control-api/src/routes/admin/registryConnect.tsindex 2585ba512..f3b82db36 100644--- a/control-api/src/routes/admin/registryConnect.ts+++ b/control-api/src/routes/admin/registryConnect.ts@@ -102,8 +102,11 @@ export function createRegistryConnectRouter(): Router {// Buffer.from(null) crash inside the encryption path.if (typeof claimed.client_id !== 'string' ||+ claimed.client_id.length === 0 ||typeof claimed.client_secret !== 'string' ||- typeof claimed.org !== 'string'+ claimed.client_secret.length === 0 ||+ typeof claimed.org !== 'string' ||+ claimed.org.length === 0) {rootLogger.error({ event: 'registry_connect_claim_malformed', status: claimRes.status },@@ -132,16 +135,17 @@ export function createRegistryConnectRouter(): Router {async function requireSelfHostedAdmin(req: Request,- res: Response+ res: Response,+ options: { requireRegistryUrl?: boolean } = {}): Promise<{ adminId: string } | null> {if (config.registryConnectionMode !== 'self-hosted') {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 === '') {+ // Network-dependent connect routes need a configured registry URL. DELETE+ // is deliberately exempt: it only removes local credentials, and must+ // remain the recovery path after an operator removes a broken/stale URL.+ if (options.requireRegistryUrl !== false && config.registryUrl === '') {res.status(409).json({ error: 'registry_url_not_configured' })return null}@@ -486,23 +490,16 @@ 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- }+ // redeemClaim validated a non-empty credential pair and+ // markConnected committed it. Do not perform a second fallible DB+ // read after this irreversible one-time claim has succeeded: a+ // transient read failure must not turn a completed connection into a+ // misleading 502 response.res.status(200).json({state: 'connected',org: outcome.org,deploymentId: reg.deployment_id,- authEnabled,+ authEnabled: true,})return}@@ -676,21 +673,13 @@ export function createRegistryConnectRouter(): Router {})switch (outcome.kind) {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- }+ // Same committed-outcome rule as POST /request: recovery already+ // consumed the one-time token and stored a validated credential+ // pair, so its response must not depend on a redundant DB read.res.status(200).json({state: 'connected',org: outcome.org,- authEnabled,+ authEnabled: true,})return}@@ -725,7 +714,7 @@ export function createRegistryConnectRouter(): Router {// DELETE — disconnect (drop the row).router.delete('/admin/registry/connect', requireAuthForControlUI, async (req, res, next) => {try {- const ctx = await requireSelfHostedAdmin(req, res)+ const ctx = await requireSelfHostedAdmin(req, res, { requireRegistryUrl: false })if (!ctx) returnawait deleteConnection()res.status(204).end()diff --git a/control-api/src/services/registryClient.ts b/control-api/src/services/registryClient.tsindex dfea3ab24..1616741f1 100644--- a/control-api/src/services/registryClient.ts+++ b/control-api/src/services/registryClient.ts@@ -1,13 +1,12 @@/*** Registry Client — fetches entries from Clerum Registry service.- * When CLERUM_REGISTRY_AUTH_ENABLED=true, calls are Bearer-authenticated- * via OAuth2 client_credentials minted from CLERUM_REGISTRY_CLIENT_ID/SECRET.- * Auth-off mode preserved for minikube: mintToken returns "" and the- * Authorization header is omitted downstream.+ * Managed deployments use CLERUM_REGISTRY_AUTH_ENABLED plus env-provided+ * client credentials. Self-hosted deployments become Bearer-authenticated when+ * their claimed registry_connection row holds machine credentials.*/import { config } from '../config.js'import { rootLogger } from '../observability/logger.js'-import { isRegistryAuthActive, resolveMachineCreds } from './registryConnectionDb.js'+import { resolveMachineCreds } from './registryConnectionDb.js'const API_BASE = `${config.registryUrl}/api/v1`@@ -76,37 +75,33 @@ export async function mintToken(envOverride?: NodeJS.ProcessEnv): Promise<stringconst now = Date.now()if (cached && now < cached.expiresAt - 30_000) return cached.token- // Env precedence: explicit override wins; otherwise process.env / config- // (which is what config also reads, but routes through env directly here so- // tests can mutate without rebuilding the config singleton). This resolves- // MANAGED creds — env/Secret, unchanged from before.- let id = env.CLERUM_REGISTRY_CLIENT_ID || (envOverride ? '' : config.registryClientId)- let secret = env.CLERUM_REGISTRY_CLIENT_SECRET || (envOverride ? '' : config.registryClientSecret)+ // An explicit override is a test-only path and remains fully env-driven. In+ // production, credentials MUST come from the mode-aware resolver: managed+ // reads config/env, self-hosted reads only the claimed DB row. Reading env+ // first here would create a split brain where isRegistryAuthActive authorizes+ // the DB identity while the registry client authenticates as a stale managed+ // identity left in the pod environment.+ let id = envOverride ? env.CLERUM_REGISTRY_CLIENT_ID || '' : ''+ let secret = envOverride ? env.CLERUM_REGISTRY_CLIENT_SECRET || '' : ''// Single source of truth for the registry base URL — env override wins for// tests/minikube, else config.registryUrl (mandatory + allowlisted when auth// is on). resolveMachineCreds no longer carries a `url`.const url = env.CLERUM_REGISTRY_URL || (envOverride ? '' : config.registryUrl)- // When creds are still absent AND no explicit env override is in play, fall- // through to the mode-aware resolver: managed → config env creds (a no-op- // here, already resolved above); self-hosted → the registry_connection DB row- // populated at claim. An explicit envOverride short-circuits this so the- // env-driven test/minikube paths never touch the DB.- if ((!id || !secret) && !envOverride) {+ let authEnabled = false+ if (!envOverride) {const resolved = await resolveMachineCreds()if (resolved) {- id = id || resolved.clientId- secret = secret || resolved.clientSecret+ id = resolved.clientId+ secret = resolved.clientSecret}+ // Derive the decision from the SAME resolution used for the credentials.+ // Managed deliberately keeps its env flag; self-hosted is active exactly+ // when the DB row yielded a complete credential pair.+ authEnabled =+ config.registryConnectionMode === 'managed' ? config.registryAuthEnabled : resolved !== null}- // Auth is ACTIVE when credentials actually exist (self-hosted) or the env- // says so (managed). The old CLERUM_REGISTRY_AUTH_ENABLED override is gone:- // in self-hosted the var is inert, and in managed isRegistryAuthActive()- // returns it verbatim. envOverride still short-circuits for the env-driven- // test/minikube paths, which must never touch the DB.- const authEnabled = envOverride ? false : await isRegistryAuthActive()-if (!id || !secret) {if (!authEnabled) return '' // minikube / auth-offthrow new Error(diff --git a/control-api/test/main.selfHostedBootGuard.test.ts b/control-api/test/main.selfHostedBootGuard.test.tsindex ce176effa..9b5efcd75 100644--- a/control-api/test/main.selfHostedBootGuard.test.ts+++ b/control-api/test/main.selfHostedBootGuard.test.ts@@ -102,9 +102,14 @@ describe('logRegistryConnectionState', () => {expect(logger.rootLogger.info).not.toHaveBeenCalled()})- it('no-op when no registry URL is configured', async () => {+ it('still reports connection state when no registry URL is configured', async () => {cfg.registryUrl = ''+ connDb.getRegistryConnection.mockResolvedValue({ status: 'connected', clientId: 'cid' })await expect(logRegistryConnectionState()).resolves.toBeUndefined()- expect(connDb.getRegistryConnection).not.toHaveBeenCalled()+ expect(connDb.getRegistryConnection).toHaveBeenCalledTimes(1)+ expect(logger.rootLogger.info).toHaveBeenCalledWith(+ expect.objectContaining({ connected: true }),+ expect.any(String)+ )})})diff --git a/control-api/test/registryClient.test.ts b/control-api/test/registryClient.test.tsindex ca3ef29fe..79cf2164a 100644--- a/control-api/test/registryClient.test.ts+++ b/control-api/test/registryClient.test.ts@@ -11,17 +11,18 @@ import {searchEntries,} from '../src/services/registryClient.js'-// Controls the derived-auth path (Task 7): mintToken() with NO envOverride-// consults isRegistryAuthActive() for the authEnabled decision and-// resolveMachineCreds() for self-hosted credentials. Every OTHER test in this-// file drives mintToken via ENV_OVERRIDE or process.env id/secret directly,-// so it never reaches either mock — only the two derived-auth tests below do.+// mintToken() with NO envOverride resolves both the active decision and the+// credential pair through this mode-aware dependency. Most tests in this file+// populate process.env; the default mock mirrors managed-mode resolution from+// those values so they exercise the normal client path without rebuilding the+// config singleton.const connDb = vi.hoisted(() => ({- isRegistryAuthActive: vi.fn(),resolveMachineCreds: vi.fn(),}))vi.mock('../src/services/registryConnectionDb.js', () => connDb)+const ORIGINAL_ENV = { ...process.env }+function fakeTokenResponse(token = 'tok-abc', expiresIn = 600) {return new Response(JSON.stringify({ access_token: token, token_type: 'Bearer', expires_in: expiresIn }),@@ -37,18 +38,18 @@ const ENV_OVERRIDE: NodeJS.ProcessEnv = {}beforeEach(() => {+ process.env = { ...ORIGINAL_ENV }__resetTokenCacheForTests()__resetScopeCacheForTests()- // Deterministic defaults for the connDb mock (no creds, auth off) rather- // than relying on an unconfigured vi.fn() resolving `undefined` (falsy, but- // for the wrong reason). Only the derived-auth tests below reach these; every- // other test in the file resolves id/secret from ENV_OVERRIDE/process.env- // before this mock would ever be consulted.- connDb.resolveMachineCreds.mockReset().mockResolvedValue(null)- connDb.isRegistryAuthActive.mockReset().mockResolvedValue(false)+ connDb.resolveMachineCreds.mockReset().mockImplementation(async () => {+ const clientId = process.env.CLERUM_REGISTRY_CLIENT_ID+ const clientSecret = process.env.CLERUM_REGISTRY_CLIENT_SECRET+ return clientId && clientSecret ? { clientId, clientSecret } : null+ })})afterEach(() => {+ process.env = { ...ORIGINAL_ENV }vi.unstubAllGlobals()vi.useRealTimers()})@@ -146,15 +147,8 @@ describe('registryClient — mintToken cache behavior', () => {})describe('registryClient — mintToken derived auth (no envOverride)', () => {- // Critical: no ENV_OVERRIDE here. An envOverride short-circuits authEnabled- // to false by design (see mintToken), so these two tests must call- // mintToken() bare to actually reach the isRegistryAuthActive()-derived path.- // They also explicitly blank CLIENT_ID/SECRET: earlier tests in this file- // mutate the REAL process.env via Object.assign(process.env, ENV_OVERRIDE)- // and never reset it (only afterEach's unstubAllGlobals/useRealTimers run),- // so without this, a leftover id/secret from a prior test would populate- // `id`/`secret` and the credential-missing branch under test would never- // trigger.+ // Critical: no ENV_OVERRIDE here. That test-only path intentionally bypasses+ // the mode-aware resolver.beforeEach(() => {process.env = {...process.env,@@ -165,21 +159,8 @@ describe('registryClient — mintToken derived auth (no envOverride)', () => {it('returns an empty token when auth is inactive and no creds exist', async () => {connDb.resolveMachineCreds.mockResolvedValue(null)- connDb.isRegistryAuthActive.mockResolvedValue(false)await expect(mintToken()).resolves.toBe('') // NO ENV_OVERRIDE — see above- // Without this, the assertion above is vacuous: the old env-var-based- // implementation also resolves authEnabled=false here (config.registryAuthEnabled- // is frozen false at module load in this test env) WITHOUT ever calling- // isRegistryAuthActive — so the return-value alone can't tell the derived- // path apart from the old, un-refactored one. This call-count assertion fails- // under both a full revert and a "hardcoded/ignored accessor" mutation.- expect(connDb.isRegistryAuthActive).toHaveBeenCalledTimes(1)- })-- it('throws when auth is active but credentials are unavailable', async () => {- connDb.resolveMachineCreds.mockResolvedValue(null)- connDb.isRegistryAuthActive.mockResolvedValue(true)- await expect(mintToken()).rejects.toThrow(/machine credentials unavailable/)+ expect(connDb.resolveMachineCreds).toHaveBeenCalledTimes(1)})})diff --git a/control-api/test/routes.adminRegistryGrants.test.ts b/control-api/test/routes.adminRegistryGrants.test.tsindex c6dc7463c..960405ead 100644--- a/control-api/test/routes.adminRegistryGrants.test.ts+++ b/control-api/test/routes.adminRegistryGrants.test.ts@@ -57,7 +57,11 @@ vi.mock('../src/services/adminAuthService.js', () => ({ findAdminById: vi.fn() }// which branches on mode first. 'managed' makes it return registryAuthEnabled// verbatim, which is the behaviour these tests intend to exercise.const { cfg } = vi.hoisted(() => ({- cfg: { registryAuthEnabled: true, registryConnectionMode: 'managed' },+ cfg: {+ registryAuthEnabled: true,+ registryConnectionMode: 'managed',+ registryUrl: 'https://registry.evenfire.ai',+ },}))vi.mock('../src/config.js', () => ({ config: cfg }))// Partial mock (unlike the Keys file's full replacement): the "wire shape"@@ -98,6 +102,7 @@ beforeEach(() => {vi.clearAllMocks()cfg.registryAuthEnabled = truecfg.registryConnectionMode = 'managed'+ cfg.registryUrl = 'https://registry.evenfire.ai'// Default mirrors the real accessor's managed-mode branch (registryAuthEnabled// verbatim) so the pre-existing tests below — which only flip// cfg.registryAuthEnabled, not this mock — still reach the same 200/400/409@@ -264,6 +269,20 @@ describe('GET /admin/registry/grants + granted-to-me', () => {const res = await request(makeApp()).get('/admin/registry/grants')expect(res.status).not.toBe(409)})++ it('self-hosted: 409 registry_url_not_configured when credentials remain but URL was removed', async () => {+ cfg.registryConnectionMode = 'self-hosted'+ cfg.registryAuthEnabled = false+ cfg.registryUrl = ''+ connDb.isRegistryAuthActive.mockResolvedValue(true)++ const res = await request(makeApp()).get('/admin/registry/grants')++ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'registry_url_not_configured' })+ expect(resolvePublishScope).not.toHaveBeenCalled()+ expect(listOrgGrants).not.toHaveBeenCalled()+ })})describe('DELETE /admin/registry/grants/:id', () => {@@ -360,27 +379,13 @@ describe('wire shape (real wrappers, stubbed registry fetch)', () => {vi.stubGlobal('fetch', fetchMock)return fetchMock}- // Auth-derived (Task 7): the route guard (resolveSelfServiceOrg) AND- // mintToken now BOTH derive their auth state from the same- // isRegistryAuthActive() accessor — mintToken no longer has its own- // independent process.env.CLERUM_REGISTRY_AUTH_ENABLED read to diverge from- // it. A single blanket mock value can no longer give the guard "on" (so the- // request isn't 409'd) and the wrapper's mintToken "off" (so it returns ''- // instead of throwing on missing creds) at the same time.- //- // Fixed by sequencing connDb.isRegistryAuthActive per call instead: the- // guard's call is the FIRST isRegistryAuthActive() call made while handling- // the request (resolveSelfServiceOrg calls it before anything else and- // returns/409s before the route ever reaches createOrgGrant/revokeOrgGrant —- // see routes/admin/registry.ts's resolveSelfServiceOrg), so- // mockResolvedValueOnce(true) satisfies exactly that call. Every call after- // it — i.e. mintToken's own internal call, reached via- // createOrgGrant/revokeOrgGrant → authedFetch → mintToken — falls through to- // the mockResolvedValue(false) default, so mintToken takes the auth-off- // branch and returns '' (no token round trip), with no real credentials- // configured anywhere in this file's mocked config.+ // Keep the route guard active while the real wrapper's managed token path is+ // auth-off. mintToken now resolves credentials through resolveMachineCreds+ // and reads the managed flag from config; it no longer performs a second+ // isRegistryAuthActive call that tests can sequence independently.function armGuardOnMintTokenOff(): void {- connDb.isRegistryAuthActive.mockReset().mockResolvedValueOnce(true).mockResolvedValue(false)+ cfg.registryAuthEnabled = false+ connDb.isRegistryAuthActive.mockReset().mockResolvedValue(true)}it('POST self_grant → 400 with {error:"self_grant"} verbatim', async () => {diff --git a/control-api/test/routes.adminRegistryKeys.test.ts b/control-api/test/routes.adminRegistryKeys.test.tsindex cd85073ab..c56e1e9b3 100644--- a/control-api/test/routes.adminRegistryKeys.test.ts+++ b/control-api/test/routes.adminRegistryKeys.test.ts@@ -43,7 +43,11 @@ vi.mock('../src/services/adminAuthService.js', () => ({ findAdminById: vi.fn() }// which branches on mode first. 'managed' makes it return registryAuthEnabled// verbatim, which is the behaviour these tests intend to exercise.const { cfg } = vi.hoisted(() => ({- cfg: { registryAuthEnabled: true, registryConnectionMode: 'managed' },+ cfg: {+ registryAuthEnabled: true,+ registryConnectionMode: 'managed',+ registryUrl: 'https://registry.evenfire.ai',+ },}))vi.mock('../src/config.js', () => ({ config: cfg }))// Narrow mock: registry.ts imports nothing else from registryConnectionDb, so@@ -75,6 +79,7 @@ beforeEach(() => {vi.clearAllMocks()cfg.registryAuthEnabled = truecfg.registryConnectionMode = 'managed'+ cfg.registryUrl = 'https://registry.evenfire.ai'// Default mirrors the real accessor's managed-mode branch (registryAuthEnabled// verbatim) so the pre-existing tests below — which only flip// cfg.registryAuthEnabled, not this mock — still reach the same 200/409 they did@@ -126,6 +131,20 @@ describe('GET /admin/registry/keys', () => {expect(res.body).toEqual({ org: 'acme', keys: [{ id: 'k1' }] })})+ it('self-hosted: 409 registry_url_not_configured when credentials remain but URL was removed', async () => {+ cfg.registryConnectionMode = 'self-hosted'+ cfg.registryAuthEnabled = false+ cfg.registryUrl = ''+ connDb.isRegistryAuthActive.mockResolvedValue(true)++ const res = await request(makeApp()).get('/admin/registry/keys')++ expect(res.status).toBe(409)+ expect(res.body).toEqual({ error: 'registry_url_not_configured' })+ expect(resolvePublishScope).not.toHaveBeenCalled()+ expect(listKeys).not.toHaveBeenCalled()+ })+// isRegistryAuthActive() can now reject (self-hosted reaches a raw pool.query// in getRegistryConnection with no try/catch of its own). The guard must catch// it and degrade to the same 502 used for a resolvePublishScope failure onediff --git a/control-api/test/routes.registryConnect.test.ts b/control-api/test/routes.registryConnect.test.tsindex c96e07635..4d1e870f1 100644--- a/control-api/test/routes.registryConnect.test.ts+++ b/control-api/test/routes.registryConnect.test.ts@@ -455,6 +455,12 @@ describe('registry connect flow', () => {expect(connDb.deleteConnection).toHaveBeenCalled()})+ it('DELETE still drops the local row when the registry URL was removed', async () => {+ cfg.registryUrl = ''+ await request(app()).delete('/admin/registry/connect').expect(204)+ 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@@ -568,10 +574,9 @@ describe('registry connect flow', () => {})describe('register — auto-claim (201)', () => {- // Parameterized over registryAuthEnabled: the beforeEach default is `true`,- // so a mutation replacing `authEnabled: config.registryAuthEnabled` with the- // literal `true` on the 201-connected response passes an authEnabled-only-true- // suite. The `false` case is the one that would catch it.+ // A successful claim has persisted a validated credential pair, so the+ // response is authEnabled:true regardless of the now-inert self-hosted env+ // flag. Parameterize over both values to pin that invariant.it.each([true, false])('claims immediately and reports connected (registryAuthEnabled=%s)',async registryAuthEnabled => {@@ -597,7 +602,7 @@ describe('register — auto-claim (201)', () => {.send({ requested_org_name: 'acme', contact_email: '[email protected]' }).expect(200)expect(res.body).toMatchObject({ state: 'connected', org: 'acme' })- expect(res.body.authEnabled).toBe(registryAuthEnabled)+ expect(res.body.authEnabled).toBe(true)// The claim call must actually carry the token the registry minted, and// be PoP-authenticated — otherwise every auto-approved self-hoster gets a// registry-side 401 and silently falls back to 202 connecting.@@ -609,13 +614,7 @@ 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 () => {+ it('does not re-read auth state after a successful auto-claim', async () => {connDb.getRegistryConnection.mockResolvedValue(null)connDb.markConnected.mockResolvedValue(true)connDb.isRegistryAuthActive.mockRejectedValue(new Error('pg blip'))@@ -630,8 +629,29 @@ describe('register — auto-claim (201)', () => {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')+ .expect(200)+ expect(res.body).toMatchObject({ state: 'connected', authEnabled: true })+ expect(connDb.isRegistryAuthActive).not.toHaveBeenCalled()+ })++ it('does not persist empty machine credentials from a malformed claim response', async () => {+ connDb.getRegistryConnection.mockResolvedValue(null)+ routeFetch({+ '/register': () =>+ json(+ { deployment_id: 'dep-1', key_id: 'kid-1', status: 'approved', claim_token: 'tok-abc' },+ 201+ ),+ '/claim': () => json({ client_id: '', client_secret: '', org: 'acme' }, 200),+ })++ 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('connecting')+ expect(connDb.markConnected).not.toHaveBeenCalled()})// The mocks return undefined, so `await x` and `void x` produce IDENTICAL@@ -954,11 +974,7 @@ 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 () => {+ it('does not re-read auth state after a successful recover', async () => {connDb.getRegistryConnection.mockResolvedValue({status: 'approved',deploymentId: 'dep-1',@@ -973,8 +989,9 @@ describe('POST recover', () => {'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')+ const res = await request(app()).post('/admin/registry/connect/recover').expect(200)+ expect(res.body).toMatchObject({ state: 'connected', authEnabled: true })+ expect(connDb.isRegistryAuthActive).not.toHaveBeenCalled()})// The route is rate-limited (each call rotates a one-time claim token atdiff --git a/control-api/test/services.registryClientMachineCreds.test.ts b/control-api/test/services.registryClientMachineCreds.test.tsindex e7f463d53..d4afeb48f 100644--- a/control-api/test/services.registryClientMachineCreds.test.ts+++ b/control-api/test/services.registryClientMachineCreds.test.ts@@ -13,14 +13,8 @@ const { cfg } = vi.hoisted(() => ({}))vi.mock('../src/config.js', () => ({ config: cfg }))-// Task 7: mintToken() now also calls isRegistryAuthActive() to derive-// authEnabled (replacing the CLERUM_REGISTRY_AUTH_ENABLED env read). This is-// a whole-module mock, so isRegistryAuthActive must be included here too —-// otherwise it is undefined on the mocked module and mintToken's `await-// isRegistryAuthActive()` throws a TypeError in both tests below.const resolver = vi.hoisted(() => ({resolveMachineCreds: vi.fn(),- isRegistryAuthActive: vi.fn(),}))vi.mock('../src/services/registryConnectionDb.js', () => resolver)@@ -29,6 +23,8 @@ afterEach(() => {vi.restoreAllMocks()cfg.registryConnectionMode = 'self-hosted'cfg.registryAuthEnabled = true+ delete process.env.CLERUM_REGISTRY_CLIENT_ID+ delete process.env.CLERUM_REGISTRY_CLIENT_SECRET})describe('mintToken — self-hosted sources creds from the DB row', () => {@@ -37,8 +33,6 @@ describe('mintToken — self-hosted sources creds from the DB row', () => {clientId: 'db-id',clientSecret: 'db-secret',})- // Mirrors the real self-hosted isRegistryAuthActive(): creds resolved → active.- resolver.isRegistryAuthActive.mockResolvedValue(true)const fetchSpy = vi.spyOn(globalThis, 'fetch').mockResolvedValue(@@ -54,8 +48,39 @@ describe('mintToken — self-hosted sources creds from the DB row', () => {it('returns "" (auth-off) when no creds are resolvable and auth is disabled', async () => {cfg.registryAuthEnabled = falseresolver.resolveMachineCreds.mockResolvedValue(null)- // Mirrors the real self-hosted isRegistryAuthActive(): no creds → inactive.- resolver.isRegistryAuthActive.mockResolvedValue(false)expect(await mintToken()).toBe('')})++ it('ignores stale env credentials and authenticates with the self-hosted DB identity', async () => {+ process.env.CLERUM_REGISTRY_CLIENT_ID = 'stale-managed-id'+ process.env.CLERUM_REGISTRY_CLIENT_SECRET = 'stale-managed-secret'+ resolver.resolveMachineCreds.mockResolvedValue({+ clientId: 'db-id',+ clientSecret: 'db-secret',+ })+ const fetchSpy = vi+ .spyOn(globalThis, 'fetch')+ .mockResolvedValue(+ new Response(JSON.stringify({ access_token: 'tok', expires_in: 300 }), { status: 200 })+ )++ await mintToken()++ const [, init] = fetchSpy.mock.calls[0]+ const auth = (init as RequestInit).headers as Record<string, string>+ expect(auth.Authorization).toBe(`Basic ${Buffer.from('db-id:db-secret').toString('base64')}`)+ expect(auth.Authorization).not.toContain(+ Buffer.from('stale-managed-id:stale-managed-secret').toString('base64')+ )+ })++ it('does not authenticate from stale env credentials before the DB connection exists', async () => {+ process.env.CLERUM_REGISTRY_CLIENT_ID = 'stale-managed-id'+ process.env.CLERUM_REGISTRY_CLIENT_SECRET = 'stale-managed-secret'+ resolver.resolveMachineCreds.mockResolvedValue(null)+ const fetchSpy = vi.spyOn(globalThis, 'fetch')++ await expect(mintToken()).resolves.toBe('')+ expect(fetchSpy).not.toHaveBeenCalled()+ })})diff --git a/control-ui/components/RegistryApiKeysPanel.tsx b/control-ui/components/RegistryApiKeysPanel.tsxindex 727357a27..f7e5a4bb0 100644--- a/control-ui/components/RegistryApiKeysPanel.tsx+++ b/control-ui/components/RegistryApiKeysPanel.tsx@@ -26,6 +26,7 @@ type View =| { kind: 'not-owner'; org?: string }| { kind: 'no-org' }| { kind: 'auth-disabled' }+ | { kind: 'url-not-configured' }| { kind: 'error' }const API_KEYS_COLUMNS: TableHeaderColumn[] = [@@ -78,6 +79,8 @@ export default function RegistryApiKeysPanel() {else if (status === 409 && code === 'no_org') setView({ kind: 'no-org' })else if (status === 409 && code === 'registry_auth_disabled')setView({ kind: 'auth-disabled' })+ else if (status === 409 && code === 'registry_url_not_configured')+ setView({ kind: 'url-not-configured' })else setView({ kind: 'error' })}}, [])@@ -173,6 +176,13 @@ export default function RegistryApiKeysPanel() {)}</p>) : null}+ {view.kind === 'url-not-configured' ? (+ <p className="cu-banner cu-banner--warn">+ This deployment still holds registry credentials, but <code>CLERUM_REGISTRY_URL</code>{' '}+ is not configured. Restore the registry URL or disconnect the stale connection before+ managing API keys.+ </p>+ ) : null}{view.kind === 'error' ? (<p className="cu-banner cu-banner--warn">Could not load API keys.{' '}diff --git a/control-ui/components/__tests__/RegistryApiKeysPanel.test.tsx b/control-ui/components/__tests__/RegistryApiKeysPanel.test.tsxindex 62f30ae48..7c6bf53dd 100644--- a/control-ui/components/__tests__/RegistryApiKeysPanel.test.tsx+++ b/control-ui/components/__tests__/RegistryApiKeysPanel.test.tsx@@ -103,6 +103,17 @@ describe('RegistryApiKeysPanel', () => {expect(screen.queryByRole('link', { name: /connect to evenfire registry/i })).toBeNull()})+ it('shows actionable configuration guidance when connected credentials remain without a URL', async () => {+ vi.mocked(api.listRegistryApiKeys).mockRejectedValue(+ Object.assign(new Error('x'), { status: 409, code: 'registry_url_not_configured' })+ )+ render(<RegistryApiKeysPanel />)++ expect(await screen.findByText(/still holds registry credentials/i)).toBeInTheDocument()+ expect(screen.getByText('CLERUM_REGISTRY_URL')).toBeInTheDocument()+ expect(screen.getByText(/disconnect the stale connection/i)).toBeInTheDocument()+ })+it('on create success, shows the reveal modal then refetches', async () => {vi.mocked(api.listRegistryApiKeys).mockResolvedValueOnce({ org: 'acme', keys: [] })diff --git a/control-ui/package-lock.json b/control-ui/package-lock.jsonindex 497cc2ce7..5a3548a48 100644--- a/control-ui/package-lock.json+++ b/control-ui/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-ui",- "version": "0.1.360",+ "version": "0.1.361","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-ui",- "version": "0.1.360",+ "version": "0.1.361","dependencies": {"@clerum/llm-providers": "file:../packages/llm-providers","@clerum/workflow-recipe-capability-policy": "file:../packages/workflow-recipe-capability-policy",diff --git a/control-ui/package.json b/control-ui/package.jsonindex eb9144e32..c6155ff42 100644--- a/control-ui/package.json+++ b/control-ui/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-ui",- "version": "0.1.360",+ "version": "0.1.361","private": true,"scripts": {"dev": "NEXT_IGNORE_INCORRECT_LOCKFILE=1 next dev",