Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): u3 open filterInvocable to oauth + rpc-proxy grant gate
Diego Zacarias94a241082e2c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 9bb4e2174..65c1b78e9 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.434",+ "version": "0.1.435","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.434",+ "version": "0.1.435","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",@@ -31,6 +31,7 @@"@types/node": "^24.3.0","@types/pg": "^8.11.10","@types/supertest": "^7.2.0",+ "fast-check": "^4.9.0","supertest": "^7.2.2","ts-node": "^10.9.2","typescript": "^5.9.2",@@ -1666,6 +1667,29 @@"integrity": "sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g==","license": "MIT"},+ "node_modules/fast-check": {+ "version": "4.9.0",+ "resolved": "https://registry.npmjs.org/fast-check/-/fast-check-4.9.0.tgz",+ "integrity": "sha512-7ms6T7SybUev/PQITciI0yLM2pOSFy5zpG8Ty7tQofcVaQUvrMXp6CBwqF6fThLCLOrfBtuHAtwq6Yu4XPCllg==",+ "dev": true,+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT",+ "dependencies": {+ "pure-rand": "^8.0.0"+ },+ "engines": {+ "node": ">=12.17.0"+ }+ },"node_modules/fast-fifo": {"version": "1.3.2","resolved": "https://registry.npmjs.org/fast-fifo/-/fast-fifo-1.3.2.tgz",@@ -3047,6 +3071,23 @@"once": "^1.3.1"}},+ "node_modules/pure-rand": {+ "version": "8.4.2",+ "resolved": "https://registry.npmjs.org/pure-rand/-/pure-rand-8.4.2.tgz",+ "integrity": "sha512-vvuOGgcuPJAirlHvuQw1TrOiw7ptaIXXmIbNuiNOY6lNGJJH49PQ1Kj4nd783nPdQhQdicgOjVI2yI/9BD6/Ng==",+ "dev": true,+ "funding": [+ {+ "type": "individual",+ "url": "https://github.com/sponsors/dubzzz"+ },+ {+ "type": "opencollective",+ "url": "https://opencollective.com/fast-check"+ }+ ],+ "license": "MIT"+ },"node_modules/qs": {"version": "6.15.3","resolved": "https://registry.npmjs.org/qs/-/qs-6.15.3.tgz",diff --git a/control-api/package.json b/control-api/package.jsonindex 87c5b1e45..70ff5c36e 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.434",+ "version": "0.1.435","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {@@ -39,6 +39,7 @@"@types/node": "^24.3.0","@types/pg": "^8.11.10","@types/supertest": "^7.2.0",+ "fast-check": "^4.9.0","supertest": "^7.2.2","ts-node": "^10.9.2","typescript": "^5.9.2",diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.tsnew file mode 100644index 000000000..1c379d656--- /dev/null+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts@@ -0,0 +1,57 @@+/**+ * Shared reader for an OAuth McpServer's `spec.oauth` declaration.+ *+ * 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):+ * - 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.+ */++export interface McpServerOAuthDecl {+ id?: unknown+ provider?: unknown+ clientIdRef?: { name?: unknown; key?: unknown }+ clientSecretRef?: { name?: unknown; key?: unknown }+ scopes?: unknown+ backgroundAccess?: unknown+ grantScope?: unknown+}++/** Minimal structural shape needed to resolve a server's OAuth grant coordinate. */+export interface McpServerOAuthSpecInput {+ spec?: {+ oauth?: McpServerOAuthDecl+ // `spec.contextRef` is REQUIRED + singular on the CRD ("the context this+ // server belongs to", mcpserver.yaml). It is the AUTHORITATIVE Context of a+ // context-identity server — the shared grant coordinate — never the body.+ contextRef?: unknown+ }+}++export type GrantScope = 'user' | 'context'++export interface ResolvedServerOAuth {+ oauthClientId: string+ grantScope: GrantScope+ /** Authoritative Context of the server (spec.contextRef); undefined if absent. */+ contextRef?: string+}++/**+ * Derive `{ oauthClientId, grantScope, contextRef }` from a McpServer's+ * `spec.oauth`. Returns null when the server carries no usable OAuth id, so+ * callers fail closed. `grantScope` defaults to `'user'` for anything other+ * than the explicit `'context'` sentinel (U1: immutable per server, CEL-guarded).+ */+export function resolveServerOAuth(server: McpServerOAuthSpecInput): ResolvedServerOAuth | null {+ const oauth = server.spec?.oauth+ if (!oauth || typeof oauth.id !== 'string' || oauth.id.length === 0) return null+ const grantScope: GrantScope = oauth.grantScope === 'context' ? 'context' : 'user'+ const contextRef =+ typeof server.spec?.contextRef === 'string' && server.spec.contextRef.length > 0+ ? server.spec.contextRef+ : undefined+ return { oauthClientId: oauth.id, grantScope, contextRef }+}diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex c241fd8d8..2cfe2ed82 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -12,6 +12,7 @@ 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 { getAccessToken } from '../oauth/tokenHelper.js'import { K8sNotFoundError } from '../services/resourceService.js'@@ -51,16 +52,6 @@ import { extractBearerToken } from '../utils/extractBearerToken.js'* Both branches ship in v1; the `context` branch is governed/exercised by U6.*/-interface McpServerOAuthDecl {- id?: unknown- provider?: unknown- clientIdRef?: { name?: unknown; key?: unknown }- clientSecretRef?: { name?: unknown; key?: unknown }- scopes?: unknown- backgroundAccess?: unknown- grantScope?: unknown-}-interface McpServerResource {metadata?: { name?: string; namespace?: string }spec?: {@@ -73,15 +64,6 @@ interface McpServerResource {}}-type GrantScope = 'user' | 'context'--interface ResolvedServerOAuth {- oauthClientId: string- grantScope: GrantScope- /** Authoritative Context of the server (spec.contextRef); undefined if absent. */- contextRef?: string-}-/*** Normalize a McpServer's single `spec.oauth` object into the* `{ spec: { oauthClients: [decl] } }` shape the owner-agnostic broker +@@ -122,17 +104,6 @@ function normalizeMcpServerOwnerDecl(server: McpServerResource): RecipeWithOAuth}}-function resolveServerOAuth(server: McpServerResource): ResolvedServerOAuth | null {- const oauth = server.spec?.oauth- if (!oauth || typeof oauth.id !== 'string' || oauth.id.length === 0) return null- const grantScope: GrantScope = oauth.grantScope === 'context' ? 'context' : 'user'- const contextRef =- typeof server.spec?.contextRef === 'string' && server.spec.contextRef.length > 0- ? server.spec.contextRef- : undefined- return { oauthClientId: oauth.id, grantScope, contextRef }-}-// DNS-1123 subdomain, the shape a k8s resource name takes. Reject anything else// up front so a malformed `mcpServerName` (e.g. "Foo/Bar") becomes a 400 rather// than surfacing a non-404 apiserver error as a 500.diff --git a/control-api/src/routes/rpc-access/users.ts b/control-api/src/routes/rpc-access/users.tsindex 5a61e6e70..9fa68f163 100644--- a/control-api/src/routes/rpc-access/users.ts+++ b/control-api/src/routes/rpc-access/users.ts@@ -1,6 +1,7 @@import express, { Router } from 'express'import type { Request } from 'express'import { config } from '../../config.js'+import { pool } from '../../db.js'import { K8sGateway } from '../../k8s.js'import {requireRpcTokenUserMatch,@@ -117,10 +118,16 @@ export function createRpcAccessUsersRouter(async (req, res, next) => {try {const userContexts = await getUserContexts(req.params.userId)+ // `req.params.userId` is authoritative here — `requireRpcTokenUserMatch()`+ // has already bound it to the RPC token subject. The DB client follows the+ // pool-wrapper idiom used by the other oauth routes (mcpOauth.ts,+ // internal/oauth.ts): `{ query: (t, v) => pool.query(t, v) }`.const servers = await resolveInvocableMcpServersForContexts(gateway,config.mcpServersNamespace,- userContexts.contextIds+ userContexts.contextIds,+ req.params.userId,+ { query: (text, values) => pool.query(text, values) })res.status(200).json({userId: req.params.userId,diff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.tsindex 53e36db5b..8689e9d0d 100644--- a/control-api/src/services/access/mcpInvocable.ts+++ b/control-api/src/services/access/mcpInvocable.ts@@ -11,13 +11,23 @@* the scoped context-ids lists it in `spec.mcpServers`.* - A server is **invocable** if it's allowed AND:* - `spec.enabled !== false`- * - `spec.auth.type` is absent or equals `"none"`+ * - `spec.auth.type` is on the allowlist — absent/`"none"`/`"oauth"`+ * (`bearer`/`basic`/`apiKey` are excluded). U3, mini-spec 04.* - `spec.transport.url` is a non-empty string+ * - **rpc-proxy rail only** (`resolveInvocableMcpServersForContexts`): an+ * `oauth` server additionally requires a valid grant for the caller,+ * computed by flavor (`grantScope`) and passed into the pure filter as data+ * (`grantPresence`). The catalog rail (`resolveMcpServersForAgents`) skips+ * this gate — its isolation is the JIT token resolution (U4), not this+ * filter.* - Session catalog preserves names-only compatibility while enriching each* authorized agent with its canonical directory identity; RPC catalog* additionally returns the transport URL.*/+import type { DbClient } from '../../db.js'import type { K8sGateway } from '../../k8s.js'+import { resolveServerOAuth } from '../../oauth/mcpServerOAuthSpec.js'+import { oauthGrantExists } from '../../oauth/store.js'import {type AgentDirectoryEntry,buildAgentDirectoryEntry,@@ -43,6 +53,14 @@ interface McpServerCR {enabled?: booleanauth?: { type?: string }transport?: { type?: string; url?: string }+ // OAuth coordinates (U1). Read only for the rpc-proxy grant-presence gate;+ // the catalog rail never inspects them. Structurally compatible with+ // `resolveServerOAuth`'s input.+ oauth?: {+ id?: unknown+ grantScope?: unknown+ }+ contextRef?: unknown}}@@ -131,11 +149,24 @@ function resolveServerUrl(s: McpServerCR, mcpServersNamespace: string): string |/*** Intersect a name set with the "invocable" filter on McpServer CRs.* Returns a new Set of just the invocable names.+ *+ * PURE + total — the only I/O is done by the caller, which passes its result in+ * as `grantPresence` (the "identity as data" pattern, mini-spec 04 §2).+ *+ * Auth-type allowlist: admits `none` (or absent) and `oauth`; still EXCLUDES+ * `bearer`/`basic`/`apiKey`. This runs on BOTH rails.+ *+ * Grant-presence gate (rpc-proxy rail ONLY): when `grantPresence` is provided,+ * an `oauth` server is invocable IFF its name is in the set. When `grantPresence`+ * is ABSENT (catalog rail, `resolveMcpServersForAgents`), the gate is skipped and+ * oauth servers pass on the auth-type allowlist alone — that rail's isolation is+ * the JIT token resolution (U4), not this filter.*/-function filterInvocable(+export function filterInvocable(names: ReadonlySet<string>,servers: McpServerCR[],- mcpServersNamespace: string+ mcpServersNamespace: string,+ grantPresence?: ReadonlySet<string>): Set<string> {const byName = new Map<string, McpServerCR>()for (const s of servers) {@@ -148,21 +179,103 @@ function filterInvocable(if (!s) continueif (s.spec?.enabled === false) continueconst authType = s.spec?.auth?.type- if (authType && authType !== 'none') continue+ // Allowlist: absent/`none`/`oauth` admitted; `bearer`/`basic`/`apiKey` excluded.+ if (authType && authType !== 'none' && authType !== 'oauth') continue+ // rpc-proxy grant-presence gate: an oauth server needs a valid grant, passed+ // as data by the resolver. Fail-closed — not in the set means not invocable.+ if (grantPresence && authType === 'oauth' && !grantPresence.has(name)) continueif (!resolveServerUrl(s, mcpServersNamespace)) continueout.add(name)}return out}+/**+ * Compute the set of candidate server names that have a valid OAuth grant for+ * this caller, by flavor (mini-spec 04 §2 step 3). Non-oauth servers are never+ * added here (the auth-type allowlist governs them). FAIL-CLOSED throughout: a+ * missing oauth id / contextRef, an unknown grantScope, or a DB error EXCLUDES+ * the server (it is simply not added to the set), so the rpc-proxy gate treats+ * it as un-serviceable rather than propagating a 500 for the whole request.+ *+ * The `user` branch is fully exercised in v1. The `context` (shared-grant)+ * branch is implemented + covered by the pure property test here; its+ * cross-service, end-to-end activation is exercised by U6(api).+ */+async function computeGrantPresence(+ db: DbClient,+ mcpServersNamespace: string,+ callerUserId: string,+ servers: McpServerCR[],+ candidateNames: ReadonlySet<string>+): Promise<Set<string>> {+ const byName = new Map<string, McpServerCR>()+ for (const s of servers) {+ const n = s.metadata?.name+ if (n) byName.set(n, s)+ }++ const present = new Set<string>()+ for (const name of candidateNames) {+ const s = byName.get(name)+ if (!s) continue+ // Only oauth servers are grant-gated; `none` servers pass on the allowlist.+ if (s.spec?.auth?.type !== 'oauth') continue+ const resolved = resolveServerOAuth(s)+ if (!resolved) continue // fail-closed: no usable oauth id++ 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)+ } 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)+ )+ }+ }+ return present+}+/*** Flat list of invocable `{name, url}` for the given scoped context ids.- * Used by `/rpc/access/users/:id/mcp-servers`.+ * Used by `/rpc/access/users/:id/mcp-servers` — the rpc-proxy rail, so it+ * additionally applies the OAuth grant-presence gate (mini-spec 04).*/export async function resolveInvocableMcpServersForContexts(gateway: K8sGateway,mcpServersNamespace: string,- scopedContextIds: readonly string[]+ scopedContextIds: readonly string[],+ callerUserId: string,+ db: DbClient): Promise<InvocableMcpServer[]> {const scoped = new Set(scopedContextIds)if (scoped.size === 0) return []@@ -177,7 +290,14 @@ export async function resolveInvocableMcpServersForContexts(for (const names of allowedByContext.values()) {for (const name of names) union.add(name)}- const invocable = filterInvocable(union, serverList, mcpServersNamespace)+ const grantPresence = await computeGrantPresence(+ db,+ mcpServersNamespace,+ callerUserId,+ serverList,+ union+ )+ const invocable = filterInvocable(union, serverList, mcpServersNamespace, grantPresence)const byName = new Map<string, McpServerCR>()for (const s of serverList) {diff --git a/control-api/test/services.access.mcpInvocable.filterInvocable.property.test.ts b/control-api/test/services.access.mcpInvocable.filterInvocable.property.test.tsnew file mode 100644index 000000000..112d71fc4--- /dev/null+++ b/control-api/test/services.access.mcpInvocable.filterInvocable.property.test.ts@@ -0,0 +1,131 @@+import { describe, expect, it } from 'vitest'+import fc from 'fast-check'+import { filterInvocable } from '../src/services/access/mcpInvocable.js'++// T2 — property-based test of the PURE `filterInvocable` (mini-spec 04 §5a-c).+// No I/O: grant-presence is passed AS DATA, so the whole contract is exercised+// with generated inputs rather than a live DB.++const NS = 'mcp-server'+const AUTH_TYPES = [undefined, 'none', 'oauth', 'bearer', 'basic', 'apiKey'] as const+const EXCLUDED_AUTH = new Set(['bearer', 'basic', 'apiKey'])++type GenServer = { name: string; authType: (typeof AUTH_TYPES)[number]; enabled: boolean }++// Every generated server carries a transport.url so url-resolvability is a+// constant — invocability then turns solely on enabled/auth-type/grant, which is+// what these properties probe.+function toCR(s: GenServer) {+ return {+ metadata: { name: s.name },+ spec: {+ enabled: s.enabled,+ auth: s.authType === undefined ? undefined : { type: s.authType },+ transport: { url: `http://${s.name}.${NS}.svc:3000/mcp` },+ },+ }+}++const serverArb: fc.Arbitrary<GenServer> = fc.record({+ name: fc.constantFrom('s1', 's2', 's3', 's4', 's5', 's6'),+ authType: fc.constantFrom(...AUTH_TYPES),+ enabled: fc.boolean(),+})++// A set of servers with distinct names + an arbitrary grant-presence subset of+// those names (models the resolver's computed `Set<serverName>`).+const scenarioArb = fc+ .uniqueArray(serverArb, { selector: s => s.name, minLength: 1, maxLength: 6 })+ .chain(servers =>+ fc.record({+ servers: fc.constant(servers),+ present: fc.subarray(servers.map(s => s.name)),+ })+ )++describe('filterInvocable — pure property tests (rpc-proxy rail: grantPresence provided)', () => {+ it('(a) an OAuth server is invocable ONLY when its name is in grantPresence', () => {+ fc.assert(+ fc.property(scenarioArb, ({ servers, present }) => {+ const names = new Set(servers.map(s => s.name))+ const presence = new Set(present)+ const out = filterInvocable(names, servers.map(toCR), NS, presence)+ for (const s of servers) {+ if (s.authType === 'oauth' && !presence.has(s.name)) {+ expect(out.has(s.name)).toBe(false)+ }+ }+ })+ )+ })++ it('(b) the auth-type allowlist NEVER admits bearer/basic/apiKey, whatever the grant state', () => {+ fc.assert(+ fc.property(scenarioArb, ({ servers, present }) => {+ const names = new Set(servers.map(s => s.name))+ // Even if the name were (nonsensically) in grantPresence, it stays out.+ const presence = new Set([...present, ...servers.map(s => s.name)])+ const out = filterInvocable(names, servers.map(toCR), NS, presence)+ for (const s of servers) {+ if (s.authType && EXCLUDED_AUTH.has(s.authType)) {+ expect(out.has(s.name)).toBe(false)+ }+ }+ })+ )+ })++ it('(c) an OAuth server is invocable IFF grant present AND enabled — membership drives it', () => {+ // At the pure level, a `grantScope=context` server presents identically to a+ // `user` one: the resolver computes its presence from the SHARED key+ // (decoupled from the caller's userId, mini-spec 04 §2 3b) and hands the same+ // Set in here. That decoupling is exercised end-to-end by U6(api); here the+ // observable contract is: name ∈ grantPresence ⇔ invocable (auth/enabled ok).+ fc.assert(+ fc.property(scenarioArb, ({ servers, present }) => {+ const names = new Set(servers.map(s => s.name))+ const presence = new Set(present)+ const out = filterInvocable(names, servers.map(toCR), NS, presence)+ for (const s of servers) {+ if (s.authType !== 'oauth') continue+ const expected = presence.has(s.name) && s.enabled !== false+ expect(out.has(s.name)).toBe(expected)+ }+ })+ )+ })++ it('`none`/absent servers are never grant-gated (invocable when enabled, regardless of grantPresence)', () => {+ fc.assert(+ fc.property(scenarioArb, ({ servers }) => {+ const names = new Set(servers.map(s => s.name))+ const out = filterInvocable(names, servers.map(toCR), NS, new Set())+ for (const s of servers) {+ if (s.authType === undefined || s.authType === 'none') {+ expect(out.has(s.name)).toBe(s.enabled !== false)+ }+ }+ })+ )+ })+})++describe('filterInvocable — catalog rail (grantPresence ABSENT): allowlist only, no grant gating', () => {+ it('OAuth servers pass on the auth-type allowlist alone; bearer/basic/apiKey still excluded', () => {+ fc.assert(+ fc.property(scenarioArb, ({ servers }) => {+ const names = new Set(servers.map(s => s.name))+ const out = filterInvocable(names, servers.map(toCR), NS /* no grantPresence */)+ for (const s of servers) {+ if (s.authType === 'oauth') {+ // Not gated by any grant here — invocable purely on enabled/url.+ expect(out.has(s.name)).toBe(s.enabled !== false)+ }+ if (s.authType && EXCLUDED_AUTH.has(s.authType)) {+ expect(out.has(s.name)).toBe(false)+ }+ }+ })+ )+ })+})diff --git a/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.tsnew file mode 100644index 000000000..a9aa4c712--- /dev/null+++ b/control-api/test/services.access.mcpInvocable.grantGate.realPostgres.integration.test.ts@@ -0,0 +1,147 @@+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 { bootstrapSharedOAuthGrant, upsertOAuthGrant } from '../src/oauth/store.js'+import { resolveInvocableMcpServersForContexts } from '../src/services/access/mcpInvocable.js'+import { MockGateway } from './mockGateway.js'++// T1 — the rpc-proxy grant-presence gate exercised end-to-end against grant+// state built by the REAL producers (`upsertOAuthGrant` / `bootstrapSharedOAuthGrant`)+// and read by the REAL `oauthGrantExists` inside the resolver. No hand-built+// oauth_grants rows. Gated on a real Postgres, like the store integration test:+// CONTROL_API_REAL_PG_ADMIN_URL=postgres://user:pass@host:5432 npm test -- \+// test/services.access.mcpInvocable.grantGate.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('mcpInvocable grant-presence gate (real Postgres)', () => {+ const database = `control_api_mcpinvocable_gate_${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()+ }+ })++ function gatewayWith(+ servers: Array<{ name: string; grantScope: 'user' | 'context'; contextRef: string }>+ ): MockGateway {+ const g = new MockGateway(NS)+ void g.createResource(+ 'contexts',+ {+ metadata: { name: 'ctx-1' },+ spec: { contextId: 'ctx-1', mcpServers: servers.map(s => s.name) },+ },+ NS+ )+ for (const s of servers) {+ void g.createResource(+ 'mcpservers',+ {+ metadata: { name: s.name },+ spec: {+ enabled: true,+ auth: { type: 'oauth' },+ transport: { url: `http://${s.name}.${NS}.svc:3000/mcp` },+ contextRef: s.contextRef,+ oauth: { id: CLIENT_ID, provider: 'google', grantScope: s.grantScope },+ },+ },+ NS+ )+ }+ return g+ }++ const list = async (g: MockGateway, userId: string) =>+ (await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], userId, db)).map(s => s.name)++ it('user-flavor: excluded without a grant, invocable after the caller upserts one', async () => {+ const g = gatewayWith([{ name: 'gdrive-u', grantScope: 'user', contextRef: 'ctx-1' }])+ expect(await list(g, 'alice')).toEqual([])++ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive-u',+ userId: 'alice',+ oauthClientId: CLIENT_ID,+ provider: 'google',+ accessToken: 'A',+ })+ expect(await list(g, 'alice')).toEqual(['gdrive-u'])+ // Another user without their own grant still cannot invoke it.+ expect(await list(g, 'bob')).toEqual([])+ })++ it('context-flavor: invocable for EVERY member once the shared grant is bootstrapped, decoupled from userId', async () => {+ const g = gatewayWith([{ name: 'gdrive-s', grantScope: 'context', contextRef: 'ctx-1' }])+ expect(await list(g, 'alice')).toEqual([])++ // Bob bootstraps the team identity; Alice never consented individually.+ await bootstrapSharedOAuthGrant(db, KEY, {+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive-s',+ contextId: 'ctx-1',+ oauthClientId: CLIENT_ID,+ bootstrappedByUserId: 'bob',+ provider: 'google',+ accessToken: 'S',+ })+ expect(await list(g, 'alice')).toEqual(['gdrive-s'])+ expect(await list(g, 'bob')).toEqual(['gdrive-s'])+ })++ it('a user grant does NOT satisfy a context-flavor server (disjoint keyspaces)', async () => {+ const g = gatewayWith([{ name: 'gdrive-x', grantScope: 'context', contextRef: 'ctx-1' }])+ // A stray user grant on the same server/client for the caller.+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive-x',+ userId: 'carol',+ oauthClientId: CLIENT_ID,+ provider: 'google',+ accessToken: 'A',+ })+ // Still not invocable: the context flavor reads the SHARED key only.+ expect(await list(g, 'carol')).toEqual([])+ })+})diff --git a/control-api/test/services.access.mcpInvocable.grantGate.test.ts b/control-api/test/services.access.mcpInvocable.grantGate.test.tsnew file mode 100644index 000000000..c5ed53853--- /dev/null+++ b/control-api/test/services.access.mcpInvocable.grantGate.test.ts@@ -0,0 +1,259 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { DbClient } from '../src/db.js'+import type { GetOAuthGrantInput } from '../src/oauth/store.js'+import { MockGateway } from './mockGateway.js'++// The resolver calls the REAL `oauthGrantExists`, whose SQL is covered by the+// store's own suites (incl. the real-Postgres integration test). Here we mock+// ONLY that boolean existence check to drive grant-presence deterministically,+// and assert (1) the resolver queries the RIGHT grant coordinate per flavor and+// (2) the OBSERVABLE resolved list (T4). importActual keeps every other store+// export real so the rest of the import graph is undisturbed.+const grantExists = vi.fn<(db: unknown, input: GetOAuthGrantInput) => Promise<boolean>>()+vi.mock('../src/oauth/store.js', async importActual => {+ const actual = await importActual<typeof import('../src/oauth/store.js')>()+ return {+ ...actual,+ oauthGrantExists: (db: unknown, input: GetOAuthGrantInput) => grantExists(db, input),+ }+})++const { resolveInvocableMcpServersForContexts } =+ await import('../src/services/access/mcpInvocable.js')++const NS = 'mcp-server'+const CALLER = 'user-caller'+// A DB error is simulated by the mock rejecting; the wrapper never touches SQL.+const DB: DbClient = { query: async () => ({ rows: [], rowCount: 0 }) }++function seedContext(g: MockGateway, contextId: string, servers: string[]): void {+ void g.createResource(+ 'contexts',+ { metadata: { name: contextId }, spec: { contextId, mcpServers: servers } },+ NS+ )+}++function seedOauthServer(+ g: MockGateway,+ opts: {+ name: string+ grantScope?: 'user' | 'context'+ contextRef?: string+ oauthId?: string | undefined+ }+): void {+ void g.createResource(+ 'mcpservers',+ {+ metadata: { name: opts.name },+ spec: {+ enabled: true,+ auth: { type: 'oauth' },+ transport: { url: `http://${opts.name}.${NS}.svc:3000/mcp` },+ ...(opts.contextRef !== undefined ? { contextRef: opts.contextRef } : {}),+ oauth: {+ ...(opts.oauthId === undefined ? {} : { id: opts.oauthId }),+ provider: 'google',+ ...(opts.grantScope ? { grantScope: opts.grantScope } : {}),+ },+ },+ },+ NS+ )+}++function seedNoneServer(g: MockGateway, name: string): void {+ void g.createResource(+ 'mcpservers',+ {+ metadata: { name },+ spec: {+ enabled: true,+ auth: { type: 'none' },+ transport: { url: `http://${name}.${NS}.svc:3000/mcp` },+ },+ },+ NS+ )+}++const names = (list: Array<{ name: string }>) => list.map(s => s.name)++beforeEach(() => {+ grantExists.mockReset()+})++describe('resolveInvocableMcpServersForContexts — rpc-proxy grant-presence gate (user flavor)', () => {+ it('excludes an OAuth user-server with NO grant, includes it once the grant exists', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-1', ['gdrive'])+ seedOauthServer(g, {+ name: 'gdrive',+ grantScope: 'user',+ contextRef: 'ctx-1',+ oauthId: 'google-drive',+ })++ // No grant.+ grantExists.mockResolvedValue(false)+ expect(+ names(await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB))+ ).toEqual([])++ // Grant present.+ grantExists.mockResolvedValue(true)+ expect(+ names(await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB))+ ).toEqual(['gdrive'])+ })++ it('queries the USER grant coordinate keyed by the caller userId + server name', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-1', ['gdrive'])+ seedOauthServer(g, {+ name: 'gdrive',+ grantScope: 'user',+ contextRef: 'ctx-1',+ oauthId: 'google-drive',+ })+ grantExists.mockResolvedValue(true)++ await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB)++ expect(grantExists).toHaveBeenCalledTimes(1)+ expect(grantExists.mock.calls[0][1]).toEqual({+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive',+ userId: CALLER,+ oauthClientId: 'google-drive',+ })+ })++ it('defaults an OAuth server without grantScope to the user flavor', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-1', ['gdrive'])+ seedOauthServer(g, { name: 'gdrive', contextRef: 'ctx-1', oauthId: 'google-drive' }) // no grantScope+ grantExists.mockResolvedValue(true)++ await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB)+ expect(grantExists.mock.calls[0][1]).toMatchObject({ grantKind: 'user', userId: CALLER })+ })+})++describe('resolveInvocableMcpServersForContexts — context (shared) flavor', () => {+ it('queries the SHARED coordinate keyed by the server contextRef, DECOUPLED from the caller userId', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-team', ['gdrive-shared'])+ seedOauthServer(g, {+ name: 'gdrive-shared',+ grantScope: 'context',+ contextRef: 'ctx-authoritative',+ oauthId: 'google-drive',+ })+ grantExists.mockResolvedValue(true)++ const out = await resolveInvocableMcpServersForContexts(g, NS, ['ctx-team'], CALLER, DB)++ expect(names(out)).toEqual(['gdrive-shared'])+ const key = grantExists.mock.calls[0][1]+ expect(key).toEqual({+ grantKind: 'shared',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'gdrive-shared',+ contextId: 'ctx-authoritative', // server's spec.contextRef, NOT the scoped ctx-team+ oauthClientId: 'google-drive',+ })+ // Shared key must not carry a userId — invocability is team-wide.+ expect(key).not.toHaveProperty('userId')+ })++ it('is invocable for a caller with NO user grant once the shared grant exists', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-team', ['gdrive-shared'])+ seedOauthServer(g, {+ name: 'gdrive-shared',+ grantScope: 'context',+ contextRef: 'ctx-team',+ oauthId: 'google-drive',+ })+ // The mock only answers 'shared' queries true; a 'user' query would be false.+ grantExists.mockImplementation(async (_db, input) => input.grantKind === 'shared')++ expect(+ names(await resolveInvocableMcpServersForContexts(g, NS, ['ctx-team'], CALLER, DB))+ ).toEqual(['gdrive-shared'])+ })+})++describe('resolveInvocableMcpServersForContexts — fail-closed + non-oauth', () => {+ it('never grant-gates a `none` server (always invocable, no oauthGrantExists call)', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-1', ['plain'])+ seedNoneServer(g, 'plain')++ const out = await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB)+ expect(names(out)).toEqual(['plain'])+ expect(grantExists).not.toHaveBeenCalled()+ })++ it('excludes a context-flavor server missing contextRef (fail-closed, no query issued)', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-1', ['ctx-server'])+ seedOauthServer(g, { name: 'ctx-server', grantScope: 'context', oauthId: 'google-drive' }) // no contextRef+ grantExists.mockResolvedValue(true)++ const out = await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB)+ expect(names(out)).toEqual([])+ expect(grantExists).not.toHaveBeenCalled()+ })++ it('excludes an OAuth server with no usable oauth.id (fail-closed, no query issued)', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-1', ['no-id'])+ seedOauthServer(g, {+ name: 'no-id',+ grantScope: 'user',+ contextRef: 'ctx-1',+ oauthId: undefined,+ })+ grantExists.mockResolvedValue(true)++ const out = await resolveInvocableMcpServersForContexts(g, NS, ['ctx-1'], CALLER, DB)+ expect(names(out)).toEqual([])+ expect(grantExists).not.toHaveBeenCalled()+ })++ it('a DB error on one server excludes ONLY that server; the request still resolves the rest', async () => {+ const g = new MockGateway(NS)+ seedContext(g, 'ctx-1', ['broken', 'plain', 'good'])+ seedOauthServer(g, {+ name: 'broken',+ grantScope: 'user',+ contextRef: 'ctx-1',+ oauthId: 'google-drive',+ })+ seedNoneServer(g, 'plain')+ seedOauthServer(g, {+ name: 'good',+ grantScope: 'user',+ contextRef: 'ctx-1',+ oauthId: 'google-drive',+ })++ grantExists.mockImplementation(async (_db, input) => {+ 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.+ expect(names(out)).toEqual(['good', 'plain'])+ expect(errSpy).toHaveBeenCalled()+ errSpy.mockRestore()+ })+})diff --git a/control-api/test/services.access.mcpInvocable.test.ts b/control-api/test/services.access.mcpInvocable.test.tsindex fc299a301..670932d13 100644--- a/control-api/test/services.access.mcpInvocable.test.ts+++ b/control-api/test/services.access.mcpInvocable.test.ts@@ -1,4 +1,5 @@import { describe, expect, it, vi } from 'vitest'+import type { DbClient } from '../src/db.js'import type { K8sGateway } from '../src/k8s.js'import {isK8sResourceNotFound,@@ -8,6 +9,13 @@ import {type Resource = Record<string, unknown>+// rpc-proxy rail caller identity + a DB that reports NO grants. These existing+// suites use `none`/`bearer`/disabled servers, which the grant-presence gate+// never touches, so the resolved list is unaffected — they double as a guard+// that `none` servers are NOT grant-gated.+const CALLER = 'user-1'+const NO_GRANTS_DB: DbClient = { query: async () => ({ rows: [], rowCount: 0 }) }+function gateway(resources: {contexts?: Resource[]mcpservers?: Resource[]@@ -71,7 +79,13 @@ describe('resolveInvocableMcpServersForContexts', () => {contexts: [ctx('trading', ['mcp-a', 'mcp-b']), ctx('business', ['mcp-c'])],mcpservers: [okServer('mcp-a'), okServer('mcp-b'), okServer('mcp-c')],})- const out = await resolveInvocableMcpServersForContexts(g, 'mcp-server', ['trading'])+ const out = await resolveInvocableMcpServersForContexts(+ g,+ 'mcp-server',+ ['trading'],+ CALLER,+ NO_GRANTS_DB+ )expect(out.map(s => s.name)).toEqual(['mcp-a', 'mcp-b'])expect(out[0].url).toContain('mcp-a.mcp-server.svc')})@@ -87,9 +101,9 @@ describe('resolveInvocableMcpServersForContexts', () => {},],})- const names = (await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'])).map(- s => s.name- )+ const names = (+ await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'], CALLER, NO_GRANTS_DB)+ ).map(s => s.name)expect(names).toEqual(['a'])})@@ -104,9 +118,9 @@ describe('resolveInvocableMcpServersForContexts', () => {},],})- const names = (await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'])).map(- s => s.name- )+ const names = (+ await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'], CALLER, NO_GRANTS_DB)+ ).map(s => s.name)expect(names).toEqual(['a'])})@@ -121,9 +135,9 @@ describe('resolveInvocableMcpServersForContexts', () => {},],})- const names = (await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'])).map(- s => s.name- )+ const names = (+ await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'], CALLER, NO_GRANTS_DB)+ ).map(s => s.name)expect(names).toEqual(['a'])})@@ -137,7 +151,13 @@ describe('resolveInvocableMcpServersForContexts', () => {},],})- const out = await resolveInvocableMcpServersForContexts(g, 'mcp-server', ['trading'])+ const out = await resolveInvocableMcpServersForContexts(+ g,+ 'mcp-server',+ ['trading'],+ CALLER,+ NO_GRANTS_DB+ )expect(out).toEqual([{ name: 'mcp-fred', url: 'http://mcp-fred.mcp-server.svc.cluster.local:3000/mcp' },])@@ -148,15 +168,17 @@ describe('resolveInvocableMcpServersForContexts', () => {contexts: [ctx('trading', ['a']), ctx('someone-else', ['b'])],mcpservers: [okServer('a'), okServer('b')],})- const names = (await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'])).map(- s => s.name- )+ const names = (+ await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'], CALLER, NO_GRANTS_DB)+ ).map(s => s.name)expect(names).toEqual(['a'])})it('returns an empty array when no contexts are in scope', async () => {const g = gateway({ contexts: [ctx('trading', ['a'])], mcpservers: [okServer('a')] })- expect(await resolveInvocableMcpServersForContexts(g, 'ns', [])).toEqual([])+ expect(await resolveInvocableMcpServersForContexts(g, 'ns', [], CALLER, NO_GRANTS_DB)).toEqual(+ []+ )})it('results are stable-sorted by name', async () => {@@ -164,9 +186,9 @@ describe('resolveInvocableMcpServersForContexts', () => {contexts: [ctx('trading', ['b', 'a', 'c'])],mcpservers: [okServer('a'), okServer('b'), okServer('c')],})- const names = (await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'])).map(- s => s.name- )+ const names = (+ await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'], CALLER, NO_GRANTS_DB)+ ).map(s => s.name)expect(names).toEqual(['a', 'b', 'c'])})})@@ -337,7 +359,13 @@ describe('parity: agent-scoped server names ⊆ RPC-flat-list for the same contemcpservers: [okServer('mcp-a'), okServer('mcp-b')],hosts: [host('trader', 'trading')],})- const rpc = await resolveInvocableMcpServersForContexts(g, 'ns', ['trading'])+ const rpc = await resolveInvocableMcpServersForContexts(+ g,+ 'ns',+ ['trading'],+ CALLER,+ NO_GRANTS_DB+ )const agents = await resolveMcpServersForAgents(g, {mcpServersNamespace: 'ns',hostsNamespace: 'mcp-host',