Skip to content

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

TypeScript

feat(connectors): end-user disconnect endpoint for mcp-server grants (U4)

Diego Zacarias08290222eaf2
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index a08b64823..57623924d 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.499",
+ "version": "0.1.500",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.499",
+ "version": "0.1.500",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/image-policy": "file:../packages/image-policy",
diff --git a/control-api/package.json b/control-api/package.json
index 842aace95..8c4e58254 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.499",
+ "version": "0.1.500",
"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/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.ts
index 4047036a0..f80302fd2 100644
--- a/control-api/src/oauth/mcpServerOAuthSpec.ts
+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts
@@ -8,6 +8,7 @@
* - the rpc-proxy grant-presence gate (`services/access/mcpInvocable.ts`).
* Both read the SAME fields the SAME way, so the rule lives here once.
*/
+import type { GetOAuthGrantInput } from './store.js'
export interface McpServerOAuthDecl {
id?: unknown
@@ -56,6 +57,55 @@ export function resolveServerOAuth(server: McpServerOAuthSpecInput): ResolvedSer
return { oauthClientId: oauth.id, grantScope, contextRef }
}
+/**
+ * Build the `oauth_grants` key for an OAuth mcp-server, BY FLAVOR — the single
+ * construction shared by every seam that touches a server's grant row (D4/F2):
+ * - the rpc-proxy grant-presence gate (`computeGrantPresence`) — read;
+ * - the end-user disconnect endpoint (`internal/oauth.ts`) — delete.
+ * Keeping the key derivation here (next to `resolveServerOAuth`) means the two
+ * never drift, and a `grantScope` we don't recognize fails closed in ONE place.
+ *
+ * - `user` → per-user key `(mcpserver, ns, server, userId, oauthClientId)`.
+ * - `context` → shared key `(mcpserver, ns, server, contextRef, oauthClientId)`,
+ * `user_id NULL`; the `contextId` is the server's AUTHORITATIVE `spec.contextRef`
+ * (resolved server-side), NEVER a caller-supplied value.
+ *
+ * Returns null (fail-closed) when the key cannot be built:
+ * - a `context`-scope server without a `contextRef`, or
+ * - an unrecognized `grantScope`.
+ * A null return must be treated as "cannot act on this grant" — never as a
+ * broad/blind delete.
+ */
+export function buildMcpServerGrantKey(
+ resolved: Pick<ResolvedServerOAuth, 'grantScope' | 'oauthClientId' | 'contextRef'>,
+ coords: { namespace: string; serverName: string; userId: string }
+): GetOAuthGrantInput | null {
+ if (resolved.grantScope === 'user') {
+ return {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: coords.namespace,
+ recipeName: coords.serverName,
+ userId: coords.userId,
+ oauthClientId: resolved.oauthClientId,
+ }
+ }
+ if (resolved.grantScope === 'context') {
+ // fail-closed: a context-identity server MUST carry its authoritative Context.
+ if (!resolved.contextRef) return null
+ return {
+ grantKind: 'shared',
+ ownerKind: 'mcpserver',
+ recipeNamespace: coords.namespace,
+ recipeName: coords.serverName,
+ contextId: resolved.contextRef,
+ oauthClientId: resolved.oauthClientId,
+ }
+ }
+ // Unknown grantScope → fail-closed.
+ return null
+}
+
/**
* The `spec.oauth` declaration in the `oauthClients[]`-compatible shape the
* consent flow (U5: authorize-URL mint + callback) consumes, plus the grant
diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.ts
index b729f5551..9f07d1bd7 100644
--- a/control-api/src/routes/internal/oauth.ts
+++ b/control-api/src/routes/internal/oauth.ts
@@ -17,6 +17,8 @@ import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'
import { integrationNotConfigured, isSecretNotFound } from '../../oauth/integrationNotConfigured.js'
import {
type McpServerOAuthSpecInput,
+ buildMcpServerGrantKey,
+ resolveServerOAuth,
resolveServerOAuthSubject,
} from '../../oauth/mcpServerOAuthSpec.js'
import { deleteOAuthGrant } from '../../oauth/store.js'
@@ -259,6 +261,131 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {
}
)
+ // ── U4 (spec 11): revoke an OAuth mcp-server grant from the desktop panel ──
+ //
+ // End-user "Disconnect <server>". rpc-proxy fronts this and forwards the
+ // session `userId` (auth.sub) over the mutually-authenticated seam
+ // (requireInternalService('rpc-proxy')) — NEVER a client-controlled param
+ // (invariant §1.4). The grant coordinate (oauthClientId + grantScope + the
+ // Context) is derived from the McpServer CR, never the body.
+ //
+ // Authorization BY FLAVOR (spec §2.3, mini-spec 05 §7):
+ // - `user` → the caller may only delete their OWN grant — the key is
+ // built on the forwarded `userId`, so a cross-user delete is structurally
+ // impossible.
+ // - `context` → any MEMBER of the server's Context may revoke the single
+ // shared grant → blast-radius: the WHOLE Context is disconnected.
+ //
+ // The Context-membership gate runs for EVERY grantScope, using the SAME
+ // primitive as the authorize-URL mint and the callback bootstrap
+ // (`getUserContexts` → user_contexts), so membership authz lives in ONE place
+ // (D4). Fail-closed: a server with no usable OAuth id, no `contextRef`, or a
+ // caller who is not a Context member is rejected — the grant is NEVER deleted
+ // blindly.
+ //
+ // Idempotent: deleting a grant that does not exist returns 204 (matching the
+ // sandbox-ui grant delete below). We deliberately do NOT surface "no grant
+ // existed" as a distinct status — the desktop treats disconnect as idempotent,
+ // and a 404 would leak which (server, user/context) pairs are connected.
+ router.delete(
+ '/internal/mcp-oauth/grant',
+ requireInternalService('rpc-proxy'),
+ async (req, res, next) => {
+ try {
+ const { mcpServerName, userId, contextId } = (req.body ?? {}) as {
+ mcpServerName?: unknown
+ userId?: unknown
+ contextId?: unknown
+ }
+ if (typeof mcpServerName !== 'string' || !isValidK8sName(mcpServerName)) {
+ return res.status(400).json({ error: 'invalid_request' })
+ }
+ if (typeof userId !== 'string' || userId.length === 0) {
+ return res.status(400).json({ error: 'invalid_request' })
+ }
+ if (contextId !== undefined && typeof contextId !== 'string') {
+ return res.status(400).json({ error: 'invalid_request' })
+ }
+
+ // Read the server to derive the grant coordinate. Never trust the body.
+ let server: McpServerAuthResource
+ try {
+ server = (await gateway.getResource(
+ 'mcpservers',
+ mcpServerName,
+ config.mcpServersNamespace
+ )) as McpServerAuthResource
+ } catch (err) {
+ if (err instanceof K8sNotFoundError) {
+ return res.status(404).json({ error: 'server_not_found' })
+ }
+ throw err
+ }
+
+ const authType = server?.spec?.auth?.type
+ // `resolveServerOAuth` (not …Subject): revoke only needs the grant
+ // coordinate, not the client-secret refs — a server whose Secret rotated
+ // away must still be disconnectable. Gate on `auth.type==='oauth'` to
+ // stay aligned with the U1 classifier / grant-presence gate.
+ const resolved = authType === 'oauth' ? resolveServerOAuth(server) : null
+ if (!resolved) {
+ return res.status(400).json({ error: 'not_oauth_server' })
+ }
+
+ // Context-identity servers: the AUTHORITATIVE Context is spec.contextRef.
+ // A body contextId, if present, must match it (cross-context guard).
+ if (resolved.grantScope === 'context') {
+ if (!resolved.contextRef) {
+ return res.status(400).json({ error: 'server_missing_context' })
+ }
+ if (typeof contextId === 'string' && contextId !== resolved.contextRef) {
+ return res.status(400).json({ error: 'context_mismatch' })
+ }
+ }
+
+ // Universal Context-membership gate (every grantScope) — same rule +
+ // primitive as the authorize-URL mint (D4). `spec.contextRef` is
+ // CRD-required + singular; a server that somehow lacks it cannot be
+ // membership-verified → fail closed.
+ if (!resolved.contextRef) {
+ return res.status(403).json({ error: 'context_membership_denied' })
+ }
+ const { contextIds } = await getUserContexts(userId)
+ if (!contextIds.includes(resolved.contextRef)) {
+ return res.status(403).json({ error: 'context_membership_denied' })
+ }
+
+ // Build the flavored delete key from the SAME source of truth the
+ // grant-presence gate reads by (D4/F2). null ⇒ fail-closed.
+ const key = buildMcpServerGrantKey(resolved, {
+ namespace: config.mcpServersNamespace,
+ serverName: mcpServerName,
+ userId,
+ })
+ if (!key) {
+ return res.status(400).json({ error: 'server_missing_context' })
+ }
+
+ await deleteOAuthGrant({ query: (text, values) => pool.query(text, values) }, key)
+
+ // Audit trail (sensitive: a revocation). Structured, pino-redacted; no
+ // tokens/secrets are read or logged here.
+ req.log?.info(
+ {
+ event: 'mcp_oauth_grant_revoked',
+ mcpServerName,
+ grantScope: resolved.grantScope,
+ oauthClientId: resolved.oauthClientId,
+ },
+ 'mcp oauth grant revoked'
+ )
+ return res.status(204).end()
+ } catch (err) {
+ next(err)
+ }
+ }
+ )
+
router.post(
'/internal/sandbox-ui/oauth/authorize-url',
requireInternalService('rpc-proxy'),
diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.ts
index e46b996e3..c5831dd35 100644
--- a/control-api/src/services/access/mcpInvocable.ts
+++ b/control-api/src/services/access/mcpInvocable.ts
@@ -26,7 +26,11 @@
*/
import type { DbClient } from '../../db.js'
import type { K8sGateway } from '../../k8s.js'
-import { type GrantScope, resolveServerOAuth } from '../../oauth/mcpServerOAuthSpec.js'
+import {
+ type GrantScope,
+ buildMcpServerGrantKey,
+ resolveServerOAuth,
+} from '../../oauth/mcpServerOAuthSpec.js'
import { oauthGrantExists } from '../../oauth/store.js'
import { rootLogger } from '../../observability/logger.js'
import {
@@ -262,41 +266,29 @@ async function computeGrantPresence(
const resolved = resolveServerOAuth(s)
if (!resolved) continue // fail-closed: no usable oauth id
+ // Flavored grant key — the SAME construction the disconnect endpoint deletes
+ // by (D4/F2). null ⇒ fail-closed (context server without contextRef, or an
+ // unknown grantScope): the server is simply not added to the present set.
+ // The shared-identity `context` branch is keyed by the server's AUTHORITATIVE
+ // Context (`spec.contextRef`), decoupled from the caller's userId
+ // (mini-spec 04 §2 3b); exercised end-to-end by U6(api).
+ const key = buildMcpServerGrantKey(resolved, {
+ namespace: mcpServersNamespace,
+ serverName: name,
+ userId: callerUserId,
+ })
+ if (!key) continue
+
try {
- let exists = false
- if (resolved.grantScope === 'user') {
- exists = await oauthGrantExists(db, {
- grantKind: 'user',
- ownerKind: 'mcpserver',
- recipeNamespace: mcpServersNamespace,
- recipeName: name,
- userId: callerUserId,
- oauthClientId: resolved.oauthClientId,
- })
- } else if (resolved.grantScope === 'context') {
- // Shared identity is keyed by the server's AUTHORITATIVE Context
- // (`spec.contextRef`), DECOUPLED from the caller's userId (mini-spec 04
- // §2 3b). Exercised end-to-end by U6(api).
- if (!resolved.contextRef) continue // fail-closed: context server without contextRef
- exists = await oauthGrantExists(db, {
- grantKind: 'shared',
- ownerKind: 'mcpserver',
- recipeNamespace: mcpServersNamespace,
- recipeName: name,
- contextId: resolved.contextRef,
- oauthClientId: resolved.oauthClientId,
- })
- }
- // Any other grantScope is unknown → fail-closed (exists stays false).
+ const exists = await oauthGrantExists(db, key)
if (exists) present.add(name)
} catch (err) {
// A grant-check DB error excludes THIS server (fail-closed) rather than
// failing the whole request — loudly, matching the sibling resolver's
// observable-degradation posture (`resolveMcpServersForAgents`).
- console.error(
- '[mcpInvocable] grant-presence check failed; server excluded from rpc-proxy rail:',
- name,
- err instanceof Error ? err.message : String(err)
+ connectorsLog.error(
+ { err, server: name },
+ 'grant-presence check failed; server excluded from rpc-proxy rail'
)
}
}
diff --git a/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts b/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
new file mode 100644
index 000000000..abd0ceb26
--- /dev/null
+++ b/control-api/test/oauth.mcpDisconnect.realPostgres.integration.test.ts
@@ -0,0 +1,174 @@
+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 { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'
+import { buildMcpServerGrantKey, resolveServerOAuth } from '../src/oauth/mcpServerOAuthSpec.js'
+import {
+ bootstrapSharedOAuthGrant,
+ deleteOAuthGrant,
+ oauthGrantExists,
+ upsertOAuthGrant,
+} from '../src/oauth/store.js'
+
+// T1/T4 — the disconnect composition (buildMcpServerGrantKey → deleteOAuthGrant)
+// exercised against grant rows built by the REAL producers (`upsertOAuthGrant` /
+// `bootstrapSharedOAuthGrant`) and observed through the REAL `oauthGrantExists`.
+// No hand-built oauth_grants rows. This is the exact key derivation + delete the
+// DELETE /internal/mcp-oauth/grant endpoint composes; the endpoint's authz gates
+// are covered by the route test (routes.internal.mcpOauthDisconnect.test.ts).
+// Gated on a real Postgres, like the U1 connectors integration test:
+// CONTROL_API_REAL_PG_ADMIN_URL=postgres://user:pass@host:5432 npm test -- \
+// test/oauth.mcpDisconnect.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
+
+/** A minimal McpServer CR, resolved through the REAL resolver the endpoint uses. */
+function resolvedFor(grantScope: 'user' | 'context', contextRef: string) {
+ const resolved = resolveServerOAuth({
+ spec: {
+ contextRef,
+ oauth: { id: 'google-drive', provider: 'google', grantScope },
+ },
+ })
+ if (!resolved) throw new Error('fixture server did not resolve to OAuth')
+ return resolved
+}
+
+describeRealPostgres('mcp-server grant disconnect composition (real Postgres)', () => {
+ const database = `control_api_mcpdisconnect_${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()
+ }
+ })
+
+ it('user flavor: deletes ONLY the caller-owned grant (a peer on the same server survives)', async () => {
+ const resolved = resolvedFor('user', 'ctx-9')
+ // Two members each connect the SAME user-scope server (real producer).
+ for (const userId of ['user-a', 'user-b']) {
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive',
+ userId,
+ oauthClientId: 'google-drive',
+ provider: 'google',
+ accessToken: `at-${userId}`,
+ refreshToken: `rt-${userId}`,
+ })
+ }
+
+ const keyA = buildMcpServerGrantKey(resolved, {
+ namespace: NS,
+ serverName: 'gdrive',
+ userId: 'user-a',
+ })
+ expect(keyA).not.toBeNull()
+ await deleteOAuthGrant(db, keyA!)
+
+ // Observable state (T4): user-a's grant is gone, user-b's is untouched.
+ expect(
+ await oauthGrantExists(db, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive',
+ userId: 'user-a',
+ oauthClientId: 'google-drive',
+ })
+ ).toBe(false)
+ expect(
+ await oauthGrantExists(db, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive',
+ userId: 'user-b',
+ oauthClientId: 'google-drive',
+ })
+ ).toBe(true)
+ })
+
+ it('context flavor: deletes the single shared grant for the whole Context', async () => {
+ const resolved = resolvedFor('context', 'ctx-A')
+ // First member bootstraps the shared identity (real producer).
+ const { inserted } = await bootstrapSharedOAuthGrant(db, KEY, {
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'teamdrive',
+ contextId: 'ctx-A',
+ oauthClientId: 'google-drive',
+ bootstrappedByUserId: 'user-a',
+ provider: 'google',
+ accessToken: 'shared-at',
+ refreshToken: 'shared-rt',
+ })
+ expect(inserted).toBe(true)
+
+ // A DIFFERENT member revokes: the key is decoupled from the caller's userId.
+ const key = buildMcpServerGrantKey(resolved, {
+ namespace: NS,
+ serverName: 'teamdrive',
+ userId: 'user-b',
+ })
+ expect(key).not.toBeNull()
+ await deleteOAuthGrant(db, key!)
+
+ expect(
+ await oauthGrantExists(db, {
+ grantKind: 'shared',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'teamdrive',
+ contextId: 'ctx-A',
+ oauthClientId: 'google-drive',
+ })
+ ).toBe(false)
+ })
+
+ it('context flavor without contextRef: key is null (fail-closed, never a blind delete)', () => {
+ const resolved = resolveServerOAuth({
+ spec: { oauth: { id: 'google-drive', provider: 'google', grantScope: 'context' } },
+ })
+ expect(resolved).not.toBeNull()
+ const key = buildMcpServerGrantKey(resolved!, {
+ namespace: NS,
+ serverName: 'gdrive',
+ userId: 'user-a',
+ })
+ expect(key).toBeNull()
+ })
+})
diff --git a/control-api/test/routes.internal.mcpOauthDisconnect.test.ts b/control-api/test/routes.internal.mcpOauthDisconnect.test.ts
new file mode 100644
index 000000000..3f6e98852
--- /dev/null
+++ b/control-api/test/routes.internal.mcpOauthDisconnect.test.ts
@@ -0,0 +1,233 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import request from 'supertest'
+import { createApp } from '../src/app.js'
+import { config } from '../src/config.js'
+import { MockGateway } from './mockGateway.js'
+
+/**
+ * U4 (spec 11) — internal endpoint that REVOKES an OAuth mcp-server grant from
+ * the desktop panel. rpc-proxy is the sole authorized caller
+ * (requireInternalService('rpc-proxy')); the `userId` is forwarded over that
+ * seam (rpc-proxy derives it from the session auth.sub). The grant coordinate
+ * (oauthClientId + grantScope + Context) comes from the McpServer CR, never the
+ * body.
+ *
+ * Authorization BY FLAVOR (the security invariant, §2.3):
+ * - `user` → the key is built on the forwarded userId, so a cross-user
+ * delete is structurally impossible.
+ * - `context` → membership in the server's Context is required (getUserContexts),
+ * and a non-member is rejected 403 with NO delete.
+ *
+ * These tests mock `pool.query` (SQL-shape assertions). The end-to-end delete
+ * against real grant rows built by the real producers is the sibling
+ * realPostgres integration test (T1/T4).
+ *
+ * T3: at the parent sha (5d9b22902) the route does not exist → Express answers
+ * 404, so both the 204 (delete) and 403 (authz) assertions fail there.
+ */
+
+const mockPoolQuery = vi.fn()
+vi.mock('../src/db.js', () => ({
+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },
+}))
+
+const MCP_NS = config.mcpServersNamespace
+const URL = '/api/v1/internal/mcp-oauth/grant'
+
+function seedOauthServer(
+ gateway: MockGateway,
+ opts: { name: string; grantScope?: 'user' | 'context'; contextRef?: string }
+): void {
+ void gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name: opts.name },
+ spec: {
+ contextRef: opts.contextRef ?? 'ctx-9',
+ auth: { type: 'oauth' },
+ oauth: {
+ id: 'google-drive',
+ provider: 'google',
+ clientIdRef: { name: 'google-creds', key: 'client-id' },
+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },
+ ...(opts.grantScope ? { grantScope: opts.grantScope } : {}),
+ },
+ },
+ },
+ MCP_NS
+ )
+}
+
+/**
+ * Route pool.query by SQL: membership lookups (getUserContexts) return the
+ * supplied contexts; the grant DELETE returns `rowCount`. Anything else is an
+ * empty result. Records the DELETE call so tests can assert the flavored key.
+ */
+function mockDb(opts: { memberContexts: string[]; deleteRowCount?: number }): void {
+ mockPoolQuery.mockImplementation((sql: unknown) => {
+ const text = typeof sql === 'string' ? sql : ''
+ if (text.includes('FROM user_contexts')) {
+ return Promise.resolve({
+ rows: opts.memberContexts.map(context_id => ({ context_id })),
+ rowCount: opts.memberContexts.length,
+ })
+ }
+ if (text.includes('DELETE FROM oauth_grants')) {
+ return Promise.resolve({ rows: [], rowCount: opts.deleteRowCount ?? 1 })
+ }
+ return Promise.resolve({ rows: [], rowCount: 0 })
+ })
+}
+
+function deleteCalls(): Array<[string, unknown[]]> {
+ return mockPoolQuery.mock.calls
+ .filter(([sql]) => typeof sql === 'string' && sql.includes('DELETE FROM oauth_grants'))
+ .map(([sql, params]) => [sql as string, (params ?? []) as unknown[]])
+}
+
+function del(app: ReturnType<typeof createApp>) {
+ return request(app)
+ .delete(URL)
+ .set('Authorization', 'Bearer dev-rpc-proxy-token')
+ .set('x-service-token', 'rpc-proxy')
+}
+
+describe('DELETE /api/v1/internal/mcp-oauth/grant (spec 11 U4)', () => {
+ let gateway: MockGateway
+ let app: ReturnType<typeof createApp>
+
+ beforeEach(() => {
+ gateway = new MockGateway(MCP_NS)
+ app = createApp(gateway as never)
+ mockPoolQuery.mockReset()
+ mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ })
+
+ it('401 without any service token', async () => {
+ seedOauthServer(gateway, { name: 'gdrive' })
+ const res = await request(app).delete(URL).send({ mcpServerName: 'gdrive', userId: 'user-1' })
+ expect(res.status).toBe(401)
+ expect(mockPoolQuery).not.toHaveBeenCalled()
+ })
+
+ it('401 for an authenticated NON-rpc-proxy service (external-rest-api)', async () => {
+ seedOauthServer(gateway, { name: 'gdrive' })
+ const res = await request(app)
+ .delete(URL)
+ .set('Authorization', 'Bearer dev-external-rest-api-token')
+ .set('x-service-token', 'external-rest-api')
+ .send({ mcpServerName: 'gdrive', userId: 'user-1' })
+ expect(res.status).toBe(401)
+ expect(mockPoolQuery).not.toHaveBeenCalled()
+ })
+
+ it('400 invalid_request when userId is absent', async () => {
+ seedOauthServer(gateway, { name: 'gdrive' })
+ const res = await del(app).send({ mcpServerName: 'gdrive' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_request')
+ expect(deleteCalls()).toHaveLength(0)
+ })
+
+ it('400 invalid_request for a malformed (non-k8s) server name', async () => {
+ const res = await del(app).send({ mcpServerName: 'Foo_Bar', userId: 'user-1' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_request')
+ })
+
+ it('404 server_not_found for an unknown server', async () => {
+ const res = await del(app).send({ mcpServerName: 'ghost', userId: 'user-1' })
+ expect(res.status).toBe(404)
+ expect(res.body.error).toBe('server_not_found')
+ })
+
+ it('400 not_oauth_server for a non-oauth server', async () => {
+ void gateway.createResource(
+ 'mcpservers',
+ { metadata: { name: 'plain' }, spec: { contextRef: 'ctx-9', auth: { type: 'none' } } },
+ MCP_NS
+ )
+ const res = await del(app).send({ mcpServerName: 'plain', userId: 'user-1' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('not_oauth_server')
+ expect(deleteCalls()).toHaveLength(0)
+ })
+
+ // ── user flavor ──────────────────────────────────────────────────────────
+
+ it('user flavor: a MEMBER revokes → 204 and deletes the (user, own-userId) grant', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
+ mockDb({ memberContexts: ['ctx-9'] })
+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-7' })
+ expect(res.status).toBe(204)
+
+ const calls = deleteCalls()
+ expect(calls).toHaveLength(1)
+ const [sql, params] = calls[0]
+ // user-flavor delete: owner_kind='mcpserver', grant_kind='user', keyed on
+ // the forwarded userId — a cross-user delete is structurally impossible.
+ expect(sql).toContain("grant_kind = 'user'")
+ // params order: [ownerKind, ns, serverName, userId, oauthClientId]
+ expect(params).toEqual(['mcpserver', MCP_NS, 'gdrive', 'user-7', 'google-drive'])
+ })
+
+ it('user flavor: a NON-member is rejected 403 and NOTHING is deleted', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
+ // user-8 belongs to other contexts, but NOT ctx-9.
+ mockDb({ memberContexts: ['ctx-other'] })
+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-8' })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('context_membership_denied')
+ expect(deleteCalls()).toHaveLength(0)
+ })
+
+ it('user flavor: idempotent — revoking an absent grant still returns 204', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user', contextRef: 'ctx-9' })
+ mockDb({ memberContexts: ['ctx-9'], deleteRowCount: 0 })
+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-7' })
+ expect(res.status).toBe(204)
+ expect(deleteCalls()).toHaveLength(1)
+ })
+
+ // ── context flavor ───────────────────────────────────────────────────────
+
+ it('context flavor: a MEMBER revokes → 204 and deletes the single (shared, contextRef) grant', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+ mockDb({ memberContexts: ['ctx-A'] })
+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-2' })
+ expect(res.status).toBe(204)
+
+ const calls = deleteCalls()
+ expect(calls).toHaveLength(1)
+ const [sql, params] = calls[0]
+ // context-flavor delete: shared grant keyed by the server's AUTHORITATIVE
+ // contextRef (ctx-A), user_id NULL — decoupled from the caller's userId.
+ expect(sql).toContain("grant_kind = 'shared'")
+ // params order: [ownerKind, ns, serverName, contextId, oauthClientId]
+ expect(params).toEqual(['mcpserver', MCP_NS, 'gdrive', 'ctx-A', 'google-drive'])
+ // The caller's userId is NEVER part of the shared delete key.
+ expect(params).not.toContain('user-2')
+ })
+
+ it('context flavor: a NON-member is rejected 403 and NOTHING is deleted', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+ mockDb({ memberContexts: ['ctx-other', 'ctx-else'] })
+ const res = await del(app).send({ mcpServerName: 'gdrive', userId: 'user-nomember' })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('context_membership_denied')
+ expect(deleteCalls()).toHaveLength(0)
+ })
+
+ it('context flavor: a cross-context body contextId is rejected 400 context_mismatch, before any delete', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })
+ mockDb({ memberContexts: ['ctx-A'] })
+ const res = await del(app).send({
+ mcpServerName: 'gdrive',
+ userId: 'user-2',
+ contextId: 'ctx-B',
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('context_mismatch')
+ expect(deleteCalls()).toHaveLength(0)
+ })
+})
diff --git a/control-api/test/services.access.mcpInvocable.grantGate.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.test.ts
index c5ed53853..4edbbf7fc 100644
--- a/control-api/test/services.access.mcpInvocable.grantGate.test.ts
+++ b/control-api/test/services.access.mcpInvocable.grantGate.test.ts
@@ -18,6 +18,17 @@ vi.mock('../src/oauth/store.js', async importActual => {
}
})
+// The resolver logs the fail-closed exclusion through the pino child logger
+// (`rootLogger.child({ module: 'mcp-connectors' })`), not console.*. Capture the
+// child's `.error` so the fail-closed-logging assertion survives the migration.
+const loggerMock = vi.hoisted(() => {
+ const error = vi.fn()
+ const noop = vi.fn()
+ const child = () => ({ error, info: noop, warn: noop, debug: noop, trace: noop, fatal: noop })
+ return { error, rootLogger: { child, error, info: noop, warn: noop, debug: noop } }
+})
+vi.mock('../src/observability/logger.js', () => ({ rootLogger: loggerMock.rootLogger }))
+
const { resolveInvocableMcpServersForContexts } =
await import('../src/services/access/mcpInvocable.js')
@@ -248,12 +259,12 @@ describe('resolveInvocableMcpServersForContexts — fail-closed + non-oauth', ()
if (input.recipeName === 'broken') throw new Error('db down')
return true // 'good'
})
- const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ loggerMock.error.mockClear()
const out = await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB)
// 'broken' excluded (fail-closed), 'plain' (none) + 'good' survive. Sorted.
expect(names(out)).toEqual(['good', 'plain'])
- expect(errSpy).toHaveBeenCalled()
- errSpy.mockRestore()
+ // Fail-closed exclusion is logged through the pino child logger (not console).
+ expect(loggerMock.error).toHaveBeenCalled()
})
})
diff --git a/deploy/base/control-plane/configmaps.yaml b/deploy/base/control-plane/configmaps.yaml
index 205a8dc7d..4ec74c053 100644
--- a/deploy/base/control-plane/configmaps.yaml
+++ b/deploy/base/control-plane/configmaps.yaml
@@ -248,6 +248,20 @@ data:
proxy_set_header X-Forwarded-Proto $scheme;
}
+ # spec 11 U4: revoke an OAuth mcp-server grant (desktop "Disconnect").
+ # rpc-proxy is the sole caller; requireInternalService('rpc-proxy') gates
+ # it at control-api.
+ location = /api/v1/internal/mcp-oauth/grant {
+ limit_except DELETE {
+ deny all;
+ }
+ proxy_pass http://control_api_upstream;
+ proxy_set_header Host $host;
+ proxy_set_header X-Real-IP $remote_addr;
+ proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
+ proxy_set_header X-Forwarded-Proto $scheme;
+ }
+
location / {
return 403;
}
diff --git a/external-rest-api/src/releaseManifest.ts b/external-rest-api/src/releaseManifest.ts
index c3976d9b5..f8cb283af 100644
--- a/external-rest-api/src/releaseManifest.ts
+++ b/external-rest-api/src/releaseManifest.ts
@@ -9,7 +9,7 @@ export type ReleaseManifest = {
export const releaseManifest: ReleaseManifest = {
releaseId: 'v0.7.0',
externalRestApiVersion: '0.1.81',
- rpcProxyVersion: '0.1.67',
+ rpcProxyVersion: '0.1.68',
desktopVersion: '0.7.0',
minimumDesktopVersion: '0.1.252',
}
diff --git a/rpc-proxy/package-lock.json b/rpc-proxy/package-lock.json
index 2c80408a8..ffcc37950 100644
--- a/rpc-proxy/package-lock.json
+++ b/rpc-proxy/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.67",
+ "version": "0.1.68",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-rpc-proxy",
- "version": "0.1.67",
+ "version": "0.1.68",
"dependencies": {
"cors": "^2.8.5",
"express": "^4.21.2",
diff --git a/rpc-proxy/package.json b/rpc-proxy/package.json
index 60d3cc078..8115c99b2 100644
--- a/rpc-proxy/package.json
+++ b/rpc-proxy/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-rpc-proxy",
- "version": "0.1.67",
+ "version": "0.1.68",
"description": "External-facing RPC proxy for tenant-scoped MCP access",
"main": "dist/main.js",
"engines": {
diff --git a/rpc-proxy/src/routes/mcpOauth.ts b/rpc-proxy/src/routes/mcpOauth.ts
index 4b972d8a6..1498610a8 100644
--- a/rpc-proxy/src/routes/mcpOauth.ts
+++ b/rpc-proxy/src/routes/mcpOauth.ts
@@ -116,5 +116,88 @@ export function createMcpOauthRouter(): Router {
}
)
+ // ── DELETE /api/v1/mcp-oauth/:mcpServerName/grant ─────────────────────────
+ //
+ // Desktop "Disconnect <server>" surface (spec 11 U4). Revokes the caller's
+ // OAuth grant for an mcp-server. Same auth chain as the authorize-URL mint:
+ // 1. `requireRpcAuth` — RPC JWT.
+ // 2. `requireScope('mcp:server:invoke')` — the SAME capability the desktop
+ // already holds to connect/invoke; revoking is the inverse of connecting,
+ // so no new scope is issued.
+ //
+ // rpc-proxy forwards IDENTITY only. control-api owns server→context
+ // resolution and the per-flavor authorization (user: own grant; context:
+ // Context membership) — this route never resolves a server's Context. The
+ // `userId` is `req.auth.sub`, never the body. An optional `{ contextId? }` is
+ // forwarded for control-api to cross-check against the server's authoritative
+ // `spec.contextRef`.
+ //
+ // Error propagation mirrors the authorize-URL route exactly:
+ // - 401 → rpc-proxy↔control-api service-token misconfig → coerce to 502 so
+ // the user does not read it as their own credential failure;
+ // - 403 → legitimate `context_membership_denied` → propagate verbatim;
+ // - 404 (`server_not_found`) / 400 (`not_oauth_server`, `context_mismatch`,
+ // `server_missing_context`, `invalid_request`) → propagate verbatim;
+ // - 204 → success (idempotent; empty body).
+ router.delete(
+ '/mcp-oauth/:mcpServerName/grant',
+ requireRpcAuth,
+ requireScope('mcp:server:invoke'),
+ async (req: AuthedRequest, res: Response) => {
+ const { mcpServerName } = req.params
+ if (!isValidK8sName(mcpServerName)) {
+ res.status(400).json({ error: 'invalid_request' })
+ return
+ }
+ const userId = req.auth!.sub
+ const contextId =
+ typeof req.body?.contextId === 'string' && req.body.contextId.trim().length > 0
+ ? String(req.body.contextId).trim()
+ : undefined
+
+ const upstreamUrl = `${config.controlApiBaseUrl.replace(/\/+$/, '')}/internal/mcp-oauth/grant`
+ let upstream: globalThis.Response
+ try {
+ upstream = await fetch(upstreamUrl, {
+ method: 'DELETE',
+ headers: {
+ authorization: `Bearer ${config.controlApiServiceToken}`,
+ 'x-service-token': config.controlApiServiceName,
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({
+ mcpServerName,
+ userId, // from req.auth.sub — never the body
+ ...(contextId ? { contextId } : {}),
+ }),
+ signal: AbortSignal.timeout(config.upstreamTimeoutMs),
+ })
+ } catch {
+ res.status(502).json({ error: 'control_api_unreachable' })
+ return
+ }
+
+ // 401 = service-token misconfig — do NOT surface as the user's own auth
+ // failure. 403 IS a legitimate membership denial → propagate.
+ if (upstream.status === 401) {
+ res.status(502).json({ error: 'control_api_auth_failed' })
+ return
+ }
+
+ // Success: control-api answers 204 (no body). Forward it verbatim.
+ if (upstream.ok) {
+ res.status(upstream.status).end()
+ return
+ }
+
+ // Forward the upstream JSON error verbatim.
+ const upstreamText = await upstream.text().catch(() => '')
+ res
+ .status(upstream.status)
+ .type(upstream.headers.get('content-type') ?? 'application/json')
+ .send(upstreamText)
+ }
+ )
+
return router
}
diff --git a/rpc-proxy/src/routes/mcpOauthDisconnect.test.ts b/rpc-proxy/src/routes/mcpOauthDisconnect.test.ts
new file mode 100644
index 000000000..c3f65ec9e
--- /dev/null
+++ b/rpc-proxy/src/routes/mcpOauthDisconnect.test.ts
@@ -0,0 +1,140 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { createMcpOauthRouter } from './mcpOauth.js'
+
+const authTokenMock = vi.hoisted(() => ({ verifyRpcToken: vi.fn() }))
+vi.mock('../authToken.js', () => authTokenMock)
+
+const VALID_CLAIMS = {
+ sub: 'user-uuid-123',
+ typ: 'user' as const,
+ accessScope: 'team' as const,
+ teamId: 'team-1',
+ scopes: ['mcp:server:invoke'],
+ hostRefs: ['h'],
+ jti: 'j1',
+ iat: 1,
+ exp: 9999999999,
+}
+
+const fetchSpy = vi.fn()
+
+function makeApp() {
+ const app = express()
+ app.use(express.json())
+ app.use('/api/v1', createMcpOauthRouter())
+ return app
+}
+
+function jsonResponse(status: number, body: unknown): Response {
+ return new Response(JSON.stringify(body), {
+ status,
+ headers: { 'content-type': 'application/json' },
+ })
+}
+
+const PATH = '/api/v1/mcp-oauth/gdrive/grant'
+
+beforeEach(() => {
+ authTokenMock.verifyRpcToken.mockReset()
+ authTokenMock.verifyRpcToken.mockReturnValue({ ...VALID_CLAIMS })
+ fetchSpy.mockReset()
+ vi.stubGlobal('fetch', fetchSpy)
+})
+
+afterEach(() => {
+ vi.unstubAllGlobals()
+})
+
+describe('DELETE /api/v1/mcp-oauth/:mcpServerName/grant (spec 11 U4 disconnect)', () => {
+ it('401 without a valid RPC JWT', async () => {
+ authTokenMock.verifyRpcToken.mockReturnValue(null)
+ await request(makeApp()).delete(PATH).expect(401)
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('403 when the token lacks the mcp:server:invoke scope', async () => {
+ authTokenMock.verifyRpcToken.mockReturnValue({ ...VALID_CLAIMS, scopes: ['sandbox:ui:view'] })
+ await request(makeApp()).delete(PATH).set('Authorization', 'Bearer t').expect(403)
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('400 for a malformed (non-k8s) server name, before any forward', async () => {
+ const res = await request(makeApp())
+ .delete('/api/v1/mcp-oauth/Foo_Bar/grant')
+ .set('Authorization', 'Bearer t')
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_request')
+ expect(fetchSpy).not.toHaveBeenCalled()
+ })
+
+ it('forwards userId=auth.sub (NOT the body) + contextId and returns 204 on upstream 204', async () => {
+ fetchSpy.mockResolvedValue(new Response(null, { status: 204 }))
+ const res = await request(makeApp())
+ .delete(PATH)
+ .set('Authorization', 'Bearer t')
+ // A body userId MUST be ignored — identity comes from auth.sub.
+ .send({ userId: 'attacker', contextId: 'ctx-A' })
+
+ expect(res.status).toBe(204)
+
+ expect(fetchSpy).toHaveBeenCalledTimes(1)
+ const [url, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
+ expect(url).toContain('/internal/mcp-oauth/grant')
+ expect(init.method).toBe('DELETE')
+ const headers = init.headers as Record<string, string>
+ expect(headers['x-service-token']).toBeTruthy()
+ expect(headers.authorization).toMatch(/^Bearer /)
+ const forwarded = JSON.parse(String(init.body))
+ expect(forwarded.mcpServerName).toBe('gdrive')
+ expect(forwarded.userId).toBe('user-uuid-123') // auth.sub, NOT 'attacker'
+ expect(forwarded.contextId).toBe('ctx-A')
+ })
+
+ it('omits contextId from the forward when the body has none', async () => {
+ fetchSpy.mockResolvedValue(new Response(null, { status: 204 }))
+ await request(makeApp()).delete(PATH).set('Authorization', 'Bearer t').send({})
+ const [, init] = fetchSpy.mock.calls[0] as [string, RequestInit]
+ const forwarded = JSON.parse(String(init.body))
+ expect('contextId' in forwarded).toBe(false)
+ })
+
+ it('propagates a 403 context_membership_denied from control-api verbatim', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(403, { error: 'context_membership_denied' }))
+ const res = await request(makeApp()).delete(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('context_membership_denied')
+ })
+
+ it('propagates a 404 server_not_found from control-api verbatim', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(404, { error: 'server_not_found' }))
+ const res = await request(makeApp()).delete(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(404)
+ expect(res.body.error).toBe('server_not_found')
+ })
+
+ it('propagates a 400 context_mismatch from control-api verbatim', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(400, { error: 'context_mismatch' }))
+ const res = await request(makeApp())
+ .delete(PATH)
+ .set('Authorization', 'Bearer t')
+ .send({ contextId: 'ctx-B' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('context_mismatch')
+ })
+
+ it('coerces a control-api 401 (service-token misconfig) to 502, not the user auth failure', async () => {
+ fetchSpy.mockResolvedValue(jsonResponse(401, { error: 'Unauthorized' }))
+ const res = await request(makeApp()).delete(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(502)
+ expect(res.body.error).toBe('control_api_auth_failed')
+ })
+
+ it('returns 502 when control-api is unreachable', async () => {
+ fetchSpy.mockRejectedValue(new Error('ECONNREFUSED'))
+ const res = await request(makeApp()).delete(PATH).set('Authorization', 'Bearer t').send({})
+ expect(res.status).toBe(502)
+ expect(res.body.error).toBe('control_api_unreachable')
+ })
+})