Skip to content

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

TypeScript

fix(control-api): fence the mcp-server uninstall OAuth teardown by CR uid (R3-H5)

Diego Zacariase20e505a0879
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 4c29ba6c0..ace292e60 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.665",
+ "version": "0.1.666",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.665",
+ "version": "0.1.666",
"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 63e5abaa8..ebcadcb60 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.665",
+ "version": "0.1.666",
"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__/callbackMcpMembership.test.ts b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
index 6c7498c16..f72d0b0d6 100644
--- a/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
+++ b/control-api/src/oauth/__tests__/callbackMcpMembership.test.ts
@@ -204,4 +204,56 @@ describe('handleOAuthCallback — mcp context membership guard (R3-L1)', () => {
expect(String(query.mock.calls[0][0])).toContain('INSERT INTO oauth_grants')
expect(String(query.mock.calls[0][0])).toContain("'user'")
})
+
+ // R3-H5 (D-T3): the subject's CR uid seals the grant so a same-name reinstall's
+ // teardown never purges this installation's consent.
+ it('seals a shared bootstrap grant with the subject cr_uid', async () => {
+ const deps = buildDeps({
+ subject: mcpSubject({ grantScope: 'context', contextRef: CONTEXT_REF, crUid: 'uid-live-cr' }),
+ contextIds: [CONTEXT_REF],
+ })
+
+ const result = await handleOAuthCallback(input(), deps)
+ expect(result.kind).toBe('ok')
+
+ const query = deps.db.query as ReturnType<typeof vi.fn>
+ const [sql, values] = query.mock.calls[0]
+ expect(String(sql)).toContain('INSERT INTO oauth_grants')
+ expect(String(sql)).toContain("'shared'")
+ // cr_uid is the last positional param of the shared INSERT.
+ expect((values as unknown[]).at(-1)).toBe('uid-live-cr')
+ })
+
+ it('seals a per-user grant with the subject cr_uid', async () => {
+ const deps = buildDeps({
+ subject: mcpSubject({ grantScope: 'user', contextRef: undefined, crUid: 'uid-live-cr' }),
+ userContextsReader: vi.fn(async () => ({ contextIds: [] })),
+ })
+
+ const result = await handleOAuthCallback(input(), deps)
+ expect(result.kind).toBe('ok')
+
+ const query = deps.db.query as ReturnType<typeof vi.fn>
+ const [sql, values] = query.mock.calls[0]
+ expect(String(sql)).toContain('INSERT INTO oauth_grants')
+ expect(String(sql)).toContain("'user'")
+ // cr_uid is the last positional param of the user INSERT.
+ expect((values as unknown[]).at(-1)).toBe('uid-live-cr')
+ })
+
+ // A grant with NO subject cr_uid (a legacy/authorize-url path that never read a
+ // live CR) persists cr_uid NULL — never crashes, and stays purgeable by any teardown.
+ it('persists cr_uid NULL when the subject carries no uid', async () => {
+ const deps = buildDeps({
+ subject: mcpSubject({ grantScope: 'user', contextRef: undefined, crUid: undefined }),
+ userContextsReader: vi.fn(async () => ({ contextIds: [] })),
+ })
+
+ const result = await handleOAuthCallback(input(), deps)
+ expect(result.kind).toBe('ok')
+
+ const query = deps.db.query as ReturnType<typeof vi.fn>
+ const [, values] = query.mock.calls[0]
+ expect((values as unknown[]).at(-1)).toBeNull()
+ })
})
diff --git a/control-api/src/oauth/__tests__/deleteOAuthGrantsForServer.test.ts b/control-api/src/oauth/__tests__/deleteOAuthGrantsForServer.test.ts
index 1031a52c1..beb85641d 100644
--- a/control-api/src/oauth/__tests__/deleteOAuthGrantsForServer.test.ts
+++ b/control-api/src/oauth/__tests__/deleteOAuthGrantsForServer.test.ts
@@ -3,23 +3,22 @@ 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.
+ * Server-teardown purge (H-3, DEC-R2; fenced by cr_uid in R3-H5): delete EVERY
+ * oauth_grants row of ONE McpServer installation, across all flavors. This unit
+ * layer pins the SQL contract — scope, the cr_uid fence, and the absence of any
+ * per-flavor narrowing that would leave grants behind. The T4 observable-list
+ * behavior (which rows survived) is pinned in the real-Postgres suites
+ * (oauth.deleteOAuthGrantsForServer / oauth.mcpServerOAuthTeardown).
*/
-describe('deleteOAuthGrantsForServer — full server-scoped wipe', () => {
- const COORDS = { recipeNamespace: 'mcp-servers', recipeName: 'gdrive' }
+describe('deleteOAuthGrantsForServer — full server-scoped wipe (fenced by cr_uid)', () => {
+ const COORDS = { recipeNamespace: 'mcp-servers', recipeName: 'gdrive', crUid: 'uid-abc' }
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 () => {
+ it('issues exactly one DELETE scoped to owner_kind=mcpserver + ns + name, all-flavors, fenced by cr_uid', async () => {
const { db, query } = fakeDb(3)
await deleteOAuthGrantsForServer(db, COORDS)
@@ -31,6 +30,8 @@ describe('deleteOAuthGrantsForServer — full server-scoped wipe', () => {
expect(sql).toContain("owner_kind = 'mcpserver'")
expect(sql).toContain('recipe_namespace = $1')
expect(sql).toContain('recipe_name = $2')
+ // Fenced: this installation's uid OR a legacy (NULL) row — never another uid's.
+ expect(sql).toContain('cr_uid = $3 OR cr_uid IS NULL')
// All-flavors wipe: NONE of these narrowings may appear, or grants survive.
expect(sql).not.toContain('user_id')
expect(sql).not.toContain('context_id')
@@ -38,12 +39,12 @@ describe('deleteOAuthGrantsForServer — full server-scoped wipe', () => {
expect(sql).not.toContain('grant_kind')
})
- it('binds params to exactly [recipeNamespace, recipeName]', async () => {
+ it('binds params to exactly [recipeNamespace, recipeName, crUid]', async () => {
const { db, query } = fakeDb(3)
await deleteOAuthGrantsForServer(db, COORDS)
- expect(query.mock.calls[0][1]).toEqual(['mcp-servers', 'gdrive'])
+ expect(query.mock.calls[0][1]).toEqual(['mcp-servers', 'gdrive', 'uid-abc'])
})
it('returns the deleted row count', async () => {
diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.ts
index 0d2bf0c72..f52ac4464 100644
--- a/control-api/src/oauth/callback.ts
+++ b/control-api/src/oauth/callback.ts
@@ -184,6 +184,12 @@ export interface McpServerOAuthSubject {
decl: OAuthClientDecl
grantScope: 'user' | 'context'
contextRef?: string
+ /**
+ * metadata.uid of the McpServer CR, sealing any grant this consent writes to the
+ * exact installation (R3-H5). Present when the reader read a live CR; absent for
+ * the authorize-url minting paths that never persist a grant.
+ */
+ crUid?: string
}
export interface McpServerOAuthReader {
@@ -589,6 +595,8 @@ async function handleMcpOAuthCallback(
accessToken: parsed.accessToken,
refreshToken: parsed.refreshToken,
accessTokenExpiresInSec: parsed.expiresIn,
+ // Seal to this installation so a same-name reinstall's teardown never purges it.
+ crUid: subject.crUid,
})
} else {
await upsertOAuthGrant(deps.db, deps.encryptionKey, {
@@ -603,6 +611,8 @@ async function handleMcpOAuthCallback(
accessToken: parsed.accessToken,
refreshToken: parsed.refreshToken,
accessTokenExpiresInSec: parsed.expiresIn,
+ // Seal to this installation so a same-name reinstall's teardown never purges it.
+ crUid: subject.crUid,
})
}
diff --git a/control-api/src/oauth/dcrCleanup.ts b/control-api/src/oauth/dcrCleanup.ts
index b3a9cd3f1..69d93f775 100644
--- a/control-api/src/oauth/dcrCleanup.ts
+++ b/control-api/src/oauth/dcrCleanup.ts
@@ -1,17 +1,11 @@
-import type { DbClient } from '../db.js'
import { pinnedFetch } from '../http/pinnedFetch.js'
import type { DcrDeps } from './dcr.js'
-import {
- type DynamicClientKey,
- deleteDynamicClient,
- getDynamicClient,
-} from './dynamicClientStore.js'
/**
- * Shared DCR (RFC 7591/7592) client teardown (spec 02 C2/C4, DEC-18). Extracted
- * here once the compensation idiom reached a 4th call site (the mcp-server
- * uninstall) — the install saga's rollback paths (`remoteMcp.ts`) and the
- * uninstall now share ONE implementation (colateral DRY note of C2).
+ * Best-effort RFC 7592 client-delete at the AS's management endpoint (spec 02
+ * C2/C4, DEC-18). Shared by the install saga's rollback paths (`remoteMcp.ts`) and
+ * the uninstall teardown module (`mcpServerOAuthTeardown.ts`) — the reliable local
+ * revocation is the store delete each caller runs; this is the courtesy cleanup.
*/
const DCR_DELETE_TIMEOUT_MS = 15_000
@@ -20,8 +14,8 @@ const DCR_DELETE_TIMEOUT_MS = 15_000
* Best-effort RFC 7592 client-delete against the AS's management endpoint, so a
* dynamic client we minted does not linger at the AS after a local abort/uninstall.
* Single-hop pinned DELETE (never re-resolves) with the registration bearer; any
- * failure is swallowed — the local `deleteDynamicClient` is the reliable
- * revocation, this is courtesy cleanup. Never logs the bearer.
+ * failure is swallowed — the caller's local store delete is the reliable revocation,
+ * this is courtesy cleanup. Never logs the bearer.
*/
export async function bestEffortRfc7592Delete(
dcrDeps: DcrDeps,
@@ -37,44 +31,6 @@ export async function bestEffortRfc7592Delete(
timeoutMs: DCR_DELETE_TIMEOUT_MS,
})
} catch {
- // Best-effort; the local store delete is the reliable revocation.
+ // Best-effort; the caller's local store delete is the reliable revocation.
}
}
-
-export interface DcrTeardownResult {
- /** Rows removed from `dynamic_clients` (0 ⇒ no DCR client for this server — already clean). */
- localRowsDeleted: number
- /** Whether a courtesy RFC 7592 DELETE was attempted (the row carried a management handle). */
- attemptedRemoteDelete: boolean
-}
-
-/**
- * Full DCR teardown for a server CR keyed per-server (`owner_kind/namespace/name`):
- * read the stored row, best-effort RFC 7592 DELETE at the AS (courtesy), then the
- * reliable local `deleteDynamicClient`. Idempotent — a server with no DCR client
- * (0 rows) is a clean no-op. Reads never mask the local delete: if the store read
- * throws (e.g. a decrypt error), the local delete still runs.
- */
-export async function cleanupDynamicClientForServer(
- db: DbClient,
- encryptionKey: Buffer,
- dcrDeps: DcrDeps,
- key: DynamicClientKey
-): Promise<DcrTeardownResult> {
- let registrationClientUri: string | undefined
- let registrationAccessToken: string | undefined
- try {
- const row = await getDynamicClient(db, encryptionKey, key)
- registrationClientUri = row?.registrationClientUri
- registrationAccessToken = row?.registrationAccessToken
- } catch {
- // Read failed — fall through to the reliable local delete below.
- }
- let attemptedRemoteDelete = false
- if (registrationClientUri && registrationAccessToken) {
- attemptedRemoteDelete = true
- await bestEffortRfc7592Delete(dcrDeps, registrationClientUri, registrationAccessToken)
- }
- const localRowsDeleted = await deleteDynamicClient(db, key)
- return { localRowsDeleted, attemptedRemoteDelete }
-}
diff --git a/control-api/src/oauth/dynamicClientStore.ts b/control-api/src/oauth/dynamicClientStore.ts
index 8be4832d5..a783f4fa3 100644
--- a/control-api/src/oauth/dynamicClientStore.ts
+++ b/control-api/src/oauth/dynamicClientStore.ts
@@ -285,21 +285,6 @@ export async function listExpiringDynamicClients(
})
}
-/**
- * Hard-delete the dynamic client for a server CR (idempotent). Returns the
- * number of rows removed so a caller can audit whether anything was revoked
- * (0 ⇒ already gone). Mirrors `deleteOAuthGrant`.
- */
-export async function deleteDynamicClient(db: DbClient, key: DynamicClientKey): Promise<number> {
- const ownerKind = resolveOwnerKind(key)
- const result = await db.query(
- `DELETE FROM dynamic_clients
- WHERE owner_kind = $1 AND server_namespace = $2 AND server_name = $3`,
- [ownerKind, key.serverNamespace, key.serverName]
- )
- return result.rowCount ?? 0
-}
-
/**
* RFC 7592 management handle of a dynamic client: the endpoint and the bearer
* needed to DELETE it at the AS. Present only when both were persisted.
diff --git a/control-api/src/oauth/mcpServerOAuthTeardown.ts b/control-api/src/oauth/mcpServerOAuthTeardown.ts
new file mode 100644
index 000000000..11e45e728
--- /dev/null
+++ b/control-api/src/oauth/mcpServerOAuthTeardown.ts
@@ -0,0 +1,104 @@
+import type { DbClient } from '../db.js'
+import type { Logger } from '../observability/logger.js'
+import { mcpServerUninstallTeardownFailuresTotal } from '../observability/metrics.js'
+import type { DcrDeps } from './dcr.js'
+import { bestEffortRfc7592Delete } from './dcrCleanup.js'
+import { claimDeleteDynamicClientForResource } from './dynamicClientStore.js'
+import { deleteOAuthGrantsForServer } from './store.js'
+
+/**
+ * Shared OAuth teardown for a mcp-server uninstall, fenced by the uninstalled CR's
+ * `metadata.uid` (R3-H5). Replaces the previous name-only pair — `dcrCleanup`'s
+ * `cleanupDynamicClientForServer` and the loose `deleteOAuthGrantsForServer` call in
+ * the uninstall route — so a same-name REINSTALL's state is never torn down or revoked
+ * by the uninstall of a previous installation.
+ *
+ * Two race windows the uid fence + the single-statement claim close:
+ * - B: the reinstall wrote its row before the old teardown ran → the old name-only
+ * read+revoke would revoke the NEW client. Here the DELETE…RETURNING only revokes
+ * the client of the row it actually removed (this uid's, or a legacy row's).
+ * - C: the old read→await(7592)→delete gap let a reinstall slip a new row in between.
+ * Here there is no gap: the claim is one statement.
+ *
+ * Runs AFTER the CR delete; never throws. Each stage is best-effort — a throw is
+ * caught, counted (metric, existing stage labels) and logged (names-only), and the
+ * uninstall keeps its 200. Changing that response policy is R3-H7, out of scope.
+ */
+export type TeardownStageResult = 'done' | 'none' | 'failed'
+
+export interface McpServerOAuthTeardownResult {
+ /** 'done' = a DCR row was removed, 'none' = none matched (clean), 'failed' = threw. */
+ dynamicClient: TeardownStageResult
+ /** 'done' = grant rows were purged, 'none' = none matched (clean), 'failed' = threw. */
+ grants: TeardownStageResult
+}
+
+export async function teardownMcpServerOAuthState(
+ db: DbClient,
+ encryptionKey: Buffer,
+ dcrDeps: DcrDeps,
+ input: { namespace: string; name: string; crUid: string },
+ logger: Logger
+): Promise<McpServerOAuthTeardownResult> {
+ const { namespace, name, crUid } = input
+ const result: McpServerOAuthTeardownResult = { dynamicClient: 'none', grants: 'none' }
+
+ // DCR: single-statement claim+read. Deletes the row bound to this uid (or a legacy
+ // row) and returns its RFC 7592 handle; a pending row or a row bound to a different
+ // uid (a reinstall) is left intact. Only the actually-deleted row's client is revoked.
+ try {
+ const claimed = await claimDeleteDynamicClientForResource(
+ db,
+ encryptionKey,
+ { ownerKind: 'mcpserver', serverNamespace: namespace, serverName: name },
+ crUid
+ )
+ if (claimed.deleted) {
+ result.dynamicClient = 'done'
+ if (claimed.handle) {
+ await bestEffortRfc7592Delete(
+ dcrDeps,
+ claimed.handle.registrationClientUri,
+ claimed.handle.registrationAccessToken
+ )
+ }
+ logger.info(
+ { serverName: name, namespace, attemptedRemoteDelete: Boolean(claimed.handle) },
+ 'Revoked remote OAuth dynamic client on uninstall'
+ )
+ }
+ } catch (err) {
+ result.dynamicClient = 'failed'
+ mcpServerUninstallTeardownFailuresTotal.inc({ stage: 'dynamic_client' })
+ logger.error(
+ { serverName: name, namespace, err },
+ 'Dynamic client cleanup failed on uninstall (CR already deleted)'
+ )
+ }
+
+ // Grants: purge this installation's rows (fenced by cr_uid + legacy). A reinstall's
+ // grant (a different uid) survives.
+ try {
+ const purged = await deleteOAuthGrantsForServer(db, {
+ recipeNamespace: namespace,
+ recipeName: name,
+ crUid,
+ })
+ if (purged > 0) {
+ result.grants = 'done'
+ logger.info(
+ { serverName: name, namespace, count: purged },
+ 'Purged OAuth grants on uninstall'
+ )
+ }
+ } catch (err) {
+ result.grants = 'failed'
+ mcpServerUninstallTeardownFailuresTotal.inc({ stage: 'oauth_grants' })
+ logger.error(
+ { serverName: name, namespace, err },
+ 'OAuth grants purge failed on uninstall (CR already deleted)'
+ )
+ }
+
+ return result
+}
diff --git a/control-api/src/oauth/store.ts b/control-api/src/oauth/store.ts
index 74e13565c..479c904e6 100644
--- a/control-api/src/oauth/store.ts
+++ b/control-api/src/oauth/store.ts
@@ -104,6 +104,12 @@ export type UpsertOAuthGrantInput = OAuthGrantKey & {
refreshToken?: string
/** Seconds until access token expires; null if provider didn't supply expires_in. */
accessTokenExpiresInSec?: number
+ /**
+ * metadata.uid of the owning McpServer, sealing the grant to this installation
+ * (user path only). Omitted for recipe-domain grants → NULL. The latest consent
+ * re-seals the row so a reinstall's grant carries the new uid.
+ */
+ crUid?: string
}
/**
@@ -136,14 +142,15 @@ export async function upsertOAuthGrant(
`INSERT INTO oauth_grants (
owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id, grant_kind,
provider, access_token_encrypted, refresh_token_encrypted,
- access_token_expires_at, updated_at
- ) VALUES ($1, $2, $3, $4, $5, 'user', $6, $7, $8, $9, NOW())
+ access_token_expires_at, cr_uid, updated_at
+ ) VALUES ($1, $2, $3, $4, $5, 'user', $6, $7, $8, $9, $10, NOW())
ON CONFLICT (owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id)
DO UPDATE SET
provider = EXCLUDED.provider,
access_token_encrypted = EXCLUDED.access_token_encrypted,
refresh_token_encrypted = EXCLUDED.refresh_token_encrypted,
access_token_expires_at = EXCLUDED.access_token_expires_at,
+ cr_uid = EXCLUDED.cr_uid,
updated_at = NOW()`,
[
ownerKind,
@@ -155,6 +162,7 @@ export async function upsertOAuthGrant(
accessTokenEncrypted,
refreshTokenEncrypted,
accessTokenExpiresAt,
+ input.crUid ?? null,
]
)
return
@@ -322,16 +330,23 @@ export async function refreshOAuthGrantTokens(
* an OAuth mcp-server with `grantScope='context'` lends their provider identity
* to the whole Context.
*
- * INSERT … ON CONFLICT DO NOTHING — first-wins tokens AND bootstrapper. If a
- * concurrent second member also completes consent (both minted an authorize URL
- * inside the state TTL), their row is a no-op: they inherit the team's grant,
- * and `bootstrapped_by_user_id` keeps pointing at whoever landed first
- * (mini-spec 05 §3). Distinct from the refresh path (`upsertOAuthGrant` above)
- * on purpose: conflating them would let the last completer silently overwrite
- * the team identity and the audit trail.
+ * INSERT … ON CONFLICT — first-wins tokens AND bootstrapper WITHIN ONE
+ * INSTALLATION. If a concurrent second member of the SAME install also completes
+ * consent (both minted an authorize URL inside the state TTL), their row is a
+ * no-op: they inherit the team's grant, and `bootstrapped_by_user_id` keeps
+ * pointing at whoever landed first (mini-spec 05 §3).
*
- * Returns `{ inserted }` so the caller can tell "you bootstrapped the team" from
- * "you joined an existing team identity".
+ * Fenced by `cr_uid` (R3-H5): a conflicting row of the SAME uid is left as-is
+ * (first bootstrapper wins), but a row of a DIFFERENT uid — or a legacy row
+ * (cr_uid NULL) left by a previous installation of the same name whose teardown
+ * did not reach it — is NOT this install's first bootstrapper, so it is REPLACED
+ * (the `WHERE cr_uid IS DISTINCT FROM` guard on the DO UPDATE). Distinct from the
+ * refresh path (`upsertOAuthGrant` above): conflating them would let the last
+ * completer of the same install silently overwrite the team identity and audit.
+ *
+ * Returns `{ inserted }` — true when THIS consent established this install's shared
+ * identity (a fresh insert, or a replace of a stale other-install/legacy row);
+ * false when it joined an existing same-install team identity.
*/
export type BootstrapSharedOAuthGrantInput = {
ownerKind: 'mcpserver'
@@ -345,6 +360,8 @@ export type BootstrapSharedOAuthGrantInput = {
accessToken: string
refreshToken?: string
accessTokenExpiresInSec?: number
+ /** metadata.uid of the owning McpServer, sealing the grant to this installation. */
+ crUid?: string
}
export async function bootstrapSharedOAuthGrant(
@@ -366,11 +383,19 @@ export async function bootstrapSharedOAuthGrant(
owner_kind, recipe_namespace, recipe_name, user_id, context_id,
oauth_client_id, grant_kind, bootstrapped_by_user_id,
provider, access_token_encrypted, refresh_token_encrypted,
- access_token_expires_at, updated_at
- ) VALUES ($1, $2, $3, NULL, $4, $5, 'shared', $6, $7, $8, $9, $10, NOW())
+ access_token_expires_at, cr_uid, updated_at
+ ) VALUES ($1, $2, $3, NULL, $4, $5, 'shared', $6, $7, $8, $9, $10, $11, NOW())
ON CONFLICT (owner_kind, recipe_namespace, recipe_name, context_id, oauth_client_id)
WHERE grant_kind = 'shared'
- DO NOTHING
+ DO UPDATE SET
+ bootstrapped_by_user_id = EXCLUDED.bootstrapped_by_user_id,
+ provider = EXCLUDED.provider,
+ access_token_encrypted = EXCLUDED.access_token_encrypted,
+ refresh_token_encrypted = EXCLUDED.refresh_token_encrypted,
+ access_token_expires_at = EXCLUDED.access_token_expires_at,
+ cr_uid = EXCLUDED.cr_uid,
+ updated_at = NOW()
+ WHERE oauth_grants.cr_uid IS DISTINCT FROM EXCLUDED.cr_uid
RETURNING id`,
[
input.ownerKind,
@@ -383,6 +408,7 @@ export async function bootstrapSharedOAuthGrant(
accessTokenEncrypted,
refreshTokenEncrypted,
accessTokenExpiresAt,
+ input.crUid ?? null,
]
)
return { inserted: (result.rowCount ?? 0) > 0 }
@@ -568,15 +594,21 @@ export async function deleteOAuthGrant(db: DbClient, input: GetOAuthGrantInput):
*/
export async function deleteOAuthGrantsForServer(
db: DbClient,
- coords: { recipeNamespace: string; recipeName: string }
+ coords: { recipeNamespace: string; recipeName: string; crUid: 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.
+ // grant_kind filter — the wipe is intentionally all-flavors FOR THIS INSTALLATION.
+ //
+ // Fenced by `cr_uid`: grants sealed with the uninstalled CR's uid are purged, and
+ // legacy grants (cr_uid IS NULL, written before install identity or by a pod mid-
+ // rollout) are purged too. A grant sealed with a DIFFERENT uid — a same-name
+ // reinstall's consent that landed in the teardown window — SURVIVES (R3-H5).
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]
+ WHERE owner_kind = 'mcpserver' AND recipe_namespace = $1 AND recipe_name = $2
+ AND (cr_uid = $3 OR cr_uid IS NULL)`,
+ [coords.recipeNamespace, coords.recipeName, coords.crUid]
)
return result.rowCount ?? 0
}
diff --git a/control-api/src/routes/admin/__tests__/mcpServerUninstallDeletesOauthClientSecret.test.ts b/control-api/src/routes/admin/__tests__/mcpServerUninstallDeletesOauthClientSecret.test.ts
index eeb9deae1..7d2a86198 100644
--- a/control-api/src/routes/admin/__tests__/mcpServerUninstallDeletesOauthClientSecret.test.ts
+++ b/control-api/src/routes/admin/__tests__/mcpServerUninstallDeletesOauthClientSecret.test.ts
@@ -47,18 +47,28 @@ describe('DELETE /admin/mcp-servers/:name — deletes the oauth-client Secret on
function buildApp() {
const deleteSecretCalls: Array<{ name: string; namespace: string }> = []
const gateway = {
+ // The uninstall reads the CR before deleting to capture metadata.uid (R3-H5).
+ getResource: vi.fn(async () => ({
+ metadata: { name: SERVER_NAME, uid: `uid-${SERVER_NAME}`, resourceVersion: '1' },
+ })),
deleteResource: vi.fn(async () => ({ metadata: { name: SERVER_NAME } })),
deleteSecret: vi.fn(async (name: string, namespace: string) => {
deleteSecretCalls.push({ name, namespace })
return {}
}),
// The uninstall now fences each Secret cleanup on the identity read back
- // BEFORE the CR delete (uid/resourceVersion precondition), so a live
- // read must expose that identity exactly as real K8s getSecret does —
- // returning a bare `{}` would report `identity-unavailable` and skip the
- // delete, which is not a state a real existing Secret can be in.
+ // BEFORE the CR delete (uid/resourceVersion precondition), so a live read
+ // must expose that identity exactly as real K8s getSecret does. The
+ // `${name}-oauth-client` cleanup ALSO requires the control-api managed-by
+ // label (R3-H6 ownership guard) — without it the guard classifies the Secret
+ // `not-managed` and skips the delete, so the fixture must carry the label a
+ // real install-saga-created Secret has.
getSecret: vi.fn(async (name: string) => ({
- metadata: { uid: `uid-${name}`, resourceVersion: '1' },
+ metadata: {
+ uid: `uid-${name}`,
+ resourceVersion: '1',
+ labels: { 'clerum.io/managed-by': 'control-api' },
+ },
})),
listResource: vi.fn(async () => []),
updateResource: vi.fn(async () => ({})),
diff --git a/control-api/src/routes/admin/__tests__/mcpServerUninstallPurgesGrants.test.ts b/control-api/src/routes/admin/__tests__/mcpServerUninstallPurgesGrants.test.ts
index b027794b9..adf94e903 100644
--- a/control-api/src/routes/admin/__tests__/mcpServerUninstallPurgesGrants.test.ts
+++ b/control-api/src/routes/admin/__tests__/mcpServerUninstallPurgesGrants.test.ts
@@ -44,11 +44,16 @@ vi.mock('../../../db.js', async importActual => {
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)', () => {
+describe('DELETE /admin/mcp-servers/:name — purges oauth_grants on uninstall (H-3, R3-H5)', () => {
const SERVER_NAME = 'gdrive'
+ const CR_UID = 'uid-gdrive-live'
function buildApp() {
const gateway = {
+ // The uninstall reads the CR before deleting to capture metadata.uid (R3-H5).
+ getResource: vi.fn(async () => ({
+ metadata: { name: SERVER_NAME, uid: CR_UID, resourceVersion: '7' },
+ })),
deleteResource: vi.fn(async () => ({ metadata: { name: SERVER_NAME } })),
deleteSecret: vi.fn(async () => ({})),
getSecret: vi.fn(async () => ({})),
@@ -66,7 +71,7 @@ describe('DELETE /admin/mcp-servers/:name — purges oauth_grants on uninstall (
dbMock.query.mockClear()
})
- it('executes a server-scoped DELETE FROM oauth_grants during uninstall', async () => {
+ it('executes a cr_uid-fenced 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}`)
@@ -76,8 +81,24 @@ describe('DELETE /admin/mcp-servers/:name — purges oauth_grants on uninstall (
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.
+ // Before H-3 no such query is issued; before R3-H5 it carried no cr_uid fence.
expect(purge).toBeDefined()
- expect(purge!.values).toEqual([config.mcpServersNamespace, SERVER_NAME])
+ expect(purge!.text).toContain('cr_uid = $3 OR cr_uid IS NULL')
+ expect(purge!.values).toEqual([config.mcpServersNamespace, SERVER_NAME, CR_UID])
+ })
+
+ it('deletes the CR fenced on the uid read before delete', async () => {
+ const { app, gateway } = buildApp()
+
+ await request(app).delete(`/api/v1/admin/mcp-servers/${SERVER_NAME}`)
+
+ expect(gateway.getResource).toHaveBeenCalledWith(
+ 'mcpservers',
+ SERVER_NAME,
+ config.mcpServersNamespace
+ )
+ // deleteResource receives the uid precondition captured from the read CR.
+ const deleteArgs = gateway.deleteResource.mock.calls[0]
+ expect(deleteArgs[3]).toEqual({ uid: CR_UID })
})
})
diff --git a/control-api/src/routes/admin/__tests__/mcpServerUninstallTeardownMetrics.test.ts b/control-api/src/routes/admin/__tests__/mcpServerUninstallTeardownMetrics.test.ts
index ce2c631a8..54c554344 100644
--- a/control-api/src/routes/admin/__tests__/mcpServerUninstallTeardownMetrics.test.ts
+++ b/control-api/src/routes/admin/__tests__/mcpServerUninstallTeardownMetrics.test.ts
@@ -48,6 +48,10 @@ describe('DELETE /admin/mcp-servers/:name — teardown failure increments the co
function buildApp() {
const gateway = {
+ // The uninstall reads the CR before deleting to capture metadata.uid (R3-H5).
+ getResource: vi.fn(async () => ({
+ metadata: { name: SERVER_NAME, uid: 'uid-gdrive-live', resourceVersion: '1' },
+ })),
deleteResource: vi.fn(async () => ({ metadata: { name: SERVER_NAME } })),
deleteSecret: vi.fn(async () => ({})),
getSecret: vi.fn(async () => ({})),
diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.ts
index 5213a0071..9cc8aa66f 100644
--- a/control-api/src/routes/admin/resources.ts
+++ b/control-api/src/routes/admin/resources.ts
@@ -12,9 +12,8 @@ import { enforceNamespace } from '../../http/namespaceAudit.js'
import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'
import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'
import { K8sGateway } from '../../k8s.js'
-import { cleanupDynamicClientForServer } from '../../oauth/dcrCleanup.js'
import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
-import { deleteOAuthGrantsForServer } from '../../oauth/store.js'
+import { teardownMcpServerOAuthState } from '../../oauth/mcpServerOAuthTeardown.js'
import { rootLogger } from '../../observability/logger.js'
import { mcpServerUninstallTeardownFailuresTotal } from '../../observability/metrics.js'
import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'
@@ -1178,7 +1177,30 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
})
: null
- const deleted = await gateway.deleteResource(plural, name, ns)
+ // mcpservers only: read the CR before deleting so its metadata.uid fences BOTH
+ // the delete (a same-name reinstall's CR has a different uid → the delete
+ // precondition 409s and we never tear down its state) AND the OAuth teardown
+ // (only this installation's dynamic_clients row + grants are removed, R3-H5). A
+ // 404 means the CR is already gone → no uid, so the teardown is skipped entirely.
+ let mcpServerCrUid: string | undefined
+ if (plural === 'mcpservers') {
+ try {
+ const cr = await gateway.getResource(plural, name, ns)
+ mcpServerCrUid = resourcePreconditionsFromResource(cr)?.uid
+ } catch (err) {
+ // getResource wraps a namespaced 404 as K8sNotFoundError (httpStatus, not
+ // statusCode), so match both shapes — as the update handler does above.
+ if (!(err instanceof K8sNotFoundError) && extractK8sStatusCode(err) !== 404) throw err
+ // CR already gone: leave uid undefined so the teardown below is skipped.
+ }
+ }
+
+ // Only the mcpservers delete is uid-fenced; every other plural keeps the exact
+ // 3-arg call it had (a trailing undefined would change the observed call shape).
+ const deleted =
+ mcpServerCrUid !== undefined
+ ? await gateway.deleteResource(plural, name, ns, { uid: mcpServerCrUid })
+ : await gateway.deleteResource(plural, name, ns)
if (plural === 'communicationchannels' && ccSecretRefName && ccSecretCleanup) {
if (ccSecretCleanup.status !== 'ready') {
@@ -1297,59 +1319,28 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {
}
}
- // Remote DCR client teardown (K, DEC-18): revoke the encrypted
- // `dynamic_clients` row (reliable) + best-effort RFC 7592 delete at the AS
- // (courtesy). Keyed per-server-CR; idempotent (0 rows ⇒ not a DCR server).
- // Never blocks or fails the uninstall — the CR is already deleted.
- try {
- const teardown = await cleanupDynamicClientForServer(
+ // OAuth teardown fenced by the CR uid (R3-H5): revoke this installation's
+ // encrypted `dynamic_clients` row + best-effort RFC 7592 delete at the AS, and
+ // purge its `oauth_grants` rows — never a same-name reinstall's state. Skipped
+ // when the uid is unknown (the CR read 404'd): a name-only teardown here would
+ // reopen the very race this fences. The module never throws; it counts/logs per
+ // stage and the uninstall keeps its 200 (the response policy is R3-H7).
+ if (mcpServerCrUid !== undefined) {
+ const teardown = await teardownMcpServerOAuthState(
dcrDb,
oauthEncryptionKey,
{ logger: log },
+ { namespace: ns, name, crUid: mcpServerCrUid },
+ log
+ )
+ log.info(
{
- ownerKind: 'mcpserver',
- serverNamespace: ns,
serverName: name,
- }
- )
- if (teardown.localRowsDeleted > 0) {
- log.info(
- {
- serverName: name,
- namespace: ns,
- attemptedRemoteDelete: teardown.attemptedRemoteDelete,
- },
- 'Revoked remote OAuth dynamic client on uninstall'
- )
- }
- } catch (err) {
- mcpServerUninstallTeardownFailuresTotal.inc({ stage: 'dynamic_client' })
- log.error(
- { serverName: name, namespace: ns, err },
- 'Dynamic client cleanup failed on uninstall (CR already deleted)'
- )
- }
-
- // 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(
- { serverName: name, namespace: ns, count: purged },
- 'Purged OAuth grants on uninstall'
- )
- }
- } catch (err) {
- mcpServerUninstallTeardownFailuresTotal.inc({ stage: 'oauth_grants' })
- log.error(
- { serverName: name, namespace: ns, err },
- 'OAuth grants purge failed on uninstall (CR already deleted)'
+ namespace: ns,
+ dynamicClient: teardown.dynamicClient,
+ grants: teardown.grants,
+ },
+ 'MCP server OAuth teardown completed'
)
}
diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.ts
index 0b7e68898..7e18f5235 100644
--- a/control-api/src/routes/external/oauthCallback.ts
+++ b/control-api/src/routes/external/oauthCallback.ts
@@ -90,7 +90,15 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {
}
const resolved = resolveServerOAuthSubject(server)
if (!resolved) return null
- return { namespace: config.mcpServersNamespace, ...resolved }
+ // Seal grants written by this consent to the CR's identity (R3-H5): the uid is
+ // the apiserver's, unique per object, so a same-name reinstall's teardown never
+ // purges this installation's grant. Undefined only if the CR carried no uid.
+ const crUid = (server as { metadata?: { uid?: unknown } }).metadata?.uid
+ return {
+ namespace: config.mcpServersNamespace,
+ ...(typeof crUid === 'string' && crUid ? { crUid } : {}),
+ ...resolved,
+ }
},
}
diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.ts
index c36ae42d1..85cd74f09 100644
--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts
+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts
@@ -468,7 +468,25 @@ export function makeInMemoryDynamicClientsDb(): {
const [owner_kind, server_namespace, server_name, fourth] = values
const key = keyOf(owner_kind, server_namespace, server_name)
const row = rows.get(key)
- // By-install DELETE (compensation): remove only when the install_id matches.
+ // Claim-delete (teardown): WHERE (cr_uid = $4 OR legacy) RETURNING the handle.
+ // Deletes the row bound to this uid or a legacy row (both identity cols NULL);
+ // a pending row or a row bound to a different uid does NOT match.
+ if (text.includes('RETURNING')) {
+ if (row && (row.cr_uid === fourth || (row.install_id == null && row.cr_uid == null))) {
+ rows.delete(key)
+ return {
+ rows: [
+ {
+ registration_client_uri: row.registration_client_uri,
+ registration_access_token_encrypted: row.registration_access_token_encrypted,
+ },
+ ],
+ rowCount: 1,
+ }
+ }
+ return { rows: [], rowCount: 0 }
+ }
+ // By-install DELETE (saga compensation): remove only when the install_id matches.
if (values.length === 4) {
if (row && row.install_id === fourth) {
rows.delete(key)
@@ -476,7 +494,7 @@ export function makeInMemoryDynamicClientsDb(): {
}
return { rows: [], rowCount: 0 }
}
- // By-name DELETE (legacy deleteDynamicClient / dcrCleanup).
+ // By-name DELETE (legacy).
const existed = rows.delete(key)
return { rows: [], rowCount: existed ? 1 : 0 }
}
diff --git a/control-api/test/oauth.callback.mcp.test.ts b/control-api/test/oauth.callback.mcp.test.ts
index db8ce3f89..8834c8037 100644
--- a/control-api/test/oauth.callback.mcp.test.ts
+++ b/control-api/test/oauth.callback.mcp.test.ts
@@ -178,10 +178,12 @@ describe('handleOAuthCallback — mcp subject (U5)', () => {
expect(db.query).toHaveBeenCalledTimes(1)
const [sql, params] = db.query.mock.calls[0] as [string, unknown[]]
- // The shared bootstrap INSERT … ON CONFLICT DO NOTHING (first-wins).
+ // The shared bootstrap INSERT … ON CONFLICT DO UPDATE fenced by cr_uid (R3-H5):
+ // same-uid conflict no-ops (first-wins), a different uid / legacy row is replaced.
expect(sql).toContain('INSERT INTO oauth_grants')
expect(sql).toContain("'shared'")
- expect(sql).toContain('DO NOTHING')
+ expect(sql).toContain('DO UPDATE SET')
+ expect(sql).toContain('oauth_grants.cr_uid IS DISTINCT FROM EXCLUDED.cr_uid')
// owner_kind, ns, name, context_id(=contextRef), oauthClientId, bootstrappedBy
expect(params[0]).toBe('mcpserver')
expect(params[1]).toBe(MCP_NS)
diff --git a/control-api/test/oauth.dcrCleanup.test.ts b/control-api/test/oauth.dcrCleanup.test.ts
index 3dbf454f7..6a8e775a2 100644
--- a/control-api/test/oauth.dcrCleanup.test.ts
+++ b/control-api/test/oauth.dcrCleanup.test.ts
@@ -1,89 +1,17 @@
import { describe, expect, it } from 'vitest'
-import { bestEffortRfc7592Delete, cleanupDynamicClientForServer } from '../src/oauth/dcrCleanup.js'
-import { getDynamicClient, upsertDynamicClient } from '../src/oauth/dynamicClientStore.js'
-import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
-import { makeDcrTransport, makeInMemoryDynamicClientsDb } from './fixtures/remoteOAuthDiscovery.js'
+import { bestEffortRfc7592Delete } from '../src/oauth/dcrCleanup.js'
/**
- * C4/K (DEC-18) — uninstall teardown of a remote server's DCR client. The row is
- * written by the REAL store (`upsertDynamicClient`, T1 — encrypted envelope never
- * hand-built) and the RFC 7592 DELETE goes through the injected pinned transport.
- * Idempotent: a non-DCR server is a clean no-op.
+ * C4/K (DEC-18) — best-effort RFC 7592 client-delete at the AS. The full server
+ * teardown moved to `mcpServerOAuthTeardown.ts` (fenced by cr_uid, R3-H5) and is
+ * covered by its real-Postgres suite; this pins the courtesy revocation's
+ * failure-swallowing contract shared by the saga rollback and the teardown module.
*/
-const ENC = deriveOAuthEncryptionKey(
- '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'
-)
const PUBLIC_IP = async () => ['93.184.216.34']
-const KEY = {
- ownerKind: 'mcpserver' as const,
- serverNamespace: 'mcp-server',
- serverName: 'notion-remote',
-}
-describe('cleanupDynamicClientForServer (uninstall)', () => {
- it('revokes the local row AND attempts the best-effort RFC 7592 delete', async () => {
- const { db } = makeInMemoryDynamicClientsDb()
- await upsertDynamicClient(db, ENC, {
- ...KEY,
- issuer: 'https://mcp.notion.com',
- clientId: 'dcr-client-123',
- clientMode: 'confidential',
- clientSecret: 'shh',
- registrationAccessToken: 'reg-bearer-xyz',
- registrationClientUri: 'https://mcp.notion.com/register/dcr-client-123',
- })
-
- const { transport, calls } = makeDcrTransport({ responseJson: '' })
- const result = await cleanupDynamicClientForServer(
- db,
- ENC,
- { transport, resolveDns: PUBLIC_IP },
- KEY
- )
-
- expect(result).toEqual({ localRowsDeleted: 1, attemptedRemoteDelete: true })
- // Local row gone.
- expect(await getDynamicClient(db, ENC, KEY)).toBeNull()
- // RFC 7592 DELETE hit the registration_client_uri with the bearer.
- const del = calls.find(c => c.method === 'DELETE')
- expect(del?.url).toBe('https://mcp.notion.com/register/dcr-client-123')
- expect(del?.headers.authorization).toBe('Bearer reg-bearer-xyz')
- })
-
- it('is idempotent — a server with no DCR client is a clean no-op (0 rows, no remote delete)', async () => {
- const { db } = makeInMemoryDynamicClientsDb()
- const { transport, calls } = makeDcrTransport({ responseJson: '' })
- const result = await cleanupDynamicClientForServer(
- db,
- ENC,
- { transport, resolveDns: PUBLIC_IP },
- KEY
- )
- expect(result).toEqual({ localRowsDeleted: 0, attemptedRemoteDelete: false })
- expect(calls.some(c => c.method === 'DELETE')).toBe(false)
- })
-
- it('a DCR row without a management handle still deletes locally (no remote delete)', async () => {
- const { db } = makeInMemoryDynamicClientsDb()
- await upsertDynamicClient(db, ENC, {
- ...KEY,
- issuer: 'https://mcp.notion.com',
- clientId: 'dcr-client-nohandle',
- clientMode: 'public',
- })
- const { transport, calls } = makeDcrTransport({ responseJson: '' })
- const result = await cleanupDynamicClientForServer(
- db,
- ENC,
- { transport, resolveDns: PUBLIC_IP },
- KEY
- )
- expect(result).toEqual({ localRowsDeleted: 1, attemptedRemoteDelete: false })
- expect(calls.some(c => c.method === 'DELETE')).toBe(false)
- })
-
- it('bestEffortRfc7592Delete swallows transport failures (courtesy cleanup)', async () => {
+describe('bestEffortRfc7592Delete', () => {
+ it('swallows transport failures (courtesy cleanup)', async () => {
const transport = async () => {
throw new Error('AS unreachable')
}
diff --git a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
index 5c63e7026..50fd005fd 100644
--- a/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
+++ b/control-api/test/oauth.deleteOAuthGrantsForServer.realPostgres.integration.test.ts
@@ -66,8 +66,11 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
}
})
- it('wipes every flavor of the target server and leaves a peer server intact', async () => {
- // Target server 'gdrive': one user grant + one shared/context grant.
+ const U = 'uid-gdrive-U'
+ const U_PRIME = 'uid-gdrive-Uprime'
+
+ it('purges this uid + legacy grants, spares a different uid and a peer server (fenced)', async () => {
+ // Target server 'gdrive', THIS installation (uid U): a user grant + a shared grant.
await upsertOAuthGrant(db, KEY, {
grantKind: 'user',
ownerKind: 'mcpserver',
@@ -78,6 +81,7 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
provider: 'google',
accessToken: 'at-user-a',
refreshToken: 'rt-user-a',
+ crUid: U,
})
const { inserted } = await bootstrapSharedOAuthGrant(db, KEY, {
ownerKind: 'mcpserver',
@@ -89,9 +93,37 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
provider: 'google',
accessToken: 'shared-at',
refreshToken: 'shared-rt',
+ crUid: U,
})
expect(inserted).toBe(true)
+ // A LEGACY gdrive grant (cr_uid NULL — written before install identity): purged too.
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive',
+ userId: 'user-legacy',
+ oauthClientId: 'google-drive',
+ provider: 'google',
+ accessToken: 'at-legacy',
+ refreshToken: 'rt-legacy',
+ })
+
+ // A gdrive grant of a DIFFERENT installation (uid U′ — a reinstall's consent): MUST survive.
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive',
+ userId: 'user-reinstall',
+ oauthClientId: 'google-drive',
+ provider: 'google',
+ accessToken: 'at-reinstall',
+ refreshToken: 'rt-reinstall',
+ crUid: U_PRIME,
+ })
+
// Peer server 'teamdrive': a grant that MUST survive the gdrive purge.
await upsertOAuthGrant(db, KEY, {
grantKind: 'user',
@@ -103,15 +135,18 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
provider: 'google',
accessToken: 'at-peer',
refreshToken: 'rt-peer',
+ crUid: U,
})
const purged = await deleteOAuthGrantsForServer(db, {
recipeNamespace: NS,
recipeName: 'gdrive',
+ crUid: U,
})
- expect(purged).toBe(2)
+ // U's user + U's shared + the legacy row = 3. U′'s grant is NOT counted.
+ expect(purged).toBe(3)
- // Observable state (T4): both gdrive flavors are gone …
+ // Observable state (T4): both U-sealed gdrive flavors and the legacy row are gone …
expect(
await oauthGrantExists(db, {
grantKind: 'user',
@@ -132,6 +167,27 @@ describeRealPostgres('deleteOAuthGrantsForServer — full server-scoped wipe (re
oauthClientId: 'google-drive',
})
).toBe(false)
+ expect(
+ await oauthGrantExists(db, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive',
+ userId: 'user-legacy',
+ oauthClientId: 'google-drive',
+ })
+ ).toBe(false)
+ // … the DIFFERENT-uid gdrive grant (the reinstall's) SURVIVES (R3-H5 fence) …
+ expect(
+ await oauthGrantExists(db, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive',
+ userId: 'user-reinstall',
+ oauthClientId: 'google-drive',
+ })
+ ).toBe(true)
// … and the peer server's grant is untouched (scoped purge, no blast radius).
expect(
await oauthGrantExists(db, {
diff --git a/control-api/test/oauth.dynamicClientStore.test.ts b/control-api/test/oauth.dynamicClientStore.test.ts
index c7b665c9f..e4abd2ed7 100644
--- a/control-api/test/oauth.dynamicClientStore.test.ts
+++ b/control-api/test/oauth.dynamicClientStore.test.ts
@@ -2,11 +2,7 @@ import { describe, expect, it } from 'vitest'
import fc from 'fast-check'
import { config } from '../src/config.js'
import type { DbClient } from '../src/db.js'
-import {
- deleteDynamicClient,
- getDynamicClient,
- upsertDynamicClient,
-} from '../src/oauth/dynamicClientStore.js'
+import { getDynamicClient, upsertDynamicClient } from '../src/oauth/dynamicClientStore.js'
import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
import { makeInMemoryDynamicClientsDb } from './fixtures/remoteOAuthDiscovery.js'
@@ -81,20 +77,6 @@ describe('dynamicClientStore — upsert SQL + encryption at rest', () => {
expect(calls[0].values[6]).toBeNull()
expect(calls[0].values[7]).toBeNull()
})
-
- it('delete is a hard DELETE keyed by owner coordinates, returning rowCount (idempotent)', async () => {
- const { db, calls } = fakeDb([], 0)
- const removed = await deleteDynamicClient(db, CONF_KEY)
- expect(removed).toBe(0)
- expect(calls[0].text).toContain('DELETE FROM dynamic_clients')
- expect(calls[0].values).toEqual(['mcpserver', 'mcp-server', 'vercel-remote'])
- })
-
- it('defaults ownerKind to mcpserver when omitted', async () => {
- const { db, calls } = fakeDb([], 1)
- await deleteDynamicClient(db, { serverNamespace: 'mcp-server', serverName: 'x' })
- expect(calls[0].values[0]).toBe('mcpserver')
- })
})
describe('dynamicClientStore — round-trip (T1: envelope from the real producer)', () => {
diff --git a/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
new file mode 100644
index 000000000..029574212
--- /dev/null
+++ b/control-api/test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
@@ -0,0 +1,371 @@
+import { afterAll, beforeAll, describe, expect, it } from 'vitest'
+import { randomUUID } from 'node:crypto'
+import { Pool } from 'pg'
+import { config } from '../src/config.js'
+import type { DbClient } from '../src/db.js'
+import { initDb } from '../src/db.js'
+import {
+ type UpsertDynamicClientInput,
+ bindDynamicClientToResource,
+ getDynamicClient,
+ insertDynamicClientPending,
+} from '../src/oauth/dynamicClientStore.js'
+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { teardownMcpServerOAuthState } from '../src/oauth/mcpServerOAuthTeardown.js'
+import {
+ bootstrapSharedOAuthGrant,
+ oauthGrantExists,
+ upsertOAuthGrant,
+} from '../src/oauth/store.js'
+import { rootLogger } from '../src/observability/logger.js'
+import { makeDcrTransport } from './fixtures/remoteOAuthDiscovery.js'
+
+/**
+ * R3-H5 (T1/T3/T4) — the uninstall OAuth teardown fenced by the CR uid, observed as
+ * SURVIVING ROWS and the exact RFC 7592 DELETE fired (T4), never as SQL text. All
+ * rows are seeded by the REAL producers (insertDynamicClientPending + bind for DCR;
+ * upsert/bootstrap for grants) and read through the REAL readers (T1).
+ *
+ * Gated on a real Postgres:
+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<u>:<p>@<host>:5432/<db> npm test -- \
+ * test/oauth.mcpServerOAuthTeardown.realPostgres.integration.test.ts
+ */
+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URL
+const describeRealPostgres = adminUrl ? describe : describe.skip
+
+function databaseUrl(baseUrl: string, database: string): string {
+ const url = new URL(baseUrl)
+ url.pathname = `/${database}`
+ return url.toString()
+}
+
+const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
+const NS = config.mcpServersNamespace
+const PUBLIC_IP = async () => ['93.184.216.34']
+
+describeRealPostgres('teardownMcpServerOAuthState — fenced by cr_uid (real Postgres)', () => {
+ const database = `control_api_teardown_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ const dcrCreds = (serverName: string, tag: string): UpsertDynamicClientInput => ({
+ serverNamespace: NS,
+ serverName,
+ issuer: 'https://as.example.com',
+ clientId: `cid-${tag}`,
+ clientMode: 'confidential',
+ clientSecret: `secret-${tag}`,
+ registrationAccessToken: `rat-${tag}`,
+ registrationClientUri: `https://as.example.com/register/${tag}`,
+ })
+
+ it('deletes the U-bound dynamic client and revokes ONLY its client', async () => {
+ const name = `srv-tp-own-${randomUUID().slice(0, 8)}`
+ const install = randomUUID()
+ const U = randomUUID()
+ await insertDynamicClientPending(db, KEY, { ...dcrCreds(name, 'own'), installId: install })
+ await bindDynamicClientToResource(db, { serverNamespace: NS, serverName: name }, install, U)
+
+ const { transport, calls } = makeDcrTransport({ responseJson: '' })
+ const result = await teardownMcpServerOAuthState(
+ db,
+ KEY,
+ { transport, resolveDns: PUBLIC_IP },
+ { namespace: NS, name, crUid: U },
+ rootLogger
+ )
+
+ expect(result.dynamicClient).toBe('done')
+ expect(await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })).toBeNull()
+ // Exactly this row's client was revoked at the AS.
+ const deletes = calls.filter(c => c.method === 'DELETE').map(c => c.url)
+ expect(deletes).toEqual(['https://as.example.com/register/own'])
+ })
+
+ // Window B: the reinstall (uid U′) wrote its row BEFORE the old teardown ran. The
+ // name-only teardown would read+revoke THIS new client; the fenced one leaves it be.
+ it('leaves a reinstall row (uid U′) intact and does NOT revoke its client (Window B)', async () => {
+ const name = `srv-tp-reinstall-${randomUUID().slice(0, 8)}`
+ const install = randomUUID()
+ const Uprime = randomUUID()
+ const U = randomUUID() // the uninstalled (older) install's uid
+ await insertDynamicClientPending(db, KEY, {
+ ...dcrCreds(name, 'reinstall'),
+ installId: install,
+ })
+ await bindDynamicClientToResource(
+ db,
+ { serverNamespace: NS, serverName: name },
+ install,
+ Uprime
+ )
+
+ const { transport, calls } = makeDcrTransport({ responseJson: '' })
+ const result = await teardownMcpServerOAuthState(
+ db,
+ KEY,
+ { transport, resolveDns: PUBLIC_IP },
+ { namespace: NS, name, crUid: U },
+ rootLogger
+ )
+
+ // The reinstall's row is a DIFFERENT uid → not claimed → 'none'.
+ expect(result.dynamicClient).toBe('none')
+ const survivor = await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })
+ expect(survivor?.crUid).toBe(Uprime)
+ expect(calls.filter(c => c.method === 'DELETE')).toHaveLength(0)
+ })
+
+ it('deletes a legacy dynamic client row (both identity columns NULL)', async () => {
+ const name = `srv-tp-legacy-${randomUUID().slice(0, 8)}`
+ const install = randomUUID()
+ await insertDynamicClientPending(db, KEY, { ...dcrCreds(name, 'legacy'), installId: install })
+ // Emulate a pre-0119 legacy row: null the identity columns the migration added
+ // (the encrypted creds still came from the real producer above).
+ await db.query(
+ `UPDATE dynamic_clients SET install_id = NULL, cr_uid = NULL
+ WHERE owner_kind = 'mcpserver' AND server_namespace = $1 AND server_name = $2`,
+ [NS, name]
+ )
+
+ const { transport, calls } = makeDcrTransport({ responseJson: '' })
+ const result = await teardownMcpServerOAuthState(
+ db,
+ KEY,
+ { transport, resolveDns: PUBLIC_IP },
+ { namespace: NS, name, crUid: randomUUID() },
+ rootLogger
+ )
+ expect(result.dynamicClient).toBe('done')
+ expect(await getDynamicClient(db, KEY, { serverNamespace: NS, serverName: name })).toBeNull()
+ expect(calls.filter(c => c.method === 'DELETE').map(c => c.url)).toEqual([
+ 'https://as.example.com/register/legacy',
+ ])
+ })
+
+ it('purges this uid + legacy grants and spares a reinstall grant (uid U′)', async () => {
+ const name = `srv-tp-grants-${randomUUID().slice(0, 8)}`
+ const U = randomUUID()
+ const Uprime = randomUUID()
+
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId: 'user-u',
+ oauthClientId: 'client',
+ provider: 'google',
+ accessToken: 'at-u',
+ crUid: U,
+ })
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId: 'user-legacy',
+ oauthClientId: 'client',
+ provider: 'google',
+ accessToken: 'at-legacy',
+ // no crUid → legacy row
+ })
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId: 'user-reinstall',
+ oauthClientId: 'client',
+ provider: 'google',
+ accessToken: 'at-reinstall',
+ crUid: Uprime,
+ })
+
+ const { transport } = makeDcrTransport({ responseJson: '' })
+ const result = await teardownMcpServerOAuthState(
+ db,
+ KEY,
+ { transport, resolveDns: PUBLIC_IP },
+ { namespace: NS, name, crUid: U },
+ rootLogger
+ )
+ expect(result.grants).toBe('done')
+
+ const exists = (userId: string) =>
+ oauthGrantExists(db, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId,
+ oauthClientId: 'client',
+ })
+ expect(await exists('user-u')).toBe(false)
+ expect(await exists('user-legacy')).toBe(false)
+ // The reinstall's grant (uid U′) survives (R3-H5).
+ expect(await exists('user-reinstall')).toBe(true)
+ })
+
+ it('a server with no OAuth state is a clean no-op (none/none, no revoke)', async () => {
+ const name = `srv-tp-clean-${randomUUID().slice(0, 8)}`
+ const { transport, calls } = makeDcrTransport({ responseJson: '' })
+ const result = await teardownMcpServerOAuthState(
+ db,
+ KEY,
+ { transport, resolveDns: PUBLIC_IP },
+ { namespace: NS, name, crUid: randomUUID() },
+ rootLogger
+ )
+ expect(result).toEqual({ dynamicClient: 'none', grants: 'none' })
+ expect(calls.filter(c => c.method === 'DELETE')).toHaveLength(0)
+ })
+})
+
+// D-T3: the callback-side producer semantics that seal grants to an installation.
+describeRealPostgres('grant cr_uid sealing (D-T3, real Postgres)', () => {
+ const database = `control_api_sealing_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+
+ beforeAll(async () => {
+ if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')
+ adminPool = new Pool({ connectionString: adminUrl })
+ await adminPool.query(`CREATE DATABASE "${database.replace(/"/g, '""')}"`)
+ dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })
+ await initDb({ connect: () => dbPool.connect() })
+ db = { query: (text, values) => dbPool.query(text, values) }
+ })
+
+ afterAll(async () => {
+ await dbPool?.end()
+ if (adminPool) {
+ await adminPool.query(
+ `SELECT pg_terminate_backend(pid) FROM pg_stat_activity
+ WHERE datname = $1 AND pid <> pg_backend_pid()`,
+ [database]
+ )
+ await adminPool.query(`DROP DATABASE IF EXISTS "${database.replace(/"/g, '""')}"`)
+ await adminPool.end()
+ }
+ })
+
+ async function grantCrUid(name: string, contextId?: string): Promise<string | null> {
+ const res = await dbPool.query(
+ contextId
+ ? `SELECT cr_uid FROM oauth_grants WHERE owner_kind='mcpserver' AND recipe_namespace=$1
+ AND recipe_name=$2 AND context_id=$3 AND grant_kind='shared'`
+ : `SELECT cr_uid FROM oauth_grants WHERE owner_kind='mcpserver' AND recipe_namespace=$1
+ AND recipe_name=$2 AND grant_kind='user'`,
+ contextId ? [NS, name, contextId] : [NS, name]
+ )
+ return (res.rows[0] as { cr_uid: string | null }).cr_uid
+ }
+
+ it('upsertOAuthGrant (user) seals cr_uid and re-seals it on the latest consent', async () => {
+ const name = `srv-seal-user-${randomUUID().slice(0, 8)}`
+ const U = randomUUID()
+ const Uprime = randomUUID()
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId: 'user-a',
+ oauthClientId: 'client',
+ provider: 'google',
+ accessToken: 'at-1',
+ crUid: U,
+ })
+ expect(await grantCrUid(name)).toBe(U)
+ // A later consent (reinstall) re-seals the SAME row with the new uid.
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ userId: 'user-a',
+ oauthClientId: 'client',
+ provider: 'google',
+ accessToken: 'at-2',
+ crUid: Uprime,
+ })
+ expect(await grantCrUid(name)).toBe(Uprime)
+ })
+
+ it('bootstrapSharedOAuthGrant: same uid → no replace; different uid / legacy → replace', async () => {
+ const name = `srv-seal-shared-${randomUUID().slice(0, 8)}`
+ const ctx = 'ctx-A'
+ const U = randomUUID()
+ const Uprime = randomUUID()
+
+ const first = await bootstrapSharedOAuthGrant(db, KEY, {
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ contextId: ctx,
+ oauthClientId: 'client',
+ bootstrappedByUserId: 'user-a',
+ provider: 'google',
+ accessToken: 'shared-1',
+ crUid: U,
+ })
+ expect(first.inserted).toBe(true)
+ expect(await grantCrUid(name, ctx)).toBe(U)
+
+ // Same uid, second member of the SAME install → first bootstrapper wins (no replace).
+ const sameUid = await bootstrapSharedOAuthGrant(db, KEY, {
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ contextId: ctx,
+ oauthClientId: 'client',
+ bootstrappedByUserId: 'user-b',
+ provider: 'google',
+ accessToken: 'shared-2',
+ crUid: U,
+ })
+ expect(sameUid.inserted).toBe(false)
+ expect(await grantCrUid(name, ctx)).toBe(U)
+
+ // Different uid (reinstall) → this is not the same install's first bootstrapper;
+ // the stale row is replaced and re-sealed to the new uid.
+ const otherUid = await bootstrapSharedOAuthGrant(db, KEY, {
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: name,
+ contextId: ctx,
+ oauthClientId: 'client',
+ bootstrappedByUserId: 'user-c',
+ provider: 'google',
+ accessToken: 'shared-3',
+ crUid: Uprime,
+ })
+ expect(otherUid.inserted).toBe(true)
+ expect(await grantCrUid(name, ctx)).toBe(Uprime)
+ })
+})
diff --git a/control-api/test/oauth.store.sharedGrants.test.ts b/control-api/test/oauth.store.sharedGrants.test.ts
index 70096ef45..de4373886 100644
--- a/control-api/test/oauth.store.sharedGrants.test.ts
+++ b/control-api/test/oauth.store.sharedGrants.test.ts
@@ -40,7 +40,7 @@ const SHARED_KEY = {
}
describe('oauth store — shared (context-identity) grants', () => {
- it('bootstrapSharedOAuthGrant issues INSERT … ON CONFLICT DO NOTHING with bootstrapped_by, returns inserted', async () => {
+ it('bootstrapSharedOAuthGrant issues INSERT … ON CONFLICT DO UPDATE fenced by cr_uid, returns inserted', async () => {
const { db, calls } = fakeDb([{ id: 1 }], 1)
const out = await bootstrapSharedOAuthGrant(db, KEY, {
...SHARED_KEY,
@@ -49,14 +49,19 @@ describe('oauth store — shared (context-identity) grants', () => {
accessToken: 'A',
refreshToken: 'R',
accessTokenExpiresInSec: 3600,
+ crUid: 'uid-1',
})
expect(out.inserted).toBe(true)
expect(calls[0].text).toContain('INSERT INTO oauth_grants')
expect(calls[0].text).toContain('ON CONFLICT')
- expect(calls[0].text).toContain('DO NOTHING')
+ // R3-H5: same-uid conflict no-ops (first bootstrapper wins), a DIFFERENT uid /
+ // legacy row is replaced — expressed as DO UPDATE guarded on cr_uid DISTINCT.
+ expect(calls[0].text).toContain('DO UPDATE SET')
+ expect(calls[0].text).toContain('oauth_grants.cr_uid IS DISTINCT FROM EXCLUDED.cr_uid')
expect(calls[0].text).toContain('bootstrapped_by_user_id')
expect(calls[0].text).toContain("'shared'")
- // owner, ns, name, contextId, clientId, bootstrappedBy are bound in order.
+ // owner, ns, name, contextId, clientId, bootstrappedBy are bound in order,
+ // and cr_uid is the last bound param.
expect(calls[0].values.slice(0, 6)).toEqual([
'mcpserver',
'mcp-server',
@@ -65,6 +70,7 @@ describe('oauth store — shared (context-identity) grants', () => {
'google-drive',
'user-1',
])
+ expect((calls[0].values as unknown[]).at(-1)).toBe('uid-1')
})
it('bootstrapSharedOAuthGrant reports inserted=false when the conflict no-ops', async () => {
diff --git a/control-api/test/routes.resources.test.ts b/control-api/test/routes.resources.test.ts
index 99d30c283..f832d3e67 100644
--- a/control-api/test/routes.resources.test.ts
+++ b/control-api/test/routes.resources.test.ts
@@ -1244,6 +1244,10 @@ describe('routes/resources', () => {
config.mcpServersNamespace = 'mcpservers-ns'
const gateway = {
+ // The uninstall reads the CR before deleting to capture metadata.uid (R3-H5).
+ getResource: vi
+ .fn()
+ .mockResolvedValue({ metadata: { name: 'mcp-a', uid: 'uid-mcp-a', resourceVersion: '1' } }),
deleteResource: vi.fn().mockResolvedValue({ deleted: true }),
deleteSecret: vi.fn().mockResolvedValue({ deleted: true }),
listResource: vi.fn().mockResolvedValue([
@@ -1262,7 +1266,10 @@ describe('routes/resources', () => {
await request(app).delete('/admin/mcp-servers/mcp-a').expect(200)
- expect(gateway.deleteResource).toHaveBeenCalledWith('mcpservers', 'mcp-a', 'mcpservers-ns')
+ // The CR delete is now fenced on the uid read back before deletion (R3-H5).
+ expect(gateway.deleteResource).toHaveBeenCalledWith('mcpservers', 'mcp-a', 'mcpservers-ns', {
+ uid: 'uid-mcp-a',
+ })
expect(gateway.listResource).toHaveBeenCalledWith('contexts', 'contexts-ns')
expect(gateway.updateResource).toHaveBeenCalledWith(
'contexts',