Skip to content

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

TypeScript

refactor(control-api): skip the mcp-server uninstall on a missing CR, never delete unfenced (R3-H5)

Diego Zacariasc60a4d5ca230
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 1fea030c8..33262cfd4 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.669",
+ "version": "0.1.670",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.669",
+ "version": "0.1.670",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index afd6d4008..df4fc8e1f 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.669",
+ "version": "0.1.670",
"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/resources.ts b/control-api/src/routes/admin/resources.ts
index a888a0397..07f385a45 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -13,13 +13,8 @@ import { validateCommunicationChannelSpec } from '../../http/validateCommunicati
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
-import {
- captureMcpServerSecrets,
- deleteCapturedSecrets,
- uninstallMcpServer,
-} from '../../oauth/mcpServerUninstall.js'
+import { uninstallMcpServer } from '../../oauth/mcpServerUninstall.js'
import { rootLogger } from '../../observability/logger.js'
-import { stripServerFromContexts } from '../../services/contextAllowlist.js'
import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'
import {
K8sConflictError,
@@ -1104,20 +1099,15 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
})
return
}
- // The CR read found nothing, so there is no uid to fence an OAuth teardown by:
- // only the name-addressed K8s cleanup runs, and OAuth state is left alone.
- const secretCaptures = await captureMcpServerSecrets(gateway, name, ns, log)
- const deleted = await gateway.deleteResource(plural, name, ns)
- await deleteCapturedSecrets(gateway, secretCaptures, ns, log)
- try {
- await stripServerFromContexts(gateway, resourceNamespace('contexts'), name, contextName =>
- log.info({ serverName: name, contextName }, 'Removed MCP server from Context allowlist')
- )
- } catch (err) {
- log.error({ serverName: name, err }, 'Failed to clean up Context allowlists')
+ if (outcome.status === 'not_found') {
+ // Every cleanup runs before the CR delete, so a missing CR means "already clean"
+ // or "deleted out of band". Cleaning by name here would have no uid to fence
+ // by: it could delete a CR a reinstall recreated after this read, or the Secret
+ // a pre-registered reinstall creates before its CR.
+ throw new K8sNotFoundError(`mcpservers/${name} not found`)
}
- res.status(200).json(deleted)
- return
+ const unhandled: never = outcome
+ throw new Error(`unhandled mcp-server uninstall outcome: ${JSON.stringify(unhandled)}`)
}
// CommunicationChannel: read the credentialsSecretRef name FIRST (we
diff --git a/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts b/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts
index 0356f3584..b615f10dd 100644
--- a/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts
+++ b/control-api/test/routes.mcpServerUninstall.repairRequired.test.ts
@@ -24,6 +24,7 @@ vi.mock('../src/db.js', async importActual => {
const { config } = await import('../src/config.js')
const { createAdminResourcesRouter } = await import('../src/routes/admin/resources.js')
+const { clerumErrorHandler } = await import('../src/http/errorHandler.js')
const NS = config.mcpServersNamespace
const SERVER = 'srv'
@@ -169,3 +170,56 @@ describe('DELETE /admin/mcp-servers/:name — cleanup before delete, 503 repair_
await expect(gw.getSecret(CREDENTIALS, NS)).rejects.toThrow()
})
})
+
+describe('DELETE /admin/mcp-servers/:name — a missing CR touches nothing (R3-H5a)', () => {
+ // A reinstall recreates the CR (and its Secrets, which a pre-registered install writes
+ // before the CR) right after the uninstall's read found nothing. A name-addressed
+ // cleanup at that point would tear down the NEW installation.
+ it('answers 404 and leaves a CR, Secrets and allowlist recreated after the read intact', async () => {
+ const gw = new MockGateway(NS)
+ await gw.createResource(
+ 'contexts',
+ { metadata: { name: 'ctx-a' }, spec: { contextId: 'ctx-a', mcpServers: [SERVER] } },
+ 'contexts-ns'
+ )
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminResourcesRouter(gw as unknown as K8sGateway))
+ app.use(clerumErrorHandler)
+
+ let recreatedUid: string | undefined
+ const realGet = MockGateway.prototype.getResource
+ vi.spyOn(gw, 'getResource').mockImplementation(async (plural, name, ns) => {
+ try {
+ return await realGet.call(gw, plural, name, ns)
+ } catch (err) {
+ if (plural === 'mcpservers' && name === SERVER && recreatedUid === undefined) {
+ gw.seedSecret(CREDENTIALS, NS, { stringData: { TOKEN: 'new' } })
+ gw.seedSecret(`${SERVER}-oauth-client`, NS, {
+ labels: { 'clerum.io/managed-by': 'control-api' },
+ stringData: { client_id: 'id', client_secret: 'sec' },
+ })
+ const cr = (await gw.createResource(
+ 'mcpservers',
+ { metadata: { name: SERVER }, spec: { image: 'reinstall' } },
+ NS
+ )) as { metadata: { uid: string } }
+ recreatedUid = cr.metadata.uid
+ }
+ throw err
+ }
+ })
+
+ const res = await request(app).delete(`/admin/mcp-servers/${SERVER}`)
+
+ expect(res.status).toBe(404)
+ expect(res.body).toMatchObject({ error: `mcpservers/${SERVER} not found` })
+ await expect(realGet.call(gw, 'mcpservers', SERVER, NS)).resolves.toMatchObject({
+ metadata: { uid: recreatedUid },
+ })
+ await expect(gw.getSecret(CREDENTIALS, NS)).resolves.toBeTruthy()
+ await expect(gw.getSecret(`${SERVER}-oauth-client`, NS)).resolves.toBeTruthy()
+ expect(await allowlist(gw)).toEqual([SERVER])
+ expect(grantsPurges()).toBe(0)
+ })
+})
diff --git a/control-api/test/routes.resources.contextDisplayNamePruning.test.ts b/control-api/test/routes.resources.contextDisplayNamePruning.test.ts
index 50ac468e4..b9819c526 100644
--- a/control-api/test/routes.resources.contextDisplayNamePruning.test.ts
+++ b/control-api/test/routes.resources.contextDisplayNamePruning.test.ts
@@ -1,9 +1,17 @@
import { describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
-import { config } from '../src/config.js'
-import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'
-import { ResourceService } from '../src/services/resourceService.js'
+
+// The McpServer uninstall tears OAuth state down before deleting the CR and answers
+// 503 when that fails, so it needs a DB that answers (empty: nothing to tear down).
+vi.mock('../src/db.js', async importActual => {
+ const actual = await importActual<typeof import('../src/db.js')>()
+ return { ...actual, pool: { query: vi.fn(async () => ({ rows: [], rowCount: 0 })) } }
+})
+
+const { config } = await import('../src/config.js')
+const { createAdminResourcesRouter } = await import('../src/routes/admin/resources.js')
+const { ResourceService } = await import('../src/services/resourceService.js')
// R1-M6 — deploy-order guard against silent pruning of the additive context
// `spec.displayName` field (PR #304).
@@ -25,6 +33,7 @@ function realServiceGateway(opts: { pruneDisplayName: boolean }): {
deleteResource: ResourceService['deleteResource']
listResource: ResourceService['listResource']
deleteSecret: ReturnType<typeof vi.fn>
+ getSecret: ReturnType<typeof vi.fn>
}
store: Map<string, Record<string, unknown>>
deleteNamespacedCustomObject: ReturnType<typeof vi.fn>
@@ -106,6 +115,10 @@ function realServiceGateway(opts: { pruneDisplayName: boolean }): {
// handler invokes it for the `<name>-credentials` secret. It is orthogonal to
// the allowlist-pruning path under test, so a no-op spy suffices.
const deleteSecret = vi.fn(async () => ({ deleted: true }))
+ // The uninstall snapshots the server's Secrets before cleaning up; none exist here.
+ const getSecret = vi.fn(async (name: string) => {
+ throw Object.assign(new Error(`secrets "${name}" not found`), { code: 404 })
+ })
const gateway = {
getResource: svc.getResource.bind(svc),
updateResource: svc.updateResource.bind(svc),
@@ -113,6 +126,7 @@ function realServiceGateway(opts: { pruneDisplayName: boolean }): {
deleteResource: svc.deleteResource.bind(svc),
listResource: svc.listResource.bind(svc),
deleteSecret,
+ getSecret,
}
return { gateway, store, deleteNamespacedCustomObject, deleteSecret }
}
@@ -230,6 +244,13 @@ describe('routes/resources — context spec.displayName deploy-order guard (R1-M
},
config.contextsNamespace
)
+ // A missing McpServer answers 404 without touching any Context, so the server
+ // under uninstall must exist.
+ await gateway.createResource(
+ 'mcpservers',
+ { metadata: { name: 'srv-target' }, spec: {} },
+ config.mcpServersNamespace
+ )
const app = makeApp(gateway)
await request(app).delete('/admin/mcp-servers/srv-target').expect(200)
diff --git a/control-api/test/routes.resources.oauthClientSecretOwnership.test.ts b/control-api/test/routes.resources.oauthClientSecretOwnership.test.ts
index 2434a5cc9..7835228a8 100644
--- a/control-api/test/routes.resources.oauthClientSecretOwnership.test.ts
+++ b/control-api/test/routes.resources.oauthClientSecretOwnership.test.ts
@@ -1,10 +1,18 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import express from 'express'
import request from 'supertest'
-import { config } from '../src/config.js'
-import { createAdminResourcesRouter } from '../src/routes/admin/resources.js'
import { MockGateway } from './mockGateway.js'
+// The uninstall tears OAuth state down before deleting the CR and answers 503 when
+// that fails, so it needs a DB that answers (empty: nothing to tear down).
+vi.mock('../src/db.js', async importActual => {
+ const actual = await importActual<typeof import('../src/db.js')>()
+ return { ...actual, pool: { query: vi.fn(async () => ({ rows: [], rowCount: 0 })) } }
+})
+
+const { config } = await import('../src/config.js')
+const { createAdminResourcesRouter } = await import('../src/routes/admin/resources.js')
+
// R3-H6: the McpServer uninstall path (`DELETE /admin/mcp-servers/:name`) cleans up
// the derived-name `${name}-oauth-client` Secret. That name is not exclusive to
// control-api — OAuth reference mode lets an operator point clientIdRef at any
@@ -17,6 +25,18 @@ describe('DELETE /admin/mcp-servers/:name — oauth-client Secret ownership guar
let prevMcpServersNs: string
let prevContextsNs: string
+ // The Secret cleanup only runs for a live CR: a missing one answers 404 and touches
+ // nothing, so every case installs the server first.
+ async function gatewayWithServer(): Promise<MockGateway> {
+ const gw = new MockGateway('mcpservers-ns')
+ await gw.createResource(
+ 'mcpservers',
+ { metadata: { name: 'my-gmail' }, spec: {} },
+ 'mcpservers-ns'
+ )
+ return gw
+ }
+
function makeApp(gateway: MockGateway) {
const app = express()
app.use(express.json())
@@ -38,7 +58,7 @@ describe('DELETE /admin/mcp-servers/:name — oauth-client Secret ownership guar
})
it('does NOT delete a foreign, unlabeled oauth-client Secret (operator-owned collision)', async () => {
- const gw = new MockGateway('mcpservers-ns')
+ const gw = await gatewayWithServer()
// Fixture from the real producer (MockGateway.getSecret): an operator Secret
// that happens to carry the derived name and NO managed-by label.
gw.seedSecret(OAUTH_SECRET, 'mcpservers-ns', {
@@ -58,7 +78,7 @@ describe('DELETE /admin/mcp-servers/:name — oauth-client Secret ownership guar
})
it('does NOT delete an oauth-client Secret managed by another controller', async () => {
- const gw = new MockGateway('mcpservers-ns')
+ const gw = await gatewayWithServer()
gw.seedSecret(OAUTH_SECRET, 'mcpservers-ns', {
labels: { 'clerum.io/managed-by': 'Helm' },
stringData: { client_id: 'id', client_secret: 'sec' },
@@ -76,7 +96,7 @@ describe('DELETE /admin/mcp-servers/:name — oauth-client Secret ownership guar
})
it('DOES delete a control-api-managed oauth-client Secret', async () => {
- const gw = new MockGateway('mcpservers-ns')
+ const gw = await gatewayWithServer()
gw.seedSecret(OAUTH_SECRET, 'mcpservers-ns', {
labels: { 'clerum.io/managed-by': 'control-api' },
stringData: { client_id: 'id', client_secret: 'sec' },