Skip to content

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

TypeScript

feat(control-api): add batch grant-existence endpoint for the revocation sweep

Diego Zacarias7025f8a177bf
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index c84f952c0..faefb55b7 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.501",
+ "version": "0.1.502",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.501",
+ "version": "0.1.502",
"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 4cd446747..072449e94 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.501",
+ "version": "0.1.502",
"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..5f233e7fc 100644
--- a/control-api/src/oauth/mcpServerOAuthSpec.ts
+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts
@@ -3,11 +3,15 @@
*
* The grant-scope / oauthClientId / contextRef derivation is a security-relevant
* rule (it decides WHICH grant coordinate governs a server). It is consumed by
- * two seams that must never drift apart (D4):
+ * three seams that must never drift apart (D4):
* - the token broker (`routes/mcpOauth.ts`) — the LLM/tool-call rail;
- * - the rpc-proxy grant-presence gate (`services/access/mcpInvocable.ts`).
- * Both read the SAME fields the SAME way, so the rule lives here once.
+ * - the rpc-proxy grant-presence gate (`services/access/mcpInvocable.ts`);
+ * - the grant-existence sweep (`routes/mcpOauth.ts`, mini-spec 13) — the
+ * hot-revocation poll.
+ * All read the SAME fields the SAME way and derive the SAME `oauth_grants` key
+ * (`buildMcpServerGrantKey`), so the rule lives here once.
*/
+import type { OAuthGrantKey } from './store.js'
export interface McpServerOAuthDecl {
id?: unknown
@@ -56,6 +60,61 @@ export function resolveServerOAuth(server: McpServerOAuthSpecInput): ResolvedSer
return { oauthClientId: oauth.id, grantScope, contextRef }
}
+/** The coordinates the caller supplies to derive an mcp-server grant key. */
+export interface McpServerGrantKeyCoords {
+ /** McpServer name — reinterpreted as the grant owner's `recipeName`. */
+ mcpServerName: string
+ /** The mcp-servers namespace — the grant owner's `recipeNamespace`. */
+ mcpServersNamespace: string
+ /**
+ * End-user identity, for `grantScope='user'` servers only. IGNORED for
+ * `context` servers, which key by the server's AUTHORITATIVE `contextRef`
+ * (server-side), never by any caller-supplied context value.
+ */
+ userId?: string
+}
+
+/**
+ * Derive the `oauth_grants` key for an OAuth McpServer by flavor — the SINGLE
+ * key derivation shared by the token mint, the rpc-proxy grant-presence gate,
+ * and the grant-existence sweep (D4: one authority, no drift). Returns null when
+ * the coordinate the flavor needs is absent, so every caller decides fail-open
+ * vs fail-closed for itself:
+ * - `user` → needs a non-empty `userId`; null otherwise.
+ * - `context` → keys by the server's AUTHORITATIVE `contextRef` (server-side,
+ * NEVER a body value); null when the server carries none.
+ *
+ * It intentionally does NOT read the token or touch the DB — it only maps a
+ * resolved OAuth declaration + coordinates to a key.
+ */
+export function buildMcpServerGrantKey(
+ resolved: ResolvedServerOAuth,
+ coords: McpServerGrantKeyCoords
+): OAuthGrantKey | null {
+ if (resolved.grantScope === 'context') {
+ // Shared identity is keyed by the server's authoritative Context, decoupled
+ // from any caller-supplied userId/contextId (no body-trust).
+ if (!resolved.contextRef) return null
+ return {
+ grantKind: 'shared',
+ ownerKind: 'mcpserver',
+ recipeNamespace: coords.mcpServersNamespace,
+ recipeName: coords.mcpServerName,
+ contextId: resolved.contextRef,
+ oauthClientId: resolved.oauthClientId,
+ }
+ }
+ if (typeof coords.userId !== 'string' || coords.userId.length === 0) return null
+ return {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: coords.mcpServersNamespace,
+ recipeName: coords.mcpServerName,
+ userId: coords.userId,
+ oauthClientId: resolved.oauthClientId,
+ }
+}
+
/**
* 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/mcpOauth.ts b/control-api/src/routes/mcpOauth.ts
index fef7c0481..9cb8806e6 100644
--- a/control-api/src/routes/mcpOauth.ts
+++ b/control-api/src/routes/mcpOauth.ts
@@ -1,6 +1,7 @@
import { type NextFunction, type Request, type Response, Router } from 'express'
import { config } from '../config.js'
import { pool } from '../db.js'
+import type { DbClient } from '../db.js'
import { K8sGateway } from '../k8s.js'
import { rateLimitMiddleware } from '../middleware/rateLimitMiddleware.js'
import {
@@ -12,9 +13,14 @@ import {
} from '../oauth/callback.js'
import { deriveOAuthEncryptionKey } from '../oauth/encryption.js'
import { integrationNotConfigured, isSecretNotFound } from '../oauth/integrationNotConfigured.js'
-import { type McpServerOAuthDecl, resolveServerOAuth } from '../oauth/mcpServerOAuthSpec.js'
-import type { OAuthGrantKey } from '../oauth/store.js'
+import {
+ type McpServerOAuthDecl,
+ buildMcpServerGrantKey,
+ resolveServerOAuth,
+} from '../oauth/mcpServerOAuthSpec.js'
+import { type OAuthGrantKey, oauthGrantExists } from '../oauth/store.js'
import { getAccessToken } from '../oauth/tokenHelper.js'
+import { type Logger, rootLogger } from '../observability/logger.js'
import { K8sNotFoundError } from '../services/resourceService.js'
import {
type McpHostControlClaims,
@@ -112,6 +118,138 @@ function isValidK8sName(name: string): boolean {
return name.length > 0 && name.length <= 253 && K8S_NAME_RE.test(name)
}
+// Upper bound on the grant-existence batch. mcp-host caps its per-user OAuth
+// partitions at OAUTH_USER_PARTITION_MAX=500, so one sweep never legitimately
+// exceeds that; 1000 is generous headroom that still rejects an abusive payload.
+const MAX_EXISTS_BATCH = 1000
+
+/** One entry of a `POST /mcp-oauth/grants/exists` request. */
+export interface GrantExistsQuery {
+ mcpServerName: string
+ /** End-user identity, for `grantScope='user'` servers. */
+ userId?: string
+ /**
+ * Accepted for API fidelity but NEVER used to key a lookup — `context`
+ * servers key by the server's authoritative `contextRef` (server-side). A
+ * lying value therefore cannot change the answer (no body-trust).
+ */
+ contextId?: string
+}
+
+/**
+ * One entry of the response. It ECHOES the query's coordinates so the consumer
+ * (the mcp-host sweep) correlates by the tuple `(mcpServerName, userId)` /
+ * `(mcpServerName, contextId)` rather than by array position — two per-user
+ * partitions of the SAME server (different `userId`) must stay distinguishable.
+ * `userId`/`contextId` are echoed exactly as the caller sent them: values the
+ * caller itself supplied, so echoing them leaks nothing (confirmed in review).
+ * Never a token, never the server's authoritative contextRef, never a key.
+ */
+export interface GrantExistsResult {
+ mcpServerName: string
+ userId?: string
+ contextId?: string
+ exists: boolean
+}
+
+export interface GrantExistenceDeps {
+ db: DbClient
+ gateway: K8sGateway
+ mcpServersNamespace: string
+ log?: Logger
+}
+
+/**
+ * Batch grant-existence resolver for the hot-revocation poll-sweep (mini-spec
+ * 13 §4.1). For each query it resolves the server's OAuth spec, derives the
+ * grant key with the SAME `buildMcpServerGrantKey` the mint uses (D4), and
+ * reports `oauthGrantExists` — a pure `SELECT 1`, never the token, never any
+ * secret.
+ *
+ * Contract: STRICT 1:1 with the input — exactly one result per input entry, in
+ * order, each echoing that entry's coordinates. Entries are per-entry untrusted
+ * (`unknown`): a malformed one is NOT dropped (that would break positional and
+ * tuple correlation) but yields a fail-open placeholder in its own slot.
+ *
+ * Fail-OPEN per query (§4.2 "fail-open transitorio"): ANY problem — malformed
+ * entry, server not found (deleted CR), not an OAuth server, a missing grant
+ * coordinate for the flavor, an apiserver blip, or a DB error — yields
+ * `exists: true` for THAT entry, so a transient hiccup never provokes an
+ * eviction. `exists: false` is returned ONLY when `oauthGrantExists` says so
+ * definitively. For `context` servers the key is the server's authoritative
+ * `contextRef` (server-side), never the body `contextId`.
+ */
+export async function resolveBatchGrantExistence(
+ deps: GrantExistenceDeps,
+ queries: readonly unknown[]
+): Promise<GrantExistsResult[]> {
+ const log = deps.log ?? rootLogger
+ const results: GrantExistsResult[] = []
+ for (const raw of queries) {
+ const entry = (raw && typeof raw === 'object' ? raw : {}) as {
+ mcpServerName?: unknown
+ userId?: unknown
+ contextId?: unknown
+ }
+ // Echo the caller-supplied coordinates exactly as they arrived (a non-string
+ // `mcpServerName` cannot address a server, so it echoes as ''). One `echo()`
+ // per iteration guarantees `results.length === queries.length`.
+ const mcpServerName = typeof entry.mcpServerName === 'string' ? entry.mcpServerName : ''
+ const userId = typeof entry.userId === 'string' ? entry.userId : undefined
+ const contextId = typeof entry.contextId === 'string' ? entry.contextId : undefined
+ const echo = (exists: boolean): GrantExistsResult => {
+ const r: GrantExistsResult = { mcpServerName, exists }
+ if (userId !== undefined) r.userId = userId
+ if (contextId !== undefined) r.contextId = contextId
+ return r
+ }
+
+ // Malformed name → cannot address a server; fail-open placeholder in slot.
+ if (!mcpServerName || !isValidK8sName(mcpServerName)) {
+ log.warn({ mcpServerName }, 'grant-existence: malformed query entry; fail-open (exists:true)')
+ results.push(echo(true))
+ continue
+ }
+
+ try {
+ const server = (await deps.gateway.getResource(
+ 'mcpservers',
+ mcpServerName,
+ deps.mcpServersNamespace
+ )) as McpServerResource
+ const resolved = resolveServerOAuth(server)
+ if (!resolved) {
+ // Not an OAuth server / no usable oauth id → ambiguous, fail-open.
+ log.warn({ mcpServerName }, 'grant-existence: server not resolvable as oauth; fail-open')
+ results.push(echo(true))
+ continue
+ }
+ const key = buildMcpServerGrantKey(resolved, {
+ mcpServerName,
+ mcpServersNamespace: deps.mcpServersNamespace,
+ userId,
+ })
+ if (!key) {
+ // Missing the coordinate the flavor needs (no userId for a user server,
+ // no contextRef for a context server) → ambiguous, fail-open.
+ log.warn(
+ { mcpServerName, grantScope: resolved.grantScope },
+ 'grant-existence: missing grant coordinate; fail-open'
+ )
+ results.push(echo(true))
+ continue
+ }
+ results.push(echo(await oauthGrantExists(deps.db, key)))
+ } catch (err) {
+ // Server not found (deleted CR), apiserver blip, or DB error — all
+ // transient/ambiguous. Fail-open: never evict a live partition on a hiccup.
+ log.warn({ err, mcpServerName }, 'grant-existence check failed; fail-open (exists:true)')
+ results.push(echo(true))
+ }
+ }
+ return results
+}
+
export function createMcpOauthRouter(gateway: K8sGateway): Router {
const router = Router()
const encryptionKey = deriveOAuthEncryptionKey(config.oauthEncryptionKey)
@@ -241,43 +379,41 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {
return res.status(400).json({ error: 'not_oauth_server' })
}
- // Bifurcate by grantScope read from the server.
- let key: OAuthGrantKey
+ // Bifurcate by grantScope read from the server. The KEY comes from the
+ // shared derivation (`buildMcpServerGrantKey`, D4) so the mint, the
+ // rpc-proxy grant-presence gate and the grant-existence sweep never
+ // drift. The mint keeps its own request-validation guards, which map to
+ // specific error codes the shared builder's null return cannot express.
+ let userForKey: string | undefined
if (resolved.grantScope === 'context') {
// AUTHORITATIVE Context = server.spec.contextRef, NEVER the body.
// Trusting a body contextId would let a caller with the scope request
// {server, contextId: <someone else's Context>} and receive that
// Context's shared token (cross-context token theft). The body value,
// if present, is only cross-checked against the authoritative one.
- const authoritativeContextId = resolved.contextRef
- if (!authoritativeContextId) {
+ if (!resolved.contextRef) {
// A context-identity server MUST carry contextRef (CRD-required).
// Fail closed if it somehow doesn't.
return res.status(400).json({ error: 'server_missing_context' })
}
- if (typeof contextId === 'string' && contextId !== authoritativeContextId) {
+ if (typeof contextId === 'string' && contextId !== resolved.contextRef) {
return res.status(400).json({ error: 'context_mismatch' })
}
- key = {
- grantKind: 'shared',
- ownerKind: 'mcpserver',
- recipeNamespace: config.mcpServersNamespace,
- recipeName: mcpServerName,
- contextId: authoritativeContextId,
- oauthClientId: resolved.oauthClientId,
- }
} else {
if (typeof userId !== 'string' || userId.length === 0) {
return res.status(400).json({ error: 'invalid_request' })
}
- key = {
- grantKind: 'user',
- ownerKind: 'mcpserver',
- recipeNamespace: config.mcpServersNamespace,
- recipeName: mcpServerName,
- userId,
- oauthClientId: resolved.oauthClientId,
- }
+ userForKey = userId
+ }
+ const key: OAuthGrantKey | null = buildMcpServerGrantKey(resolved, {
+ mcpServerName,
+ mcpServersNamespace: config.mcpServersNamespace,
+ userId: userForKey,
+ })
+ if (!key) {
+ // Unreachable: the guards above already rejected the null cases. Fail
+ // closed defensively rather than mint against a malformed key.
+ return res.status(400).json({ error: 'invalid_request' })
}
// Interactive live-session path — a human session is present, so
@@ -343,5 +479,61 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {
}
)
+ // Batch grant-existence sweep (mini-spec 13 §4.1 / §4.3). mcp-host asks, in the
+ // cadence of the poll it already runs, whether its live per-user OAuth
+ // partitions still have a grant, and evicts the ones that do not. MIRROR of
+ // `user-token` in the FULL gate + key derivation, but batch + read-only: same
+ // kill-switch, same `requireControlCaller`, the SAME `mcp_oauth_broker` rate
+ // limiter keyed by caller, and the SAME `oauth:user-token` scope (no new scope
+ // — that would force re-issuing control JWTs, §5). Each result echoes its
+ // query's coordinates so the consumer correlates by tuple, not position;
+ // returns ONLY `{ mcpServerName, userId?, contextId?, exists }` — never a
+ // token, the authoritative contextRef, or a key.
+ router.post(
+ '/mcp-oauth/grants/exists',
+ requireBrokerEnabled,
+ requireControlCaller,
+ rateLimitMiddleware({
+ bucketType: 'mcp_oauth_broker',
+ maxPerMinute: config.oauthBrokerRlPerMin,
+ getBucketKey: req => {
+ const claims = req.res?.locals?.mcpHostControl as McpHostControlClaims | undefined
+ return claims ? `mcp-oauth:${claims.sub}` : 'mcp-oauth:unknown'
+ },
+ }),
+ async (req, res, next) => {
+ const claims = res.locals.mcpHostControl as McpHostControlClaims | undefined
+ if (!claims || !claims.scopes.includes('oauth:user-token')) {
+ return res.status(403).json({ error: 'insufficient_scope' })
+ }
+
+ const body = (req.body ?? {}) as { queries?: unknown }
+ if (!Array.isArray(body.queries)) {
+ return res.status(400).json({ error: 'invalid_request' })
+ }
+ if (body.queries.length > MAX_EXISTS_BATCH) {
+ return res.status(400).json({ error: 'batch_too_large' })
+ }
+
+ try {
+ // Per-entry untrusted, but 1:1 with the input: the resolver validates
+ // each entry, never drops one, and emits a fail-open placeholder in the
+ // slot of any malformed/unresolvable entry.
+ const results = await resolveBatchGrantExistence(
+ {
+ db: { query: (text, values) => pool.query(text, values) },
+ gateway,
+ mcpServersNamespace: config.mcpServersNamespace,
+ log: req.log ?? rootLogger,
+ },
+ body.queries
+ )
+ return res.status(200).json({ results })
+ } catch (err) {
+ next(err)
+ }
+ }
+ )
+
return router
}
diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.ts
index 8689e9d0d..23bdb6b18 100644
--- a/control-api/src/services/access/mcpInvocable.ts
+++ b/control-api/src/services/access/mcpInvocable.ts
@@ -26,13 +26,16 @@
*/
import type { DbClient } from '../../db.js'
import type { K8sGateway } from '../../k8s.js'
-import { resolveServerOAuth } from '../../oauth/mcpServerOAuthSpec.js'
+import { buildMcpServerGrantKey, resolveServerOAuth } from '../../oauth/mcpServerOAuthSpec.js'
import { oauthGrantExists } from '../../oauth/store.js'
+import { rootLogger } from '../../observability/logger.js'
import {
type AgentDirectoryEntry,
buildAgentDirectoryEntry,
} from '../directory/accessReconciliation.js'
+const log = rootLogger.child({ module: 'mcpInvocable' })
+
export interface InvocableMcpServer {
name: string
url: string
@@ -223,42 +226,26 @@ async function computeGrantPresence(
if (s.spec?.auth?.type !== 'oauth') continue
const resolved = resolveServerOAuth(s)
if (!resolved) continue // fail-closed: no usable oauth id
+ // Same key derivation (D4) as the mint and the grant-existence sweep. Shared
+ // (`context`) identity is keyed by the server's AUTHORITATIVE `contextRef`,
+ // decoupled from the caller's userId (mini-spec 04 §2 3b; exercised by
+ // U6(api)); a context server without a contextRef yields null → fail-closed.
+ const key = buildMcpServerGrantKey(resolved, {
+ mcpServerName: name,
+ mcpServersNamespace,
+ userId: callerUserId,
+ })
+ if (!key) continue // fail-closed: missing grant coordinate for the flavor
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).
- if (exists) present.add(name)
+ if (await oauthGrantExists(db, key)) 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)
+ log.error(
+ { err, mcpServerName: name },
+ 'grant-presence check failed; server excluded from rpc-proxy rail'
)
}
}
diff --git a/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
new file mode 100644
index 000000000..6dddac38d
--- /dev/null
+++ b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts
@@ -0,0 +1,286 @@
+import { afterAll, beforeAll, beforeEach, 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 {
+ bootstrapSharedOAuthGrant,
+ deleteOAuthGrant,
+ upsertOAuthGrant,
+} from '../src/oauth/store.js'
+import { resolveBatchGrantExistence } from '../src/routes/mcpOauth.js'
+import { MockGateway } from './mockGateway.js'
+
+// T1 — the batch grant-existence resolver (mini-spec 13 §4.1) exercised against
+// grant state built by the REAL producers (`upsertOAuthGrant` /
+// `bootstrapSharedOAuthGrant` / `deleteOAuthGrant`) and read by the REAL
+// `oauthGrantExists` inside the resolver. NO hand-built oauth_grants rows and NO
+// hand-typed `exists` booleans. Gated on a real Postgres, like the store and
+// grant-gate integration tests:
+// CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \
+// test/routes.mcpOauth.grantsExists.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 CLIENT_ID = 'google-drive'
+
+describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {
+ const database = `control_api_grants_exists_${randomUUID().replace(/-/g, '')}`
+ let adminPool: Pool
+ let dbPool: Pool
+ let db: DbClient
+ let gateway: MockGateway
+
+ 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()
+ }
+ })
+
+ beforeEach(async () => {
+ await dbPool.query('DELETE FROM oauth_grants')
+ gateway = new MockGateway(NS)
+ })
+
+ function seedUserServer(name: string): void {
+ void gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name },
+ spec: {
+ enabled: true,
+ auth: { type: 'oauth' },
+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },
+ oauth: { id: CLIENT_ID, provider: 'google', grantScope: 'user' },
+ },
+ },
+ NS
+ )
+ }
+
+ function seedContextServer(name: string, contextRef: string): void {
+ void gateway.createResource(
+ 'mcpservers',
+ {
+ metadata: { name },
+ spec: {
+ enabled: true,
+ auth: { type: 'oauth' },
+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },
+ contextRef,
+ oauth: { id: CLIENT_ID, provider: 'google', grantScope: 'context' },
+ },
+ },
+ NS
+ )
+ }
+
+ const resolve = (queries: Parameters<typeof resolveBatchGrantExistence>[1]) =>
+ resolveBatchGrantExistence({ db, gateway, mcpServersNamespace: NS }, queries)
+
+ it('(a) reports exists:true for a per-user server once the grant is upserted', async () => {
+ seedUserServer('gdrive-u')
+
+ // No grant yet → false (definitive). Results echo the query's userId.
+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'alice', exists: false },
+ ])
+
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive-u',
+ userId: 'alice',
+ oauthClientId: CLIENT_ID,
+ provider: 'google',
+ accessToken: 'A',
+ })
+
+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'alice', exists: true },
+ ])
+ // A different user without their own grant is still false.
+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'bob' }])).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'bob', exists: false },
+ ])
+ })
+
+ it('(c2) distinguishes two userIds on the SAME server within one batch (real grants)', async () => {
+ seedUserServer('gdrive-u')
+ // alice consents; bob does not.
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive-u',
+ userId: 'alice',
+ oauthClientId: CLIENT_ID,
+ provider: 'google',
+ accessToken: 'A',
+ })
+
+ // Both partitions of the same server in ONE batch — distinguishable by the
+ // echoed userId, not by position (FIX A).
+ const results = await resolve([
+ { mcpServerName: 'gdrive-u', userId: 'bob' },
+ { mcpServerName: 'gdrive-u', userId: 'alice' },
+ ])
+ expect(results).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'bob', exists: false },
+ { mcpServerName: 'gdrive-u', userId: 'alice', exists: true },
+ ])
+ })
+
+ it('(b) flips to exists:false after the grant is deleted', async () => {
+ seedUserServer('gdrive-u')
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive-u',
+ userId: 'alice',
+ oauthClientId: CLIENT_ID,
+ provider: 'google',
+ accessToken: 'A',
+ })
+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'alice', exists: true },
+ ])
+
+ await deleteOAuthGrant(db, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'gdrive-u',
+ userId: 'alice',
+ oauthClientId: CLIENT_ID,
+ })
+
+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([
+ { mcpServerName: 'gdrive-u', userId: 'alice', exists: false },
+ ])
+ })
+
+ it('(c) mixed batch: results correspond by mcpServerName across present/absent grants', async () => {
+ seedUserServer('has-grant')
+ seedUserServer('no-grant')
+ seedUserServer('other-user') // grant exists for someone else, not the caller
+
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'has-grant',
+ userId: 'alice',
+ oauthClientId: CLIENT_ID,
+ provider: 'google',
+ accessToken: 'A',
+ })
+ await upsertOAuthGrant(db, KEY, {
+ grantKind: 'user',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'other-user',
+ userId: 'someone-else',
+ oauthClientId: CLIENT_ID,
+ provider: 'google',
+ accessToken: 'A',
+ })
+
+ const results = await resolve([
+ { mcpServerName: 'no-grant', userId: 'alice' },
+ { mcpServerName: 'has-grant', userId: 'alice' },
+ { mcpServerName: 'other-user', userId: 'alice' },
+ ])
+
+ // Observable output (T4): the full results list, in request order, each
+ // echoing its query coordinates.
+ expect(results).toEqual([
+ { mcpServerName: 'no-grant', userId: 'alice', exists: false },
+ { mcpServerName: 'has-grant', userId: 'alice', exists: true },
+ { mcpServerName: 'other-user', userId: 'alice', exists: false },
+ ])
+ })
+
+ it('(e) context server: keyed by spec.contextRef server-side; a lying body contextId does not change the answer', async () => {
+ seedContextServer('team-drive', 'ctx-authoritative')
+
+ // Bootstrap the shared identity for the AUTHORITATIVE context.
+ await bootstrapSharedOAuthGrant(db, KEY, {
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'team-drive',
+ contextId: 'ctx-authoritative',
+ oauthClientId: CLIENT_ID,
+ bootstrappedByUserId: 'alice',
+ provider: 'google',
+ accessToken: 'A',
+ })
+
+ // Body contextId is a DIFFERENT (foreign) context, and userId varies — the
+ // result must be driven ONLY by the server's authoritative contextRef.
+ const withLie = await resolve([
+ { mcpServerName: 'team-drive', userId: 'anyone', contextId: 'ctx-foreign' },
+ ])
+ // The lying body contextId is echoed back verbatim but never used to key.
+ expect(withLie).toEqual([
+ { mcpServerName: 'team-drive', userId: 'anyone', contextId: 'ctx-foreign', exists: true },
+ ])
+
+ // Delete the shared grant for the authoritative context → false, regardless
+ // of the foreign body contextId (which, if trusted, would still be absent).
+ await deleteOAuthGrant(db, {
+ grantKind: 'shared',
+ ownerKind: 'mcpserver',
+ recipeNamespace: NS,
+ recipeName: 'team-drive',
+ contextId: 'ctx-authoritative',
+ oauthClientId: CLIENT_ID,
+ })
+ const afterDelete = await resolve([
+ { mcpServerName: 'team-drive', userId: 'anyone', contextId: 'ctx-authoritative' },
+ ])
+ expect(afterDelete).toEqual([
+ {
+ mcpServerName: 'team-drive',
+ userId: 'anyone',
+ contextId: 'ctx-authoritative',
+ exists: false,
+ },
+ ])
+ })
+
+ it('fail-open: an unknown (deleted) server yields exists:true, never a spurious false', async () => {
+ // No server seeded → getResource throws K8sNotFoundError → fail-open.
+ expect(await resolve([{ mcpServerName: 'ghost', userId: 'alice' }])).toEqual([
+ { mcpServerName: 'ghost', userId: 'alice', exists: true },
+ ])
+ })
+})
diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.ts
index a05728f1f..44b6bfe1e 100644
--- a/control-api/test/routes.mcpOauth.test.ts
+++ b/control-api/test/routes.mcpOauth.test.ts
@@ -3,6 +3,7 @@ import request from 'supertest'
import { createApp } from '../src/app.js'
import { config } from '../src/config.js'
import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'
+import { checkAndIncrement } from '../src/services/rateLimiterService.js'
import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'
import { MockGateway } from './mockGateway.js'
@@ -386,3 +387,212 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {
})
})
})
+
+// Hot-revocation poll-sweep endpoint (mini-spec 13 §4.1). Gate + validation +
+// fail-open behaviors are asserted here at the HTTP layer; the AUTHORITATIVE
+// T1 derivation of `exists` from the real store producers lives in
+// routes.mcpOauth.grantsExists.realPostgres.integration.test.ts.
+describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (mini-spec 13)', () => {
+ let gateway: MockGateway
+ let app: ReturnType<typeof createApp>
+ const originalBrokerEnabled = config.mcpOauthBrokerEnabled
+
+ beforeEach(() => {
+ gateway = new MockGateway(MCP_NS)
+ app = createApp(gateway as never)
+ mockPoolQuery.mockReset()
+ // Default: SELECT 1 finds no row → oauthGrantExists = false (no grant).
+ mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })
+ config.mcpOauthBrokerEnabled = true
+ })
+
+ afterEach(() => {
+ config.mcpOauthBrokerEnabled = originalBrokerEnabled
+ })
+
+ const post = (token: string | null, body: unknown) => {
+ const req = request(app).post('/api/v1/mcp-oauth/grants/exists')
+ if (token) req.set('Authorization', `Bearer ${token}`)
+ return req.send(body as object)
+ }
+
+ it('401 without a control JWT (same gate as user-token)', async () => {
+ const res = await post(null, { queries: [{ mcpServerName: 'gdrive', userId: 'u1' }] })
+ expect(res.status).toBe(401)
+ })
+
+ // Case (d): the SAME scope as user-token (oauth:user-token) — no new scope.
+ it('403 insufficient_scope with a valid control JWT that lacks oauth:user-token', async () => {
+ const res = await post(controlToken([]), {
+ queries: [{ mcpServerName: 'gdrive', userId: 'u1' }],
+ })
+ expect(res.status).toBe(403)
+ expect(res.body.error).toBe('insufficient_scope')
+ })
+
+ it('400 invalid_request when queries is not an array', async () => {
+ const res = await post(controlToken(), { queries: 'nope' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('invalid_request')
+ })
+
+ it('400 batch_too_large when queries exceeds the cap', async () => {
+ const queries = Array.from({ length: 1001 }, (_, i) => ({
+ mcpServerName: `srv-${i}`,
+ userId: 'u1',
+ }))
+ const res = await post(controlToken(), { queries })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('batch_too_large')
+ })
+
+ // Fail-open (§4.2): an unknown server (getResource 404) and a non-oauth server
+ // are ambiguous/transient — never a spurious `exists:false` that would evict.
+ it('200: unknown and non-oauth servers fail OPEN (exists:true), keyed by name', async () => {
+ void gateway.createResource(
+ 'mcpservers',
+ { metadata: { name: 'plain' }, spec: { auth: { type: 'none' } } },
+ MCP_NS
+ )
+ const res = await post(controlToken(), {
+ queries: [
+ { mcpServerName: 'ghost', userId: 'u1' },
+ { mcpServerName: 'plain', userId: 'u1' },
+ ],
+ })
+ expect(res.status).toBe(200)
+ // Each result echoes the query's coordinates (correlation by tuple).
+ expect(res.body.results).toEqual([
+ { mcpServerName: 'ghost', userId: 'u1', exists: true },
+ { mcpServerName: 'plain', userId: 'u1', exists: true },
+ ])
+ // Fail-open cases never touch the grants table.
+ const grantQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants')
+ )
+ expect(grantQuery).toBeUndefined()
+ })
+
+ // A definitive `exists:false` only when oauthGrantExists says so (SELECT 1
+ // returns 0 rows), and the lookup is keyed by (mcpserver owner, userId).
+ it('200: a per-user server with no grant reports exists:false (definitive), keyed by userId', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })
+ const res = await post(controlToken(), {
+ queries: [{ mcpServerName: 'gdrive', userId: 'nobody' }],
+ })
+ expect(res.status).toBe(200)
+ expect(res.body.results).toEqual([{ mcpServerName: 'gdrive', userId: 'nobody', exists: false }])
+ const grantQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) =>
+ typeof sql === 'string' &&
+ sql.includes('FROM oauth_grants') &&
+ sql.includes("grant_kind = 'user'")
+ )
+ expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'gdrive', 'nobody', 'google-drive'])
+ })
+
+ it('200: reports exists:true when the SELECT 1 finds a row', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })
+ mockPoolQuery.mockResolvedValueOnce({ rows: [{ exists: 1 }], rowCount: 1 })
+ const res = await post(controlToken(), {
+ queries: [{ mcpServerName: 'gdrive', userId: 'u1' }],
+ })
+ expect(res.status).toBe(200)
+ expect(res.body.results).toEqual([{ mcpServerName: 'gdrive', userId: 'u1', exists: true }])
+ })
+
+ // FIX A core: two per-user partitions of the SAME server (different userId)
+ // must be distinguishable in ONE batch response — correlation by (server,
+ // userId) tuple, not by array position. alice has a grant, bob does not.
+ it('200: distinguishes two userIds on the same server within one batch', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })
+ // First SELECT 1 (alice) finds a row; the default empty result covers bob.
+ mockPoolQuery.mockResolvedValueOnce({ rows: [{ exists: 1 }], rowCount: 1 })
+ const res = await post(controlToken(), {
+ queries: [
+ { mcpServerName: 'gdrive', userId: 'alice' },
+ { mcpServerName: 'gdrive', userId: 'bob' },
+ ],
+ })
+ expect(res.status).toBe(200)
+ expect(res.body.results).toEqual([
+ { mcpServerName: 'gdrive', userId: 'alice', exists: true },
+ { mcpServerName: 'gdrive', userId: 'bob', exists: false },
+ ])
+ })
+
+ // Context flavor: keyed by the server's AUTHORITATIVE spec.contextRef, NEVER
+ // the body contextId (no body-trust). The SELECT 1 coordinate proves it; the
+ // lying body contextId is only echoed back, never used to key.
+ it('200: context server keys the lookup by spec.contextRef, ignoring a lying body contextId', async () => {
+ seedOauthServer(gateway, { name: 'team', grantScope: 'context', contextRef: 'ctx-real' })
+ const res = await post(controlToken(), {
+ queries: [{ mcpServerName: 'team', userId: 'u1', contextId: 'ctx-foreign' }],
+ })
+ expect(res.status).toBe(200)
+ expect(res.body.results).toEqual([
+ { mcpServerName: 'team', userId: 'u1', contextId: 'ctx-foreign', exists: false },
+ ])
+ const grantQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) =>
+ typeof sql === 'string' &&
+ sql.includes('FROM oauth_grants') &&
+ sql.includes("grant_kind = 'shared'")
+ )
+ // contextId coordinate is the authoritative ctx-real, NOT the body ctx-foreign.
+ expect(grantQuery?.[1]).toEqual(['mcpserver', MCP_NS, 'team', 'ctx-real', 'google-drive'])
+ })
+
+ // FIX A: a malformed entry must NOT be dropped (that breaks positional/tuple
+ // correlation) — it yields a fail-open placeholder in its OWN slot, echoing
+ // whatever coordinates it carried. results stays 1:1 with queries.
+ it('200: keeps results 1:1 with queries, fail-open placeholder for malformed entries', async () => {
+ const queries = [
+ { mcpServerName: 'Foo/Bar', userId: 'u1' }, // invalid k8s name → placeholder, name echoed as-is
+ { mcpServerName: 'ghost', userId: 'u2' }, // unknown server → fail-open true
+ { userId: 'u3' }, // no mcpServerName → placeholder, name echoes ''
+ ]
+ const res = await post(controlToken(), { queries })
+ expect(res.status).toBe(200)
+ expect(res.body.results).toHaveLength(queries.length)
+ expect(res.body.results).toEqual([
+ { mcpServerName: 'Foo/Bar', userId: 'u1', exists: true },
+ { mcpServerName: 'ghost', userId: 'u2', exists: true },
+ { mcpServerName: '', userId: 'u3', exists: true },
+ ])
+ })
+
+ // FIX B: the endpoint mirrors user-token's rate limiter (same mcp_oauth_broker
+ // bucket, keyed by caller). When the bucket is exhausted the middleware short-
+ // circuits with 429 BEFORE the handler runs (no grant lookup).
+ it('429 Too Many Requests when the shared broker rate limit is exceeded', async () => {
+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })
+ vi.mocked(checkAndIncrement).mockResolvedValueOnce({
+ allowed: false,
+ remaining: 0,
+ resetMs: Date.now() + 60_000,
+ windowStartMs: Date.now(),
+ count: 61,
+ })
+ const res = await post(controlToken(), {
+ queries: [{ mcpServerName: 'gdrive', userId: 'u1' }],
+ })
+ expect(res.status).toBe(429)
+ expect(res.body.error).toBe('Too Many Requests')
+ // Denied before the handler — no grants lookup ran.
+ const grantQuery = mockPoolQuery.mock.calls.find(
+ ([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants')
+ )
+ expect(grantQuery).toBeUndefined()
+ })
+
+ // Kill-switch parity with user-token: OFF (default) → the endpoint looks absent.
+ it('404 not_found when the broker kill-switch is OFF', async () => {
+ config.mcpOauthBrokerEnabled = false
+ const res = await post(controlToken(), {
+ queries: [{ mcpServerName: 'gdrive', userId: 'u1' }],
+ })
+ expect(res.status).toBe(404)
+ expect(res.body.error).toBe('not_found')
+ })
+})
diff --git a/control-api/test/services.access.mcpInvocable.grantGate.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.test.ts
index c5ed53853..038e373df 100644
--- a/control-api/test/services.access.mcpInvocable.grantGate.test.ts
+++ b/control-api/test/services.access.mcpInvocable.grantGate.test.ts
@@ -248,12 +248,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(() => {})
const out = await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB)
- // 'broken' excluded (fail-closed), 'plain' (none) + 'good' survive. Sorted.
+ // Observable outcome (T4): 'broken' excluded (fail-closed on its DB error),
+ // 'plain' (none) + 'good' survive. Sorted. The exclusion is also logged
+ // loudly via the module's pino logger (silent in tests) — an implementation
+ // detail we no longer assert on directly.
expect(names(out)).toEqual(['good', 'plain'])
- expect(errSpy).toHaveBeenCalled()
- errSpy.mockRestore()
})
})