Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
fix(control-api): require managed-by ownership before deleting the oauth-client secret (R3-H6)
Diego Zacarias7971e5717b99
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 4b100e852..ef0764a9f 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.659",+ "version": "0.1.660","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.659",+ "version": "0.1.660","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.jsonindex 84b5488db..e2574651f 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.659",+ "version": "0.1.660","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/registry.ts b/control-api/src/routes/admin/registry.tsindex 52ec611d3..b754cae78 100644--- a/control-api/src/routes/admin/registry.ts+++ b/control-api/src/routes/admin/registry.ts@@ -64,7 +64,11 @@ import {invalidSecretTypeReason,} from '../../services/secretConstraints.js'import { findSecretReferenceState } from '../../services/secretReferenceService.js'-import { SecretSnapshot, toSecretSnapshot } from '../../services/secretRepository.js'+import {+ SecretSnapshot,+ isControlApiManagedSecret,+ toSecretSnapshot,+} from '../../services/secretRepository.js'import {validateWorkflowRecipeEgressPreflight,validateWorkflowRecipeLimits,@@ -4150,15 +4154,26 @@ export function createAdminRegistryRouter(gateway?: K8sGateway): Router {}// Delete the managed OAuth client Secret (S1-U3, Step 3b). The name is- // DERIVED (`${serverName}-oauth-client`), so it can only exist if this- // server was installed in OAuth managed mode; reference mode points the- // clientIdRef/clientSecretRef at an operator-named Secret and never- // creates this name. Fenced to the pre-CR-delete snapshot, same as- // `-credentials` above: a no-op when the server had no OAuth block or- // used reference mode, and a delete bound to the exact UID/RV so a- // concurrent reinstall's same-name Secret is never razed.+ // DERIVED (`${serverName}-oauth-client`), but reference mode accepts+ // arbitrary clientIdRef/clientSecretRef names, so an operator-owned+ // Secret can carry this exact name by coincidence. UID/RV fencing proves+ // same-object, not same-owner, so confirm control-api's install saga+ // created it via the managed-by label before razing it; otherwise skip+ // and warn. Fenced to the pre-CR-delete snapshot, a no-op when the+ // server had no OAuth block or used reference mode with a different name.try {- if (oauthClientSecretSnapshot) {+ if (+ oauthClientSecretSnapshot &&+ !isControlApiManagedSecret(oauthClientSecretSnapshot)+ ) {+ log.warn(+ {+ secretName: oauthClientSecretSnapshot.name,+ namespace: oauthClientSecretSnapshot.namespace,+ },+ 'Skipped OAuth client Secret cleanup: not managed by control-api'+ )+ } else if (oauthClientSecretSnapshot) {await gateway.deleteSecret(oauthClientSecretSnapshot.name,oauthClientSecretSnapshot.namespace,diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.tsindex 2ee6b622c..5213a0071 100644--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@ -25,6 +25,7 @@ import {} from '../../services/resourceService.js'import { secretKeyNames } from '../../services/secretKeyNames.js'import {+ isControlApiManagedSecret,isRecipeOwnedSecret,secretIdentityPreconditions,} from '../../services/secretRepository.js'@@ -1109,10 +1110,18 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {// longer exists. Every cleanup below is bound to the snapshot taken here.// Same reasoning, and same shape, as the registry uninstall path.const captureSecretForCleanup = async (- secretName: string+ secretName: string,+ { requireManagedOwnership = false }: { requireManagedOwnership?: boolean } = {}): Promise<| { status: 'ready'; precondition: SecretPreconditions }- | { status: 'absent' | 'recipe-owned' | 'identity-unavailable' | 'read-failed' }+ | {+ status:+ | 'absent'+ | 'recipe-owned'+ | 'not-managed'+ | 'identity-unavailable'+ | 'read-failed'+ }> => {let raw: unknowntry {@@ -1135,6 +1144,13 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {// route refuses them with 409; deleting one here would route around// that guard.if (isRecipeOwnedSecret(raw)) return { status: 'recipe-owned' }+ // Derived-name Secrets (`${name}-oauth-client`) share a name with any+ // operator-owned Secret referenced in OAuth reference mode. Only delete+ // when the managed-by label proves control-api's install saga created it;+ // UID/RV fencing guarantees same-object, not same-owner.+ if (requireManagedOwnership && !isControlApiManagedSecret(raw)) {+ return { status: 'not-managed' }+ }const precondition = secretIdentityPreconditions(raw)if (!precondition) return { status: 'identity-unavailable' }return { status: 'ready', precondition }@@ -1156,7 +1172,11 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {// exists to prevent). 'absent' (404) is the norm for non-pre-registered servers.const mcpOAuthClientSecretName = `${name}-oauth-client`const mcpOAuthClientSecretCleanup =- plural === 'mcpservers' ? await captureSecretForCleanup(mcpOAuthClientSecretName) : null+ plural === 'mcpservers'+ ? await captureSecretForCleanup(mcpOAuthClientSecretName, {+ requireManagedOwnership: true,+ })+ : nullconst deleted = await gateway.deleteResource(plural, name, ns)diff --git a/control-api/src/services/secretRepository.ts b/control-api/src/services/secretRepository.tsindex 0ddb59e44..daf8518ac 100644--- a/control-api/src/services/secretRepository.ts+++ b/control-api/src/services/secretRepository.ts@@ -7,6 +7,12 @@ import type { SecretPreconditions } from '../types.js'export const RECIPE_SECRET_LABEL_KEY = 'clerum.io/recipe-secret'export const RECIPE_SECRET_LABEL_VALUE = 'true'+// The ownership marker the install saga stamps on every Secret control-api+// creates (see remoteMcp.ts `managedLabels`). It lives here so every route that+// may delete a derived-name Secret reads the SAME constant and cannot drift.+export const MANAGED_BY_LABEL_KEY = 'clerum.io/managed-by'+export const MANAGED_BY_CONTROL_API = 'control-api'+/** True when the Secret is owned by a WorkflowRecipe and must not be deleted by other routes. */export function isRecipeOwnedSecret(raw: unknown): boolean {const labels = (raw as { metadata?: { labels?: Record<string, string> } } | undefined)?.metadata@@ -14,6 +20,25 @@ export function isRecipeOwnedSecret(raw: unknown): boolean {return labels?.[RECIPE_SECRET_LABEL_KEY] === RECIPE_SECRET_LABEL_VALUE}+/**+ * True when the Secret carries proof that control-api's install saga created it+ * (`clerum.io/managed-by: control-api`). A derived-name Secret like+ * `${name}-oauth-client` can COLLIDE with an operator-owned Secret of the same+ * name (reference mode accepts arbitrary `clientIdRef`/`clientSecretRef` names),+ * so a name-addressed uninstall delete must confirm ownership before razing it —+ * UID/RV fencing proves same-object, not same-owner. Reads labels from either the+ * flat {@link SecretSnapshot} or the raw Kubernetes object, mirroring+ * {@link secretIdentityPreconditions}, so both delete paths share one predicate.+ */+export function isControlApiManagedSecret(raw: unknown): boolean {+ const value = (raw ?? {}) as {+ labels?: Record<string, string>+ metadata?: { labels?: Record<string, string> }+ }+ const labels = value.labels ?? value.metadata?.labels+ return labels?.[MANAGED_BY_LABEL_KEY] === MANAGED_BY_CONTROL_API+}+/** The subset of a Kubernetes Secret that callers are allowed to observe. */export interface SecretResource {metadata?: {diff --git a/control-api/test/routes.registryInstall.oauth.test.ts b/control-api/test/routes.registryInstall.oauth.test.tsindex e7818091d..b92ac6bfe 100644--- a/control-api/test/routes.registryInstall.oauth.test.ts+++ b/control-api/test/routes.registryInstall.oauth.test.ts@@ -525,6 +525,9 @@ describe('POST /admin/registry/install — OAuth (S1-U2/U3)', () => {},})gw.seedSecret('my-gmail-oauth-client', 'mcp-server', {+ // The install saga always stamps this ownership label (registry.ts+ // `registryLabels` / remoteMcp.ts `managedLabels`); uninstall now requires it.+ labels: { 'clerum.io/managed-by': 'control-api' },stringData: { client_id: 'id', client_secret: 'sec' },})const app = makeApp(gw)@@ -557,6 +560,9 @@ describe('POST /admin/registry/install — OAuth (S1-U2/U3)', () => {})// The Secret whose identity the uninstall captures before deleting the CR.gw.seedSecret('my-gmail-oauth-client', 'mcp-server', {+ // The install saga always stamps this ownership label (registry.ts+ // `registryLabels` / remoteMcp.ts `managedLabels`); uninstall now requires it.+ labels: { 'clerum.io/managed-by': 'control-api' },stringData: { client_id: 'id', client_secret: 'sec' },})// Identity derived from the real producer (MockGateway.getSecret), not hand-built.@@ -570,6 +576,9 @@ describe('POST /admin/registry/install — OAuth (S1-U2/U3)', () => {const result = await origDeleteResource(plural, name, ns, precond)if (plural === 'mcpservers' && name === 'my-gmail') {gw.seedSecret('my-gmail-oauth-client', 'mcp-server', {+ // A concurrent reinstall's Secret is also control-api-managed; the UID+ // fence (not the ownership label) is what must protect it here.+ labels: { 'clerum.io/managed-by': 'control-api' },uid: 'uid-reinstall-different-owner',stringData: { client_id: 'new', client_secret: 'new' },})@@ -876,6 +885,8 @@ describe('generic carril install (S3-B4)', () => {},})gw.seedSecret('my-idp-oauth-client', 'mcp-server', {+ // The install saga always stamps this ownership label; uninstall requires it.+ labels: { 'clerum.io/managed-by': 'control-api' },stringData: { client_id: 'id', client_secret: 'sec' },})const res = await request(makeApp(gw)).delete('/admin/registry/uninstall/my-idp').expect(200)@@ -900,3 +911,76 @@ describe('generic carril install (S3-B4)', () => {await expect(gw.getResource('mcpservers', 'my-idp', 'mcp-server')).rejects.toThrow()})})++// R3-H6: `${name}-oauth-client` is a DERIVED name, but OAuth reference mode lets an+// operator point clientIdRef/clientSecretRef at any same-named Secret it owns.+// UID/RV fencing proves same-object, not same-owner, so uninstall must confirm the+// `clerum.io/managed-by: control-api` ownership label before razing the Secret.+describe('DELETE /admin/registry/uninstall — oauth-client Secret ownership guard (R3-H6)', () => {+ function seedServer(gw: MockGateway) {+ gw.createResource('mcpservers', {+ metadata: { name: 'my-gmail' },+ spec: {+ image: 'clerum/gmail-mcp:1.0.0',+ auth: { type: 'oauth' },+ oauth: {+ id: 'my-gmail',+ provider: 'google',+ clientIdRef: { name: 'my-gmail-oauth-client', key: 'client_id' },+ clientSecretRef: { name: 'my-gmail-oauth-client', key: 'client_secret' },+ },+ },+ })+ }++ it('does NOT delete a foreign, unlabeled oauth-client Secret (operator-owned collision)', async () => {+ const gw = new MockGateway('mcp-server')+ seedServer(gw)+ // Fixture derived from the real producer (MockGateway.getSecret): an+ // operator-created Secret that happens to carry the derived name and NO+ // managed-by label.+ gw.seedSecret('my-gmail-oauth-client', 'mcp-server', {+ stringData: { client_id: 'id', client_secret: 'sec' },+ })+ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ const res = await request(makeApp(gw)).delete('/admin/registry/uninstall/my-gmail').expect(200)++ // Observable outcome: the foreign Secret is neither reported deleted nor removed.+ expect(res.body.deleted).not.toContain('Secret/my-gmail-oauth-client')+ await expect(gw.getSecret('my-gmail-oauth-client', 'mcp-server')).resolves.toBeTruthy()+ expect(deleteSecretSpy).not.toHaveBeenCalledWith(+ 'my-gmail-oauth-client',+ 'mcp-server',+ expect.anything()+ )+ })++ it('does NOT delete an oauth-client Secret managed by another controller', async () => {+ const gw = new MockGateway('mcp-server')+ seedServer(gw)+ gw.seedSecret('my-gmail-oauth-client', 'mcp-server', {+ labels: { 'clerum.io/managed-by': 'Helm' },+ stringData: { client_id: 'id', client_secret: 'sec' },+ })++ const res = await request(makeApp(gw)).delete('/admin/registry/uninstall/my-gmail').expect(200)++ expect(res.body.deleted).not.toContain('Secret/my-gmail-oauth-client')+ await expect(gw.getSecret('my-gmail-oauth-client', 'mcp-server')).resolves.toBeTruthy()+ })++ it('DOES delete a control-api-managed oauth-client Secret', async () => {+ const gw = new MockGateway('mcp-server')+ seedServer(gw)+ gw.seedSecret('my-gmail-oauth-client', 'mcp-server', {+ labels: { 'clerum.io/managed-by': 'control-api' },+ stringData: { client_id: 'id', client_secret: 'sec' },+ })++ const res = await request(makeApp(gw)).delete('/admin/registry/uninstall/my-gmail').expect(200)++ expect(res.body.deleted).toContain('Secret/my-gmail-oauth-client')+ await expect(gw.getSecret('my-gmail-oauth-client', 'mcp-server')).rejects.toThrow()+ })+})diff --git a/control-api/test/routes.resources.oauthClientSecretOwnership.test.ts b/control-api/test/routes.resources.oauthClientSecretOwnership.test.tsnew file mode 100644index 000000000..2434a5cc9--- /dev/null+++ b/control-api/test/routes.resources.oauthClientSecretOwnership.test.ts@@ -0,0 +1,92 @@+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'++// 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+// same-named Secret it owns. UID/RV fencing proves same-object, not same-owner, so+// the cascade delete must confirm the `clerum.io/managed-by: control-api` label+// (stamped by the install saga) before razing the Secret.+describe('DELETE /admin/mcp-servers/:name — oauth-client Secret ownership guard (R3-H6)', () => {+ const OAUTH_SECRET = 'my-gmail-oauth-client'++ let prevMcpServersNs: string+ let prevContextsNs: string++ function makeApp(gateway: MockGateway) {+ const app = express()+ app.use(express.json())+ app.use(createAdminResourcesRouter(gateway as never))+ return app+ }++ beforeEach(() => {+ prevMcpServersNs = config.mcpServersNamespace+ prevContextsNs = config.contextsNamespace+ config.mcpServersNamespace = 'mcpservers-ns'+ config.contextsNamespace = 'contexts-ns'+ })++ afterEach(() => {+ config.mcpServersNamespace = prevMcpServersNs+ config.contextsNamespace = prevContextsNs+ vi.restoreAllMocks()+ })++ it('does NOT delete a foreign, unlabeled oauth-client Secret (operator-owned collision)', async () => {+ const gw = new MockGateway('mcpservers-ns')+ // 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', {+ stringData: { client_id: 'id', client_secret: 'sec' },+ })+ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ await request(makeApp(gw)).delete('/admin/mcp-servers/my-gmail').expect(200)++ // Observable outcome: the foreign Secret survives and no delete was addressed to it.+ await expect(gw.getSecret(OAUTH_SECRET, 'mcpservers-ns')).resolves.toBeTruthy()+ expect(deleteSecretSpy).not.toHaveBeenCalledWith(+ OAUTH_SECRET,+ 'mcpservers-ns',+ expect.anything()+ )+ })++ it('does NOT delete an oauth-client Secret managed by another controller', async () => {+ const gw = new MockGateway('mcpservers-ns')+ gw.seedSecret(OAUTH_SECRET, 'mcpservers-ns', {+ labels: { 'clerum.io/managed-by': 'Helm' },+ stringData: { client_id: 'id', client_secret: 'sec' },+ })+ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ await request(makeApp(gw)).delete('/admin/mcp-servers/my-gmail').expect(200)++ await expect(gw.getSecret(OAUTH_SECRET, 'mcpservers-ns')).resolves.toBeTruthy()+ expect(deleteSecretSpy).not.toHaveBeenCalledWith(+ OAUTH_SECRET,+ 'mcpservers-ns',+ expect.anything()+ )+ })++ it('DOES delete a control-api-managed oauth-client Secret', async () => {+ const gw = new MockGateway('mcpservers-ns')+ gw.seedSecret(OAUTH_SECRET, 'mcpservers-ns', {+ labels: { 'clerum.io/managed-by': 'control-api' },+ stringData: { client_id: 'id', client_secret: 'sec' },+ })+ const deleteSecretSpy = vi.spyOn(gw, 'deleteSecret')++ await request(makeApp(gw)).delete('/admin/mcp-servers/my-gmail').expect(200)++ // Observable outcome: the managed Secret is gone.+ await expect(gw.getSecret(OAUTH_SECRET, 'mcpservers-ns')).rejects.toThrow()+ expect(deleteSecretSpy).toHaveBeenCalledWith(OAUTH_SECRET, 'mcpservers-ns', expect.anything())+ })+})