Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): expose mcp-server OAuth grants to external and admin lanes
Diego Zacarias5bdddd8d6f95
diff --git a/control-api/package.json b/control-api/package.jsonindex 9ac84821c..d3cc0edd9 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.587",+ "version": "0.1.588","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/store.ts b/control-api/src/oauth/store.tsindex 79639cb18..0a2aff1a3 100644--- a/control-api/src/oauth/store.ts+++ b/control-api/src/oauth/store.ts@@ -576,28 +576,48 @@ export async function setUserGrantBackground(}export interface UserGrantSummary {+ /** Owner domain of the grant; lets the client route the DELETE by owner (D-1). */+ ownerKind: OAuthOwnerKindrecipeNamespace: stringrecipeName: stringoauthClientId: stringprovider: stringbackground: booleanupdatedAt: Date+ /** Present only when `ownerKind==='mcpserver'`: the McpServer name (= recipe_name). */+ mcpServerName?: string}-/** All of a user's grants across recipes (for the Profile UI "Connected accounts" list). */+/**+ * All of a user's grants (for the Profile UI "Connected accounts" list).+ *+ * `ownerKind` selects the owner domain: the default `'recipe'` preserves the+ * historical recipe-only behavior byte-for-byte (invariant 3); `'all'` returns+ * both recipe and mcpserver grants (spec 04 D-1) so Profile UI can see and+ * revoke mcp-server identities; a specific kind filters to that one domain. The+ * query is not duplicated — the owner filter is parameterised in place (D4).+ */export async function listUserOAuthGrants(db: DbClient,- userId: string+ userId: string,+ ownerKind: OAuthOwnerKind | 'all' = 'recipe'): Promise<UserGrantSummary[]> {+ const params: unknown[] = [userId]+ let ownerFilter = ''+ if (ownerKind !== 'all') {+ params.push(ownerKind)+ ownerFilter = ` AND owner_kind = $${params.length}`+ }const result = await db.query(- `SELECT recipe_namespace, recipe_name, oauth_client_id, provider, background, updated_at+ `SELECT owner_kind, recipe_namespace, recipe_name, oauth_client_id, provider, background, updated_atFROM oauth_grants- WHERE owner_kind = 'recipe' AND user_id = $1 AND grant_kind = 'user'+ WHERE user_id = $1 AND grant_kind = 'user'${ownerFilter}ORDER BY recipe_name, oauth_client_id`,- [userId]+ params)return result.rows.map(r => {const row = r as {+ owner_kind: OAuthOwnerKindrecipe_namespace: stringrecipe_name: stringoauth_client_id: string@@ -605,7 +625,8 @@ export async function listUserOAuthGrants(background: booleanupdated_at: Date}- return {+ const summary: UserGrantSummary = {+ ownerKind: row.owner_kind,recipeNamespace: row.recipe_namespace,recipeName: row.recipe_name,oauthClientId: row.oauth_client_id,@@ -613,6 +634,12 @@ export async function listUserOAuthGrants(background: row.background,updatedAt: row.updated_at,}+ // For mcp-server owners the McpServer name lives in recipe_name; surface it+ // under a purpose-named field so the UI never parses the recipe field.+ if (row.owner_kind === 'mcpserver') {+ summary.mcpServerName = row.recipe_name+ }+ return summary})}@@ -635,6 +662,43 @@ export async function listUserGrantsForClient(})}+/**+ * All user grants for one mcp-server — admin oversight (read-only, spec 04 U3).+ *+ * Mirror of {@link listUserGrantsForClient} but keyed by the server coordinate+ * `(namespace, name)` WITHOUT an oauthClientId: it lists EVERY user grant of the+ * server across clients, returning each row's `oauthClientId` so the admin can+ * force-revoke a specific one. Scoped to `owner_kind='mcpserver'`,+ * `grant_kind='user'`.+ */+export async function listUserGrantsForServer(+ db: DbClient,+ key: { namespace: string; name: string }+): Promise<{ userId: string; oauthClientId: string; background: boolean; updatedAt: Date }[]> {+ const result = await db.query(+ `SELECT user_id, oauth_client_id, background, updated_at+ FROM oauth_grants+ WHERE owner_kind = 'mcpserver' AND recipe_namespace = $1 AND recipe_name = $2+ AND grant_kind = 'user'+ ORDER BY user_id, oauth_client_id`,+ [key.namespace, key.name]+ )+ return result.rows.map(r => {+ const row = r as {+ user_id: string+ oauth_client_id: string+ background: boolean+ updated_at: Date+ }+ return {+ userId: row.user_id,+ oauthClientId: row.oauth_client_id,+ background: row.background,+ updatedAt: row.updated_at,+ }+ })+}+/*** List the userIds with a background-consented user grant for (recipe, client).* SEC-6: scoped to one recipe + client; returns opaque platform user ids only.diff --git a/control-api/src/routes/admin/index.ts b/control-api/src/routes/admin/index.tsindex 445e10caa..dc9c18d87 100644--- a/control-api/src/routes/admin/index.ts+++ b/control-api/src/routes/admin/index.ts@@ -10,6 +10,7 @@ import { createAdminHostEnvRouter } from './hostEnv.js'import { createAdminHostsOverviewRouter } from './hostsOverview.js'import { createAdminLlmModelsRouter } from './llmModels.js'import { createAdminLlmPricesRouter } from './llmPrices.js'+import { createAdminMcpServerOauthRouter } from './mcpServerOauth.js'import { createAdminOutputsRouter } from './outputs.js'import { createAdminPersonalizationRouter } from './personalization.js'import { createAdminPluginWorkloadSdkRouter } from './pluginWorkloadSdk.js'@@ -36,6 +37,7 @@ export function createAdminRouter(gateway: K8sGateway): Router {router.use(createAdminResourcesRouter(gateway))router.use(createAdminRecipesRouter(gateway))router.use(createAdminRecipeOauthRouter(gateway))+ router.use(createAdminMcpServerOauthRouter())router.use(createAdminRegistryRouter(gateway))router.use(createRegistryConnectRouter())router.use(createAdminSharedFilesystemsRouter(gateway))diff --git a/control-api/src/routes/admin/mcpServerOauth.ts b/control-api/src/routes/admin/mcpServerOauth.tsnew file mode 100644index 000000000..45e3485b6--- /dev/null+++ b/control-api/src/routes/admin/mcpServerOauth.ts@@ -0,0 +1,116 @@+import { Router } from 'express'+import { config } from '../../config.js'+import { pool } from '../../db.js'+import { asyncHandler } from '../../http/asyncHandler.js'+import { RFC1123_RE } from '../../http/rfc1123.js'+import { UiAuthedRequest } from '../../middleware/controlUIAuth.js'+import { deleteOAuthGrant, listUserGrantsForServer } from '../../oauth/store.js'+import { rootLogger } from '../../observability/logger.js'++/**+ * Admin oversight for mcp-server OAuth user-grants (spec 04 U3) — the mirror of+ * the recipe lane (`recipeOauth.ts`) for `owner_kind='mcpserver'`. Mounted under+ * `/admin/*`, so `requireAuthForControlUI` (app.ts) has already authenticated the+ * caller as a control-ui admin.+ *+ * DEC-R2 (re-scope): a remote grant's coordinate (`oauth.id` = self-URL / base64+ * client_id) is NOT an RFC1123 label and is not even representable as a URL path+ * segment. So — unlike the recipe lane, where the client id is an RFC1123 path+ * param — the force-revoke takes the `oauthClientId` in the JSON BODY. Only the+ * server `:name` (a real RFC1123 label) stays in the path.+ *+ * The server namespace is always forced to `config.mcpServersNamespace`, never+ * taken from the request.+ */++const MCP_SERVER_NAMESPACE = config.mcpServersNamespace+const BASE = '/admin/mcp-servers'++function dbClient() {+ return { query: (text: string, values?: unknown[]) => pool.query(text, values) }+}++export function createAdminMcpServerOauthRouter(): Router {+ const router = Router()+ const log = rootLogger.child({ module: 'admin-mcpserver-oauth' })++ // GET /admin/mcp-servers/:name/oauth/user-grants+ // Read-only list of every user with a grant for this server (across clients).+ // Namespace is forced to MCP_SERVER_NAMESPACE — never taken from the request.+ router.get(+ `${BASE}/:name/oauth/user-grants`,+ asyncHandler(async (req: UiAuthedRequest, res) => {+ const { name } = req.params+ if (!RFC1123_RE.test(name)) {+ res.status(400).json({ error: 'invalid_request' })+ return+ }+ const users = await listUserGrantsForServer(dbClient(), {+ namespace: MCP_SERVER_NAMESPACE,+ name,+ })+ res.status(200).json({+ users: users.map(u => ({ ...u, updatedAt: u.updatedAt.toISOString() })),+ })+ })+ )++ // DELETE /admin/mcp-servers/:name/oauth/user-grants/:userId body: { oauthClientId }+ // Force-revoke one user's grant (admin oversight). The client id is arbitrary+ // (self-URL / base64), so it rides in the body and is NOT RFC1123-validated.+ // Namespace is forced to MCP_SERVER_NAMESPACE. Idempotent: 204 whether or not a+ // row existed.+ //+ // Force-revoke deletes ONLY this user's grant row. It does NOT delete+ // `dynamic_clients` (per-server-CR, shared across users); that teardown lives+ // in the server-CR uninstall (DEC-R2 §3).+ router.delete(+ `${BASE}/:name/oauth/user-grants/:userId`,+ asyncHandler(async (req: UiAuthedRequest, res) => {+ const { name, userId } = req.params+ if (!RFC1123_RE.test(name)) {+ res.status(400).json({ error: 'invalid_request' })+ return+ }+ if (typeof userId !== 'string' || userId.length === 0) {+ res.status(400).json({ error: 'invalid_request' })+ return+ }+ const { oauthClientId } = (req.body ?? {}) as { oauthClientId?: unknown }+ if (typeof oauthClientId !== 'string' || oauthClientId.length === 0) {+ res.status(400).json({ error: 'invalid_request' })+ return+ }+ const adminUserId = req.adminAuth?.sub+ if (!adminUserId) {+ res.status(401).json({ error: 'Unauthorized' })+ return+ }+ await deleteOAuthGrant(dbClient(), {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: MCP_SERVER_NAMESPACE,+ recipeName: name,+ userId,+ oauthClientId,+ })+ // Audit trail (sensitive: a revocation). Structured, pino-redacted; the+ // same event the recipe lane emits, parameterised with owner_kind mcpserver.+ log.info(+ {+ event: 'oauth_user_grant_force_revoked',+ ownerKind: 'mcpserver',+ mcpServerNamespace: MCP_SERVER_NAMESPACE,+ mcpServerName: name,+ oauthClientId,+ targetUserId: userId,+ adminUserId,+ },+ 'force-revoked user grant'+ )+ res.status(204).end()+ })+ )++ return router+}diff --git a/control-api/src/routes/external/oauthGrants.ts b/control-api/src/routes/external/oauthGrants.tsindex c3ae753cc..8e91d37c3 100644--- a/control-api/src/routes/external/oauthGrants.ts+++ b/control-api/src/routes/external/oauthGrants.ts@@ -6,12 +6,31 @@ import {type ExternalAuthedRequest,requireValidExternalSessionToken,} from '../../middleware/externalSessionAuth.js'-import { deleteOAuthGrant, listUserOAuthGrants } from '../../oauth/store.js'+import { type OAuthOwnerKind, deleteOAuthGrant, listUserOAuthGrants } from '../../oauth/store.js'function dbClient() {return { query: (text: string, values?: unknown[]) => pool.query(text, values) }}+/**+ * The exact wire shape Profile UI parses (frozen contract, spec 04 U2). Built by+ * an explicit allowlist — never a blind spread of the store row — so a new+ * `UserGrantSummary` column can never leak to the browser as public API.+ * `recipeNamespace`/`recipeName` keep their historical names (additive change:+ * only `ownerKind` + optional `mcpServerName` are new), so the recipe parsing in+ * profile-ui keeps working unchanged.+ */+interface GrantView {+ ownerKind: OAuthOwnerKind+ recipeNamespace: string+ recipeName: string+ oauthClientId: string+ provider: string+ background: boolean+ updatedAt: string+ mcpServerName?: string+}+/*** User-facing OAuth grant management (Profile UI → external-rest-api → here).*@@ -43,9 +62,23 @@ export function createExternalOauthGrantsRouter(): Router {res.status(401).json({ error: 'Unauthorized' })return}- const grants = await listUserOAuthGrants(dbClient(), userId)+ // 'all' — surface both recipe and mcp-server owned grants; the client+ // routes each DELETE by its ownerKind.+ const grants = await listUserOAuthGrants(dbClient(), userId, 'all')res.status(200).json({- grants: grants.map(g => ({ ...g, updatedAt: g.updatedAt.toISOString() })),+ grants: grants.map((g): GrantView => {+ const view: GrantView = {+ ownerKind: g.ownerKind,+ recipeNamespace: g.recipeNamespace,+ recipeName: g.recipeName,+ oauthClientId: g.oauthClientId,+ provider: g.provider,+ background: g.background,+ updatedAt: g.updatedAt.toISOString(),+ }+ if (g.mcpServerName !== undefined) view.mcpServerName = g.mcpServerName+ return view+ }),})} catch (err) {next(err)@@ -54,9 +87,14 @@ export function createExternalOauthGrantsRouter(): Router {})- // DELETE /external/oauth/grants/:recipeNamespace/:recipeName/:oauthClientId+ // DELETE /external/oauth/grants/:recipeNamespace/:recipeName/:oauthClientId?ownerKind=// Revokes one grant for the authenticated user. Idempotent: 204 whether or not a- // row existed (no information leak).+ // row existed (no information leak). `ownerKind` (default 'recipe') routes the+ // delete to the recipe or mcp-server domain.+ //+ // The revocation deletes ONLY this user's grant row (deleteOAuthGrant). It does+ // NOT delete `dynamic_clients` (per-server-CR, shared across users); that+ // teardown lives in the server-CR uninstall (DEC-R2 §3 / aligns with H-3).router.delete('/external/oauth/grants/:recipeNamespace/:recipeName/:oauthClientId',...externalOauthGrantsRateLimits,@@ -69,9 +107,24 @@ export function createExternalOauthGrantsRouter(): Router {res.status(401).json({ error: 'Unauthorized' })return}+ const ownerKindRaw =+ req.query.ownerKind === undefined ? 'recipe' : String(req.query.ownerKind)+ if (ownerKindRaw !== 'recipe' && ownerKindRaw !== 'mcpserver') {+ res.status(400).json({ error: 'invalid_request' })+ return+ }+ const ownerKind: OAuthOwnerKind = ownerKindRaw+ // Force the owner namespace server-side by ownerKind (D-2, invariant 7),+ // mirroring the internal lane (internal/oauth.ts): never trust the+ // path-supplied namespace for the delete coordinate. The delete stays+ // scoped to the session userId, so a user can only ever revoke their own+ // grant, and only within the correct owner namespace.+ const recipeNamespace =+ ownerKind === 'mcpserver' ? config.mcpServersNamespace : config.sandboxNamespaceawait deleteOAuthGrant(dbClient(), {grantKind: 'user',- recipeNamespace: String(req.params.recipeNamespace),+ ownerKind,+ recipeNamespace,recipeName: String(req.params.recipeName),userId,oauthClientId: String(req.params.oauthClientId),diff --git a/control-api/test/adminMcpServerOauth.userGrants.test.ts b/control-api/test/adminMcpServerOauth.userGrants.test.tsnew file mode 100644index 000000000..8902d82de--- /dev/null+++ b/control-api/test/adminMcpServerOauth.userGrants.test.ts@@ -0,0 +1,164 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import express, { type NextFunction, type Request, type Response } from 'express'+import request from 'supertest'+import { config } from '../src/config.js'+import { rootLogger } from '../src/observability/logger.js'+import { createAdminMcpServerOauthRouter } from '../src/routes/admin/mcpServerOauth.js'++// Mock the pool — same pattern as adminRecipeOauth.userGrants.test.ts.+const mockPoolQuery = vi.fn()+vi.mock('../src/db.js', () => ({+ pool: {+ query: (...args: unknown[]) => mockPoolQuery(...args),+ },+}))++// Mock the store so we can assert calls without a real DB.+const storeMock = vi.hoisted(() => ({+ listUserGrantsForServer: vi.fn(),+ deleteOAuthGrant: vi.fn(),+}))+vi.mock('../src/oauth/store.js', () => storeMock)++const MCP_NS = config.mcpServersNamespace++// Capture the module child logger's info(...) — the factory builds+// `rootLogger.child({ module: 'admin-mcpserver-oauth' })` at router-create time,+// so a spy on `rootLogger.child` installed before makeAuthedApp intercepts it.+const infoSpy = vi.fn()+const fakeChild = {+ info: infoSpy,+ error: vi.fn(),+ warn: vi.fn(),+ debug: vi.fn(),+ trace: vi.fn(),+ fatal: vi.fn(),+ child() {+ return fakeChild+ },+}++function makeAuthedApp(adminSub = 'admin-alice') {+ const app = express()+ app.use(express.json())+ app.use(+ (+ req: Request & {+ adminAuth?: { sub: string; role: string; jti: string; exp: number; typ: 'user' }+ },+ _res: Response,+ next: NextFunction+ ) => {+ req.adminAuth = {+ sub: adminSub,+ role: 'admin',+ jti: 'test-jti',+ exp: 9999999999,+ typ: 'user',+ }+ next()+ }+ )+ app.use(createAdminMcpServerOauthRouter())+ return app+}++function auditPayload(): Record<string, unknown> | undefined {+ const call = infoSpy.mock.calls.find(+ ([obj]) =>+ obj &&+ typeof obj === 'object' &&+ (obj as { event?: unknown }).event === 'oauth_user_grant_force_revoked'+ )+ return call?.[0] as Record<string, unknown> | undefined+}++describe('admin mcp-server per-user grants (DEC-R2)', () => {+ let childSpy: ReturnType<typeof vi.spyOn>+ let app: ReturnType<typeof makeAuthedApp>++ beforeEach(() => {+ vi.clearAllMocks()+ childSpy = vi.spyOn(rootLogger, 'child').mockReturnValue(fakeChild as never)+ storeMock.listUserGrantsForServer.mockResolvedValue([])+ storeMock.deleteOAuthGrant.mockResolvedValue(0)+ mockPoolQuery.mockReset()+ mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })+ app = makeAuthedApp()+ })++ afterEach(() => {+ childSpy.mockRestore()+ })++ it('GET lists the server user grants (namespace forced to mcp-servers)', async () => {+ storeMock.listUserGrantsForServer.mockResolvedValue([+ {+ userId: 'u1',+ oauthClientId: 'self://url',+ background: false,+ updatedAt: new Date('2026-06-02'),+ },+ ])+ const res = await request(app).get('/admin/mcp-servers/gdrive/oauth/user-grants').expect(200)+ expect(res.body.users[0]).toMatchObject({ userId: 'u1', oauthClientId: 'self://url' })+ expect(typeof res.body.users[0].updatedAt).toBe('string')+ expect(storeMock.listUserGrantsForServer).toHaveBeenCalledWith(expect.anything(), {+ namespace: MCP_NS,+ name: 'gdrive',+ })+ })++ it('GET rejects a non-RFC1123 server name with 400', async () => {+ await request(app).get('/admin/mcp-servers/Bad_Name/oauth/user-grants').expect(400)+ expect(storeMock.listUserGrantsForServer).not.toHaveBeenCalled()+ })++ it('DELETE force-revokes by (name, userId) + body oauthClientId; namespace forced; ownerKind mcpserver', async () => {+ const res = await request(app)+ .delete('/admin/mcp-servers/gdrive/oauth/user-grants/u1')+ .send({ oauthClientId: 'https://as.example/.well-known/oauth' })+ .expect(204)+ expect(res.status).toBe(204)+ expect(storeMock.deleteOAuthGrant).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: MCP_NS,+ recipeName: 'gdrive',+ userId: 'u1',+ oauthClientId: 'https://as.example/.well-known/oauth',+ })+ )+ })++ it('DELETE emits the oauth_user_grant_force_revoked audit with owner_kind mcpserver', async () => {+ await request(app)+ .delete('/admin/mcp-servers/gdrive/oauth/user-grants/u1')+ .send({ oauthClientId: 'self://url' })+ .expect(204)+ expect(auditPayload()).toMatchObject({+ event: 'oauth_user_grant_force_revoked',+ ownerKind: 'mcpserver',+ mcpServerNamespace: MCP_NS,+ mcpServerName: 'gdrive',+ oauthClientId: 'self://url',+ targetUserId: 'u1',+ adminUserId: 'admin-alice',+ })+ })++ it('DELETE without a body oauthClientId is 400 and never touches the store', async () => {+ await request(app).delete('/admin/mcp-servers/gdrive/oauth/user-grants/u1').send({}).expect(400)+ expect(storeMock.deleteOAuthGrant).not.toHaveBeenCalled()+ })++ it('DELETE rejects a non-RFC1123 server name with 400', async () => {+ await request(app)+ .delete('/admin/mcp-servers/Bad_Name/oauth/user-grants/u1')+ .send({ oauthClientId: 'self://url' })+ .expect(400)+ expect(storeMock.deleteOAuthGrant).not.toHaveBeenCalled()+ })+})diff --git a/control-api/test/oauth.store.list.test.ts b/control-api/test/oauth.store.list.test.tsindex 718a1668d..b419bdda8 100644--- a/control-api/test/oauth.store.list.test.ts+++ b/control-api/test/oauth.store.list.test.ts@@ -1,6 +1,6 @@-import { describe, it, expect } from 'vitest'+import { describe, expect, it } from 'vitest'import type { DbClient } from '../src/db.js'-import { listUserOAuthGrants, listUserGrantsForClient } from '../src/oauth/store.js'+import { listUserGrantsForClient, listUserOAuthGrants } from '../src/oauth/store.js'function fakeDb(rows: unknown[]): { db: DbClient; calls: { text: string; values: unknown[] }[] } {const calls: { text: string; values: unknown[] }[] = []@@ -14,9 +14,10 @@ function fakeDb(rows: unknown[]): { db: DbClient; calls: { text: string; values:}describe('store list', () => {- it('listUserOAuthGrants scopes to the user and maps rows', async () => {+ it('listUserOAuthGrants defaults to the recipe domain and maps rows (byte-identical, + ownerKind)', async () => {const { db, calls } = fakeDb([{+ owner_kind: 'recipe',recipe_namespace: 'sandbox-recipes',recipe_name: 'leadforge',oauth_client_id: 'google-gmail',@@ -27,8 +28,11 @@ describe('store list', () => {])const out = await listUserOAuthGrants(db, 'user-1')expect(calls[0].text).toContain("grant_kind = 'user'")- expect(calls[0].values).toEqual(['user-1'])+ // The default filters to the recipe owner domain (invariant 3).+ expect(calls[0].text).toContain('owner_kind = $2')+ expect(calls[0].values).toEqual(['user-1', 'recipe'])expect(out[0]).toEqual({+ ownerKind: 'recipe',recipeNamespace: 'sandbox-recipes',recipeName: 'leadforge',oauthClientId: 'google-gmail',@@ -36,10 +40,42 @@ describe('store list', () => {background: true,updatedAt: new Date('2026-06-01'),})+ // Recipe grants carry no mcpServerName.+ expect(out[0]).not.toHaveProperty('mcpServerName')+ })++ it("listUserOAuthGrants('all') drops the owner filter and derives mcpServerName for mcpserver rows", async () => {+ const { db, calls } = fakeDb([+ {+ owner_kind: 'mcpserver',+ recipe_namespace: 'mcp-servers',+ recipe_name: 'gdrive',+ oauth_client_id: 'self://url',+ provider: 'remote',+ background: false,+ updated_at: new Date('2026-06-03'),+ },+ ])+ const out = await listUserOAuthGrants(db, 'user-1', 'all')+ // No owner_kind filter and no owner param when listing all domains.+ expect(calls[0].text).not.toContain('owner_kind =')+ expect(calls[0].values).toEqual(['user-1'])+ expect(out[0]).toEqual({+ ownerKind: 'mcpserver',+ recipeNamespace: 'mcp-servers',+ recipeName: 'gdrive',+ oauthClientId: 'self://url',+ provider: 'remote',+ background: false,+ updatedAt: new Date('2026-06-03'),+ mcpServerName: 'gdrive',+ })})it('listUserGrantsForClient scopes to recipe+client and returns userId+background', async () => {- const { db, calls } = fakeDb([{ user_id: 'a', background: true, updated_at: new Date('2026-06-02') }])+ const { db, calls } = fakeDb([+ { user_id: 'a', background: true, updated_at: new Date('2026-06-02') },+ ])const out = await listUserGrantsForClient(db, {recipeNamespace: 'sandbox-recipes',recipeName: 'leadforge',diff --git a/control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.ts b/control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.tsnew file mode 100644index 000000000..09f0bc614--- /dev/null+++ b/control-api/test/oauth.store.userGrantsListing.realPostgres.integration.test.ts@@ -0,0 +1,177 @@+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 {+ deleteOAuthGrant,+ listUserGrantsForServer,+ listUserOAuthGrants,+ upsertOAuthGrant,+} from '../src/oauth/store.js'++// T1/T3/T4/T5 (spec 04 U1/U3) — the owner-generalised grant listing exercised+// against grants written by the REAL producer (`upsertOAuthGrant`), never a+// hand-built oauth_grants fixture (the mcpserver recipe_namespace/recipe_name+// shape is subtle). Gated on a real Postgres, like the other+// *.realPostgres.integration.test.ts:+// CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \+// test/oauth.store.userGrantsListing.realPostgres.integration.test.ts+//+// T3: "the user sees their mcpserver grant via listUserOAuthGrants('all')" FAILS+// at the parent sha (16efcaa7e), where listUserOAuthGrants takes (db, userId) and+// hardcodes owner_kind='recipe' — the third arg is ignored and the mcpserver+// grant never appears.+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 USER = 'user-42'+const MCP_NS = config.mcpServersNamespace+const RECIPE_NS = config.sandboxNamespace++describeRealPostgres('listUserOAuthGrants / listUserGrantsForServer (real Postgres)', () => {+ const database = `control_api_user_grants_${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()+ }+ })++ beforeEach(async () => {+ await dbPool.query('DELETE FROM oauth_grants')+ })++ // The two grants the user actually owns, written by the real ALTA path.+ async function seedRecipeAndMcpserverGrants(): Promise<void> {+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ // owner_kind defaults to 'recipe'+ recipeNamespace: RECIPE_NS,+ recipeName: 'leadforge',+ userId: USER,+ oauthClientId: 'google-gmail',+ provider: 'google',+ accessToken: 'RECIPE-TOKEN',+ })+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: MCP_NS,+ recipeName: 'gdrive',+ userId: USER,+ oauthClientId: 'self://as.example/x',+ provider: 'remote',+ accessToken: 'MCP-TOKEN',+ })+ }++ it("T3/T4 — 'all' surfaces both owners with ownerKind + mcpServerName; default stays recipe-only (T5)", async () => {+ await seedRecipeAndMcpserverGrants()++ const all = await listUserOAuthGrants(db, USER, 'all')+ const byServer = Object.fromEntries(all.map(g => [g.recipeName, g]))+ expect(all).toHaveLength(2)+ expect(byServer.leadforge).toMatchObject({ ownerKind: 'recipe' })+ expect(byServer.leadforge.mcpServerName).toBeUndefined()+ expect(byServer.gdrive).toMatchObject({+ ownerKind: 'mcpserver',+ mcpServerName: 'gdrive',+ oauthClientId: 'self://as.example/x',+ })++ // T5 — the default preserves the historical recipe-only behavior: the+ // mcpserver grant is NOT returned.+ const recipeOnly = await listUserOAuthGrants(db, USER)+ expect(recipeOnly).toHaveLength(1)+ expect(recipeOnly[0]).toMatchObject({ ownerKind: 'recipe', recipeName: 'leadforge' })+ })++ it('T4 — the mcpserver grant disappears from the observable list after deleteOAuthGrant', async () => {+ await seedRecipeAndMcpserverGrants()+ expect(await listUserOAuthGrants(db, USER, 'all')).toHaveLength(2)++ const deleted = await deleteOAuthGrant(db, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: MCP_NS,+ recipeName: 'gdrive',+ userId: USER,+ oauthClientId: 'self://as.example/x',+ })+ expect(deleted).toBe(1)++ const after = await listUserOAuthGrants(db, USER, 'all')+ expect(after).toHaveLength(1)+ expect(after[0]).toMatchObject({ ownerKind: 'recipe', recipeName: 'leadforge' })+ })++ it('listUserGrantsForServer lists all users of a server across clients (U3 admin oversight)', async () => {+ // Two users, two clients on the same server — plus a recipe grant that must+ // never bleed into the server listing.+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: MCP_NS,+ recipeName: 'gdrive',+ userId: 'user-a',+ oauthClientId: 'self://client-1',+ provider: 'remote',+ accessToken: 'A1',+ })+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: MCP_NS,+ recipeName: 'gdrive',+ userId: 'user-b',+ oauthClientId: 'self://client-2',+ provider: 'remote',+ accessToken: 'B2',+ })+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ recipeNamespace: RECIPE_NS,+ recipeName: 'gdrive',+ userId: 'user-a',+ oauthClientId: 'google-gmail',+ provider: 'google',+ accessToken: 'RECIPE',+ })++ const rows = await listUserGrantsForServer(db, { namespace: MCP_NS, name: 'gdrive' })+ expect(rows).toHaveLength(2)+ expect(rows.map(r => `${r.userId}:${r.oauthClientId}`).sort()).toEqual([+ 'user-a:self://client-1',+ 'user-b:self://client-2',+ ])+ })+})diff --git a/control-api/test/routes.external.oauthGrants.test.ts b/control-api/test/routes.external.oauthGrants.test.tsindex f71f84646..3d00a160f 100644--- a/control-api/test/routes.external.oauthGrants.test.ts+++ b/control-api/test/routes.external.oauthGrants.test.ts@@ -1,6 +1,7 @@import { beforeEach, describe, expect, it, vi } from 'vitest'import express from 'express'import request from 'supertest'+import { config } from '../src/config.js'import { createExternalOauthGrantsRouter } from '../src/routes/external/oauthGrants.js'// Mock the pool used inside the router (no real DB needed).@@ -49,9 +50,13 @@ describe('/external/oauth/grants', () => {storeMock.deleteOAuthGrant.mockResolvedValue(undefined)})- it("GET lists only the caller's grants (userId from session)", async () => {+ // T3 (route wiring): fails at the parent sha, where GET calls+ // listUserOAuthGrants(db, userId) with only two args (recipe-only) — so the+ // 'all' assertion below is not satisfied.+ it("GET lists the caller's grants of BOTH owners (ownerKind='all', userId from session)", async () => {storeMock.listUserOAuthGrants.mockResolvedValue([{+ ownerKind: 'recipe',recipeNamespace: 'sandbox-recipes',recipeName: 'leadforge',oauthClientId: 'google-gmail',@@ -59,27 +64,76 @@ describe('/external/oauth/grants', () => {background: true,updatedAt: new Date('2026-06-01'),},+ {+ ownerKind: 'mcpserver',+ recipeNamespace: config.mcpServersNamespace,+ recipeName: 'gdrive',+ oauthClientId: 'self://url',+ provider: 'remote',+ background: false,+ updatedAt: new Date('2026-06-02'),+ mcpServerName: 'gdrive',+ },])const res = await request(makeApp()).get('/external/oauth/grants')expect(res.status).toBe(200)- expect(storeMock.listUserOAuthGrants).toHaveBeenCalledWith(expect.anything(), 'user-1')- expect(res.body.grants[0].recipeName).toBe('leadforge')+ expect(storeMock.listUserOAuthGrants).toHaveBeenCalledWith(expect.anything(), 'user-1', 'all')+ expect(res.body.grants[0]).toMatchObject({ ownerKind: 'recipe', recipeName: 'leadforge' })+ expect(res.body.grants[0]).not.toHaveProperty('mcpServerName')+ expect(res.body.grants[1]).toMatchObject({+ ownerKind: 'mcpserver',+ recipeName: 'gdrive',+ mcpServerName: 'gdrive',+ })})- it("DELETE revokes the caller's grant (userId from session, not body)", async () => {+ it('DELETE (default ownerKind) revokes the recipe grant, namespace forced to sandbox (userId from session)', async () => {const res = await request(makeApp()).delete(- '/external/oauth/grants/sandbox-recipes/leadforge/google-gmail'+ '/external/oauth/grants/anything-here/leadforge/google-gmail')expect(res.status).toBe(204)expect(storeMock.deleteOAuthGrant).toHaveBeenCalledWith(expect.anything(),expect.objectContaining({grantKind: 'user',+ ownerKind: 'recipe',userId: 'user-1',- recipeNamespace: 'sandbox-recipes',+ // Forced server-side, NOT taken from the vestigial path namespace.+ recipeNamespace: config.sandboxNamespace,recipeName: 'leadforge',oauthClientId: 'google-gmail',}))})++ // T3 (route wiring): fails at the parent sha, where DELETE never reads+ // ?ownerKind and never passes ownerKind to deleteOAuthGrant (defaults recipe)+ // nor forces the mcp-server namespace.+ it('DELETE ?ownerKind=mcpserver revokes the mcpserver grant, namespace forced to mcp-servers', async () => {+ const selfUrl = encodeURIComponent('https://as.example/.well-known/x')+ const res = await request(makeApp()).delete(+ `/external/oauth/grants/anything-here/gdrive/${selfUrl}?ownerKind=mcpserver`+ )+ expect(res.status).toBe(204)+ expect(storeMock.deleteOAuthGrant).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({+ grantKind: 'user',+ ownerKind: 'mcpserver',+ userId: 'user-1',+ recipeNamespace: config.mcpServersNamespace,+ recipeName: 'gdrive',+ // Arbitrary self-URL coordinate arrives as one decoded path segment.+ oauthClientId: 'https://as.example/.well-known/x',+ })+ )+ })++ it('DELETE with an invalid ownerKind is rejected 400 and never touches the store', async () => {+ const res = await request(makeApp()).delete(+ '/external/oauth/grants/anything/gdrive/client?ownerKind=bogus'+ )+ expect(res.status).toBe(400)+ expect(storeMock.deleteOAuthGrant).not.toHaveBeenCalled()+ })})