Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-api): add an explicit recovery endpoint and keep connect GET read-only

Jose Ramirez4fdb01209656
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 4ad633e4d..ea1cac4a4 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.372",
+ "version": "0.1.373",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.372",
+ "version": "0.1.373",
"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.json
index 6f0a43cce..2329b163e 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.372",
+ "version": "0.1.373",
"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.ts
index 1918537af..5bdd0a2cd 100644
--- a/control-api/src/routes/admin/registryConnect.ts
+++ b/control-api/src/routes/admin/registryConnect.ts
@@ -139,18 +139,20 @@ export function createRegistryConnectRouter(): Router {
// Poll the registry for the deployment's current lifecycle status. Best-effort:
// a poll failure degrades to the locally-known pending state so GET never 500s
- // on a transient registry hiccup. Returns the registry status string or null.
+ // on a transient registry hiccup. Returns the parsed status/suspended/claimed
+ // triple, or null on any failure.
async function pollRegistryStatus(row: {
deploymentId: string
keyId: string
privateKeyPem: string
adminId: string
- }): Promise<string | null> {
+ }): Promise<{ status: string | null; suspended: boolean; claimed: boolean } | null> {
try {
const pop = signPop({ privateKeyPem: row.privateKeyPem, sub: row.adminId, kid: row.keyId })
const statusRes = await fetch(`${base()}/${row.deploymentId}/status`, {
method: 'GET',
headers: { DPoP: pop },
+ signal: AbortSignal.timeout(REGISTRY_FETCH_TIMEOUT_MS),
})
if (!statusRes.ok) {
rootLogger.warn(
@@ -159,8 +161,16 @@ export function createRegistryConnectRouter(): Router {
)
return null
}
- const parsed = (await statusRes.json()) as { status?: unknown }
- return typeof parsed.status === 'string' ? parsed.status : null
+ const parsed = (await statusRes.json()) as {
+ status?: unknown
+ suspended?: unknown
+ claimed?: unknown
+ }
+ return {
+ status: typeof parsed.status === 'string' ? parsed.status : null,
+ suspended: parsed.suspended === true,
+ claimed: parsed.claimed === true,
+ }
} catch (err) {
rootLogger.warn(
{ event: 'registry_connect_status_poll_error', err: (err as Error).message },
@@ -190,14 +200,42 @@ export function createRegistryConnectRouter(): Router {
})
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: config.registryAuthEnabled,
+ ...(recoveryError ? { recoveryError } : {}),
+ })
+ return
+ }
// Not yet connected — poll the registry so an operator approval (or
// rejection) is reflected before the user attempts to claim.
- const registryStatus = await pollRegistryStatus({
+ 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'
@@ -451,6 +489,124 @@ export function createRegistryConnectRouter(): Router {
}
})
+ // POST recover — finish an auto-approved connection whose inline claim failed.
+ // Explicit POST rather than a side effect of GET: GET has a second caller
+ // (RegistryCatalog) and is CSRF-reachable, and /:id/claim-token is unthrottled
+ // at the registry.
+ router.post(
+ '/admin/registry/connect/recover',
+ requireAuthForControlUI,
+ async (req, res, next) => {
+ try {
+ const ctx = await requireSelfHostedAdmin(req, res)
+ if (!ctx) return
+ const row = await getRegistryConnection()
+ if (!row || row.status !== 'approved') {
+ res.status(409).json({ error: 'not_recoverable' })
+ return
+ }
+ // Cheapest check first: a read tells us whether a rotate can possibly
+ // help, so a terminal state costs no mutation and no audit event.
+ const poll = await pollRegistryStatus({
+ deploymentId: row.deploymentId,
+ keyId: row.keyId,
+ privateKeyPem: row.privateKeyPem,
+ adminId: ctx.adminId,
+ })
+ if (poll?.claimed) {
+ res.status(409).json({ error: 'already_claimed' })
+ return
+ }
+ if (poll?.suspended) {
+ res.status(409).json({ error: 'deployment_suspended' })
+ return
+ }
+ if (poll?.status === 'rejected') {
+ res.status(409).json({ error: 'rejected' })
+ return
+ }
+ rootLogger.info(
+ { event: 'registry_connect_recover_attempted', status: 0 },
+ 'attempting auto-claim recovery'
+ )
+ let claimToken: string
+ try {
+ const pop = signPop({
+ privateKeyPem: row.privateKeyPem,
+ sub: ctx.adminId,
+ kid: row.keyId,
+ })
+ const rotRes = await fetch(`${base()}/${row.deploymentId}/claim-token`, {
+ method: 'POST',
+ headers: { DPoP: pop },
+ signal: AbortSignal.timeout(REGISTRY_FETCH_TIMEOUT_MS),
+ })
+ if (rotRes.status === 409) {
+ res.status(409).json({ error: 'already_claimed' })
+ return
+ }
+ if (!rotRes.ok) {
+ rootLogger.error(
+ { event: 'registry_connect_recover_rotate_failed', status: rotRes.status },
+ 'claim-token rotate failed'
+ )
+ res.status(202).json({ state: 'connecting', deploymentId: row.deploymentId })
+ return
+ }
+ const rotated = (await rotRes.json()) as { claim_token?: unknown }
+ if (typeof rotated.claim_token !== 'string') {
+ res.status(202).json({ state: 'connecting', deploymentId: row.deploymentId })
+ return
+ }
+ claimToken = rotated.claim_token
+ } catch {
+ // Never 500 on a registry hiccup — same guarantee the status poll makes.
+ res.status(202).json({ state: 'connecting', deploymentId: row.deploymentId })
+ return
+ }
+ const outcome = await redeemClaim({
+ deploymentId: row.deploymentId,
+ keyId: row.keyId,
+ privateKeyPem: row.privateKeyPem,
+ adminId: ctx.adminId,
+ claimToken,
+ })
+ switch (outcome.kind) {
+ case 'connected':
+ res.status(200).json({
+ state: 'connected',
+ org: outcome.org,
+ authEnabled: config.registryAuthEnabled,
+ })
+ return
+ // Terminal: the client is disabled (operator suspension). Retrying
+ // rotates forever against a deployment that was deliberately killed.
+ case 'client_unavailable':
+ rootLogger.error(
+ { event: 'registry_connect_recover_terminal', status: 0 },
+ 'recovery terminal: client unavailable'
+ )
+ res.status(409).json({ error: 'client_unavailable' })
+ return
+ case 'already_claimed':
+ res.status(409).json({ error: 'already_claimed' })
+ return
+ case 'superseded':
+ res.status(409).json({ error: 'connection_superseded' })
+ return
+ case 'expired':
+ res.status(409).json({ error: 'claim_expired' })
+ return
+ default:
+ res.status(202).json({ state: 'connecting', deploymentId: row.deploymentId })
+ return
+ }
+ } catch (err) {
+ next(err)
+ }
+ }
+ )
+
// DELETE — disconnect (drop the row).
router.delete('/admin/registry/connect', requireAuthForControlUI, async (req, res, next) => {
try {
diff --git a/control-api/test/routes.registryConnect.test.ts b/control-api/test/routes.registryConnect.test.ts
index a72df5e93..522b91e73 100644
--- a/control-api/test/routes.registryConnect.test.ts
+++ b/control-api/test/routes.registryConnect.test.ts
@@ -646,3 +646,165 @@ describe('register — guarded while a recovery is outstanding', () => {
expect(connDb.upsertPendingConnection).not.toHaveBeenCalled()
})
})
+
+describe('GET — local approved row', () => {
+ it('reports connecting and never rotates', { retry: 0 }, async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'approved',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ const spy = routeFetch({
+ '/status': () => json({ status: 'approved', suspended: false, claimed: false }, 200),
+ })
+ const res = await request(app()).get('/admin/registry/connect').expect(200)
+ expect(res.body.state).toBe('connecting')
+ expect(spy.mock.calls.map(c => String(c[0])).some(u => u.includes('claim-token'))).toBe(false)
+ })
+
+ it('surfaces a terminal recoveryError when already claimed', async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'approved',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ routeFetch({
+ '/status': () => json({ status: 'approved', suspended: false, claimed: true }, 200),
+ })
+ const res = await request(app()).get('/admin/registry/connect').expect(200)
+ expect(res.body).toMatchObject({ state: 'connecting', recoveryError: 'already_claimed' })
+ })
+})
+
+// THE operator-flow regression proof. A flag-off registration stays locally
+// 'pending' until a human pastes a token; rotating would silently invalidate
+// the token an operator delivered out of band.
+describe('GET — local pending row is never rotated', () => {
+ it(
+ 'reports approved from the registry poll without touching claim-token',
+ { retry: 0 },
+ async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'pending',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ const spy = routeFetch({
+ '/status': () => json({ status: 'approved', suspended: false, claimed: false }, 200),
+ })
+ const res = await request(app()).get('/admin/registry/connect').expect(200)
+ expect(res.body.state).toBe('approved')
+ expect(spy.mock.calls.map(c => String(c[0])).some(u => u.includes('claim-token'))).toBe(false)
+ expect(connDb.markConnected).not.toHaveBeenCalled()
+ }
+ )
+})
+
+describe('POST recover', () => {
+ it('rotates then claims and reports connected', 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', authEnabled: true })
+ })
+
+ it('refuses when the local row is pending', async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'pending',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ const res = await request(app()).post('/admin/registry/connect/recover').expect(409)
+ expect(res.body.error).toBe('not_recoverable')
+ })
+
+ it('reports already_claimed WITHOUT spending a rotate', async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'approved',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ const spy = routeFetch({
+ '/status': () => json({ status: 'approved', suspended: false, claimed: true }, 200),
+ })
+ const res = await request(app()).post('/admin/registry/connect/recover').expect(409)
+ expect(res.body.error).toBe('already_claimed')
+ expect(spy.mock.calls.map(c => String(c[0])).some(u => u.includes('claim-token'))).toBe(false)
+ })
+
+ it('reports deployment_suspended without rotating', async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'approved',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ routeFetch({
+ '/status': () => json({ status: 'approved', suspended: true, claimed: false }, 200),
+ })
+ const res = await request(app()).post('/admin/registry/connect/recover').expect(409)
+ expect(res.body.error).toBe('deployment_suspended')
+ })
+
+ // client_unavailable means the registry client is disabled (operator
+ // suspension). Retrying rotates forever against a deployment an operator
+ // deliberately killed, so it must be terminal.
+ it('treats client_unavailable as terminal', async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'approved',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ routeFetch({
+ '/status': () => json({ status: 'approved', suspended: false, claimed: false }, 200),
+ 'claim-token': () => json({ claim_token: 'tok-new' }, 200),
+ '/claim': () => json({ error: 'client_unavailable' }, 409),
+ })
+ const res = await request(app()).post('/admin/registry/connect/recover').expect(409)
+ expect(res.body.error).toBe('client_unavailable')
+ })
+
+ // GET never 500s on a registry hiccup (registryConnect.ts:50-52); recovery
+ // must honour the same guarantee.
+ it('degrades to 202 connecting when the rotate fetch throws', async () => {
+ connDb.getRegistryConnection.mockResolvedValue({
+ status: 'approved',
+ deploymentId: 'dep-1',
+ keyId: 'kid-1',
+ privateKeyPem: pkForTest(),
+ requestedOrgName: 'acme',
+ })
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async input => {
+ if (String(input).includes('/status')) {
+ return json({ status: 'approved', suspended: false, claimed: false }, 200)
+ }
+ throw new Error('ECONNREFUSED')
+ })
+ const res = await request(app()).post('/admin/registry/connect/recover').expect(202)
+ expect(res.body.state).toBe('connecting')
+ })
+})