Skip to content

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

TypeScript

fix(oauth): purge server oauth_grants on CR uninstall (H-3)

Diego Zacarias2680eade5c83
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 7f6ce4328..343c05cc9 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.595",
+ "version": "0.1.596",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.595",
+ "version": "0.1.596",
"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 860e1b21b..15acddefd 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.595",
+ "version": "0.1.596",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/oauth/__tests__/deleteOAuthGrantsForServer.test.ts b/control-api/src/oauth/__tests__/deleteOAuthGrantsForServer.test.ts
new file mode 100644
index 000000000..1031a52c1
--- /dev/null
+++ b/control-api/src/oauth/__tests__/deleteOAuthGrantsForServer.test.ts
@@ -0,0 +1,58 @@
+import { describe, expect, it, vi } from 'vitest'
+import type { DbClient } from '../../db.js'
+import { deleteOAuthGrantsForServer } from '../store.js'
+
+/**
+ * Server-teardown purge (H-3, DEC-R2): delete EVERY oauth_grants row owned by one
+ * McpServer, across all flavors. The SQL scoping IS the testable contract at this
+ * layer — the service has no real-DB store harness (dynamicClientStore.ts and
+ * cleanupDynamicClientForServer are likewise untested), so a T4 observable-list
+ * assertion (which rows survived) is not achievable here. What we CAN pin is that
+ * the emitted DELETE is scoped to owner_kind='mcpserver' + the server coordinate
+ * and carries NO per-flavor narrowing that would leave grants behind.
+ */
+describe('deleteOAuthGrantsForServer — full server-scoped wipe', () => {
+ const COORDS = { recipeNamespace: 'mcp-servers', recipeName: 'gdrive' }
+
+ function fakeDb(rowCount: number | null) {
+ const query = vi.fn(async () => ({ rowCount, rows: [] }))
+ return { db: { query } as unknown as DbClient, query }
+ }
+
+ it('issues exactly one DELETE scoped to owner_kind=mcpserver + ns + name, all-flavors', async () => {
+ const { db, query } = fakeDb(3)
+
+ await deleteOAuthGrantsForServer(db, COORDS)
+
+ expect(query).toHaveBeenCalledTimes(1)
+ const sql = String(query.mock.calls[0][0])
+ expect(sql).toContain('DELETE FROM oauth_grants')
+ // Scope: server-owned rows only, keyed by the server coordinate.
+ expect(sql).toContain("owner_kind = 'mcpserver'")
+ expect(sql).toContain('recipe_namespace = $1')
+ expect(sql).toContain('recipe_name = $2')
+ // All-flavors wipe: NONE of these narrowings may appear, or grants survive.
+ expect(sql).not.toContain('user_id')
+ expect(sql).not.toContain('context_id')
+ expect(sql).not.toContain('oauth_client_id')
+ expect(sql).not.toContain('grant_kind')
+ })
+
+ it('binds params to exactly [recipeNamespace, recipeName]', async () => {
+ const { db, query } = fakeDb(3)
+
+ await deleteOAuthGrantsForServer(db, COORDS)
+
+ expect(query.mock.calls[0][1]).toEqual(['mcp-servers', 'gdrive'])
+ })
+
+ it('returns the deleted row count', async () => {
+ const { db } = fakeDb(3)
+ expect(await deleteOAuthGrantsForServer(db, COORDS)).toBe(3)
+ })
+
+ it('returns 0 when the driver reports a null rowCount (idempotent, nothing purged)', async () => {
+ const { db } = fakeDb(null)
+ expect(await deleteOAuthGrantsForServer(db, COORDS)).toBe(0)
+ })
+})
diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.ts
index 79639cb18..495710d04 100644
--- a/control-api/src/oauth/store.ts
+++ b/control-api/src/oauth/store.ts
@@ -555,6 +555,32 @@ export async function deleteOAuthGrant(db: DbClient, input: GetOAuthGrantInput):
return result.rowCount ?? 0
}
+/**
+ * Purge EVERY oauth_grants row owned by one McpServer — server teardown only
+ * (called from the CR uninstall). Deletes across all flavors (user/service/shared),
+ * all users, all contexts, all client ids for the server coordinate. Returns the
+ * row count deleted (0 ⇒ the server had none; idempotent).
+ *
+ * NOT the per-user revocation path (deleteOAuthGrant): that removes ONE user's grant
+ * by full key and must never cascade to other users or to dynamic_clients. This one
+ * is the opposite — a full wipe scoped to the server, run only when the server CR is
+ * being deleted.
+ */
+export async function deleteOAuthGrantsForServer(
+ db: DbClient,
+ coords: { recipeNamespace: string; recipeName: string }
+): Promise<number> {
+ // `owner_kind = 'mcpserver'` is load-bearing: it must never touch recipe-domain
+ // grants that share a name coordinate. No user_id / context_id / oauth_client_id /
+ // grant_kind filter — the wipe is intentionally all-flavors.
+ const result = await db.query(
+ `DELETE FROM oauth_grants
+ WHERE owner_kind = 'mcpserver' AND recipe_namespace = $1 AND recipe_name = $2`,
+ [coords.recipeNamespace, coords.recipeName]
+ )
+ return result.rowCount ?? 0
+}
+
/**
* Set (or clear) the background-consent flag on a user grant. Separate from
* upsertOAuthGrant so the refresh-on-demand re-upsert never disturbs consent.
diff --git a/control-api/src/routes/admin/__tests__/mcpServerUninstallPurgesGrants.test.ts b/control-api/src/routes/admin/__tests__/mcpServerUninstallPurgesGrants.test.ts
new file mode 100644
index 000000000..b027794b9
--- /dev/null
+++ b/control-api/src/routes/admin/__tests__/mcpServerUninstallPurgesGrants.test.ts
@@ -0,0 +1,83 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+
+/**
+ * H-3 route regression (T3/T4): the generic McpServer uninstall
+ * (DELETE /admin/mcp-servers/:name) must purge the server's oauth_grants rows
+ * as an observable uninstall side-effect. Before H-3 the handler cleaned the
+ * Secret, the DCR row, and the Context allowlists but never touched
+ * oauth_grants, orphaning them.
+ *
+ * Seam chosen: a test-only `vi.mock('../../../db.js', ...)` that keeps every
+ * real export via `importActual` and swaps ONLY the module-global `pool` for a
+ * recording fake whose `query` returns benign empty results. No production
+ * change — `createAdminResourcesRouter` reads the DB through `pool.query`
+ * (resources.ts: `dcrDb = { query: (t,v) => pool.query(t,v) }`). We observe the
+ * uninstall via the recorded queries.
+ *
+ * T4: the assertion is on the observable uninstall behavior (a scoped
+ * grants-purge DELETE was executed), derived from the real handler — not on a
+ * hand-built fixture of another layer. The store's exact SQL contract is pinned
+ * separately in oauth/__tests__/deleteOAuthGrantsForServer.test.ts.
+ *
+ * T3: this test FAILS against parent a5b354ce9 — there the uninstall issues no
+ * oauth_grants DELETE, so `purge` is undefined and the assertion fails. The file
+ * does not import deleteOAuthGrantsForServer, so it compiles+runs at parent.
+ */
+
+const dbMock = vi.hoisted(() => {
+ const calls: Array<{ text: string; values: unknown[] }> = []
+ const query = vi.fn(async (text: string, values?: unknown[]) => {
+ calls.push({ text, values: values ?? [] })
+ return { rows: [], rowCount: 0 }
+ })
+ return { calls, query }
+})
+
+vi.mock('../../../db.js', async importActual => {
+ const actual = await importActual<typeof import('../../../db.js')>()
+ return { ...actual, pool: { query: dbMock.query } }
+})
+
+// Import AFTER vi.mock so the swapped `pool` wires into the router.
+const { createAdminResourcesRouter } = await import('../resources.js')
+const { config } = await import('../../../config.js')
+
+describe('DELETE /admin/mcp-servers/:name — purges oauth_grants on uninstall (H-3)', () => {
+ const SERVER_NAME = 'gdrive'
+
+ function buildApp() {
+ const gateway = {
+ deleteResource: vi.fn(async () => ({ metadata: { name: SERVER_NAME } })),
+ deleteSecret: vi.fn(async () => ({})),
+ getSecret: vi.fn(async () => ({})),
+ listResource: vi.fn(async () => []),
+ updateResource: vi.fn(async () => ({})),
+ }
+ const app = express()
+ app.use(express.json({ limit: '1mb' }))
+ app.use('/api/v1', createAdminResourcesRouter(gateway as never))
+ return { app, gateway }
+ }
+
+ beforeEach(() => {
+ dbMock.calls.length = 0
+ dbMock.query.mockClear()
+ })
+
+ it('executes a server-scoped DELETE FROM oauth_grants during uninstall', async () => {
+ const { app } = buildApp()
+
+ const res = await request(app).delete(`/api/v1/admin/mcp-servers/${SERVER_NAME}`)
+ expect(res.status).toBe(200)
+
+ const purge = dbMock.calls.find(
+ c =>
+ /DELETE\s+FROM\s+oauth_grants/i.test(c.text) && c.text.includes("owner_kind = 'mcpserver'")
+ )
+ // Before H-3 no such query is issued — this is the regression anchor.
+ expect(purge).toBeDefined()
+ expect(purge!.values).toEqual([config.mcpServersNamespace, SERVER_NAME])
+ })
+})
diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.ts
index a85918ead..2ad41b182 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -14,6 +14,7 @@ import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec
import { K8sGateway } from '../../k8s.js'
import { cleanupDynamicClientForServer } from '../../oauth/dcrCleanup.js'
import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
+import { deleteOAuthGrantsForServer } from '../../oauth/store.js'
import { rootLogger } from '../../observability/logger.js'
import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'
import {
@@ -1105,6 +1106,28 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
)
}
+ // Server teardown (DEC-R2): wipe ALL of this server's oauth_grants rows —
+ // every user / context / client / flavor. Idempotent; never blocks the
+ // uninstall (the CR is already deleted). This is NOT the per-user
+ // revocation path — see deleteOAuthGrantsForServer.
+ try {
+ const purged = await deleteOAuthGrantsForServer(dcrDb, {
+ recipeNamespace: ns,
+ recipeName: name,
+ })
+ if (purged > 0) {
+ log.info(
+ { event: 'mcpserver_oauth_grants_purged', name, namespace: ns, count: purged },
+ 'purged oauth grants on uninstall'
+ )
+ }
+ } catch (err) {
+ log.error(
+ { event: 'mcpserver_oauth_grants_purge_failed', name, namespace: ns, err },
+ 'oauth grants purge failed on uninstall (CR already deleted)'
+ )
+ }
+
try {
const ctxList = (await gateway.listResource('contexts', contextsNs)) as Array<{
metadata?: { name?: string }