Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): bind OAuth grants/exists to the authenticated Host (S-05 F1)
Diego Zacarias14613e7ea968
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex fee88a17c..cfa74257d 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.817",+ "version": "0.1.818","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.817",+ "version": "0.1.818","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex e5d0b39ce..9906debd5 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.817",+ "version": "0.1.818","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex f118ea9a4..b34e7d517 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -28,6 +28,7 @@ import { type OAuthGrantKey, oauthGrantExists } from '../oauth/store.js'import { type Logger, rootLogger } from '../observability/logger.js'import { mcpOauthBrokerDeniedTotal } from '../observability/metrics.js'import {+ type ResolvedHostBinding,checkBrokerCallerLineage,hasContextIdMismatch,hostAccessForUser,@@ -224,143 +225,254 @@ export interface GrantExistsResult {exists: boolean}+/**+ * The coordinates of one untrusted batch entry, echoed back exactly as they+ * arrived so the consumer correlates by tuple. A non-string `mcpServerName`+ * cannot address a server and echoes as ''.+ */+function parseGrantExistsEntry(raw: unknown): GrantExistsQuery {+ const entry = (raw && typeof raw === 'object' ? raw : {}) as Record<string, unknown>+ const parsed: GrantExistsQuery = {+ mcpServerName: typeof entry.mcpServerName === 'string' ? entry.mcpServerName : '',+ }+ if (typeof entry.userId === 'string') parsed.userId = entry.userId+ if (typeof entry.contextId === 'string') parsed.contextId = entry.contextId+ return parsed+}++function echoGrantExistsEntry(entry: GrantExistsQuery, exists: boolean): GrantExistsResult {+ return { ...entry, exists }+}+export interface GrantExistenceDeps {db: DbClient- gateway: K8sGateway+ gateway: Pick<K8sGateway, 'getResource'>+ /** The calling Host, already resolved live: every entry is judged against it. */+ binding: ResolvedHostBindingmcpServersNamespace: stringlog?: Logger}+type BrokerRoute = 'user_token' | 'grants_exists'++function recordBrokerDenial(+ log: Logger,+ route: BrokerRoute,+ reason: BrokerDenialReason,+ context: Record<string, unknown>,+ level: 'warn' | 'debug' = 'warn'+): void {+ mcpOauthBrokerDeniedTotal.inc({ reason, route }, 1)+ log[level](+ { event: 'mcp_oauth_broker_denied', reason, route, ...context },+ 'mcp oauth broker denied'+ )+}++/** What one mcp-server contributes to every entry that names it in a batch. */+type ServerVerdict =+ | { kind: 'deny'; reason: 'server_not_found' | 'context_ref_mismatch' }+ // Cannot be decided now, or nothing to evict: keep the partition. `cause` is+ // set only for a transient read failure, which is reported per entry.+ | { kind: 'error'; cause?: { err: unknown } }+ | { kind: 'resolved'; resolved: NonNullable<ReturnType<typeof resolveServerOAuth>> }+/**- * 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.+ * Batch grant-existence resolver for the hot-revocation sweep, bound to the+ * calling Host (`deps.binding`). Each entry gets the `user-token` rules, but a+ * definitive denial answers `exists:false` (mcp-host evicts the partition) and+ * anything transient or undecidable answers `exists:true` (mcp-host keeps it):+ * an apiserver or DB blip must never disconnect a user.*- * 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.+ * - outside the Host Context's allowlist (exact match), being deleted or+ * disabled → false; outside the allowlist the CR is never read;+ * - allowlisted but the CR is gone → true: an uninstall in flight is not+ * this sweep's to evict (the uninstall itself purges grants);+ * - read error, not an OAuth server, a per-user entry without userId → true;+ * - context-scope owned by another Context or without one → false;+ * - per-user: non-UUID userId or a user who cannot enter the Host → false,+ * a DB error checking that → true;+ * - otherwise the store decides (`oauthGrantExists`, never the token).*- * 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`.+ * Strictly 1:1 and in order with the input, each result echoing its entry's+ * coordinates; a malformed entry gets a fail-open placeholder in its slot.+ * Every mcp-server is read once and every userId's Host access queried once+ * per batch; denials are logged and counted once per (reason, mcp-server).*/export async function resolveBatchGrantExistence(deps: GrantExistenceDeps,queries: readonly unknown[]): Promise<GrantExistsResult[]> {const log = deps.log ?? rootLogger+ const { binding } = depsconst results: GrantExistsResult[] = []- // Memoize the CR resolution by `mcpServerName` for the lifetime of THIS batch.- // The sweep fans a per-user partition out to one entry per user, so a shared- // server with N live users produces N IDENTICAL apiserver reads of the same CR- // (mini-spec 13 Should-fix #1). The apiserver read + `resolveServerOAuth`- // depend ONLY on the server name (not on userId), so they are resolved once- // per distinct name; the grant SELECT still runs per entry (it keys by userId).- //- // A `null` entry is the memoized fail-open verdict for a server whose CR read- // threw (deleted CR / apiserver blip) OR did not resolve as OAuth — both yield- // `exists:true` per entry exactly as before, and neither is retried N times.- // `.has()` distinguishes "not yet read" from "read → null", so a failed read is- // cached, never re-attempted within the batch.- const serverOAuthCache = new Map<string, ReturnType<typeof resolveServerOAuth>>()- const resolveServerOAuthCached = async (- name: string- ): Promise<ReturnType<typeof resolveServerOAuth>> => {- if (serverOAuthCache.has(name)) return serverOAuthCache.get(name) ?? null- let resolved: ReturnType<typeof resolveServerOAuth>+ type Denial = {+ reason: BrokerDenialReason+ mcpServerName: string+ entries: number+ warn: boolean+ detail: Record<string, unknown>+ }+ const denials = new Map<string, Denial>()+ // Called once per affected entry; the first call's detail (stage, err) is kept.+ const noteDenial = (+ reason: BrokerDenialReason,+ mcpServerName: string,+ opts: { warn?: boolean; detail?: Record<string, unknown> } = {}+ ) => {+ const warn = opts.warn ?? true+ const key = `${reason}\u0000${mcpServerName}`+ const seen = denials.get(key)+ if (seen) {+ seen.entries += 1+ seen.warn ||= warn+ } else {+ denials.set(key, { reason, mcpServerName, entries: 1, warn, detail: opts.detail ?? {} })+ }+ }++ const serverVerdicts = new Map<string, ServerVerdict>()+ const serverVerdict = async (name: string): Promise<ServerVerdict> => {+ const memo = serverVerdicts.get(name)+ if (memo) return memo+ const verdict = await readServerVerdict(name)+ serverVerdicts.set(name, verdict)+ return verdict+ }+ const readServerVerdict = async (name: string): Promise<ServerVerdict> => {+ if (!binding.allowlist.includes(name)) return { kind: 'deny', reason: 'server_not_found' }+ let server: McpServerResourcetry {- const server = (await deps.gateway.getResource(+ server = (await deps.gateway.getResource('mcpservers',name,deps.mcpServersNamespace)) as McpServerResource- resolved = resolveServerOAuth(server)- if (!resolved) {- // Not an OAuth server / no usable oauth id → ambiguous, fail-open.+ } catch (err) {+ if (isK8sResourceNotFound(err)) {log.warn({ mcpServerName: name },- 'grant-existence: server not resolvable as oauth; fail-open'+ 'grant-existence: allowlisted server not found; fail-open')+ return { kind: 'error' }}- } catch (err) {- // Server not found (deleted CR) or apiserver blip — transient/ambiguous.- // Fail-open: never evict a live partition on a hiccup.+ return { kind: 'error', cause: { err } }+ }+ if (!server || !isLive(server.metadata) || server.spec?.enabled === false) {+ return { kind: 'deny', reason: 'server_not_found' }+ }+ const resolved = resolveServerOAuth(server)+ if (server.spec?.auth?.type !== 'oauth' || !resolved) {log.warn(- { err, mcpServerName: name },- 'grant-existence: server read failed; fail-open (exists:true)'+ { mcpServerName: name },+ 'grant-existence: server not resolvable as oauth; fail-open')- resolved = null+ return { kind: 'error' }}- serverOAuthCache.set(name, resolved)- return resolved+ if (resolved.grantScope === 'context' && resolved.contextRef !== binding.contextName) {+ return { kind: 'deny', reason: 'context_ref_mismatch' }+ }+ return { kind: 'resolved', resolved }}- 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+ type Access = { kind: 'allowed' } | { kind: 'denied' } | { kind: 'error'; err: unknown }+ const userAccess = new Map<string, Access>()+ const accessFor = async (userId: string): Promise<Access> => {+ const memo = userAccess.get(userId)+ if (memo) return memo+ let access: Access+ try {+ access = { kind: await hostAccessForUser(deps.db, userId, binding.hostName) }+ } catch (err) {+ access = { kind: 'error', err }}+ userAccess.set(userId, access)+ return access+ }++ for (const raw of queries) {+ const entry = parseGrantExistsEntry(raw)+ const { mcpServerName, userId } = entry+ const echo = (exists: boolean) => echoGrantExistsEntry(entry, exists)- // 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}- // Resolve the server's OAuth spec ONCE per distinct name (memoized above).- // A null verdict (read failed OR not an OAuth server) is fail-open per entry.- const resolved = await resolveServerOAuthCached(mcpServerName)- if (!resolved) {+ const verdict = await serverVerdict(mcpServerName)+ if (verdict.kind === 'deny') {+ noteDenial(verdict.reason, mcpServerName)+ results.push(echo(false))+ continue+ }+ if (verdict.kind === 'error') {+ if (verdict.cause) {+ noteDenial('unavailable', mcpServerName, {+ detail: { stage: 'mcp_server', err: verdict.cause.err },+ })+ }results.push(echo(true))continue}+ const { resolved } = verdict++ if (resolved.grantScope === 'user') {+ if (!userId) {+ results.push(echo(true))+ continue+ }+ if (!isCanonicalUuid(userId)) {+ // Channel senders reach here on every sweep by design: debug only.+ noteDenial('no_grant', mcpServerName, { warn: false })+ results.push(echo(false))+ continue+ }+ const access = await accessFor(userId)+ if (access.kind === 'error') {+ noteDenial('unavailable', mcpServerName, {+ detail: { stage: 'user_access', err: access.err },+ })+ results.push(echo(true))+ continue+ }+ if (access.kind === 'denied') {+ noteDenial('no_grant', mcpServerName)+ results.push(echo(false))+ 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. Depends on- // the per-entry userId, so it is decided per entry, not memoized.- log.warn(- { mcpServerName, grantScope: resolved.grantScope },- 'grant-existence: missing grant coordinate; fail-open'- )+ // Unreachable: a context server without contextRef was denied above and a+ // per-user entry without userId answered already. Keep the partition.results.push(echo(true))continue}try {- // The grant SELECT keys by the per-entry coordinate, so it always runs per- // entry. A DB error here is transient/ambiguous → fail-open for THIS entry.results.push(echo(await oauthGrantExists(deps.db, key)))} catch (err) {log.warn({ err, mcpServerName }, 'grant-existence check failed; fail-open (exists:true)')results.push(echo(true))}}++ for (const { reason, mcpServerName, entries, warn, detail } of denials.values()) {+ recordBrokerDenial(+ log,+ 'grants_exists',+ reason,+ { host: binding.hostName, mcpServerName, entries, ...detail },+ warn ? 'warn' : 'debug'+ )+ }return results}@@ -472,11 +584,7 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {context: Record<string, unknown> = {},level: 'warn' | 'debug' = 'warn') => {- mcpOauthBrokerDeniedTotal.inc({ reason, route: 'user_token' }, 1)- log[level](- { event: 'mcp_oauth_broker_denied', reason, route: 'user_token', ...context },- 'mcp oauth broker denied'- )+ recordBrokerDenial(log, 'user_token', reason, context, level)return res.status(status).json(body)}@@ -516,7 +624,6 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {'context spec.contextId differs from its name')}- const hostContext = binding.host.spec?.contextRef as string// Allowlist before the CR read: a server outside this Host's Context// must cost the same as one that does not exist.@@ -553,7 +660,7 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {// Context-scope: the server's owner must be this Host's Context. Checked// before remote coherence so a foreign owner gets the uniform 404, not// a 409 that would reveal its spec. Any body `contextId` is ignored.- if (resolved.grantScope === 'context' && resolved.contextRef !== hostContext) {+ if (resolved.grantScope === 'context' && resolved.contextRef !== binding.contextName) {return deny('context_ref_mismatch', 404, SERVER_NOT_FOUND, where)}@@ -670,16 +777,15 @@ 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.+ // Batch grant-existence sweep. mcp-host asks, in the cadence+ // of the poll it already runs, whether its live OAuth partitions still have a+ // grant, and evicts the ones answered with a strict `exists:false`. Same+ // kill-switch, caller gate, rate-limit bucket and scope as user-token, and the+ // same Host binding. mcp-host treats ANY non-200 as "keep everything", so+ // only caller-level failures (scope, lineage, a token to renew) are errors:+ // a Host that no longer binds answers 200 with every entry false, and a+ // binding that cannot be read answers 200 with every entry true. Returns only+ // `{ mcpServerName, userId?, contextId?, exists }` — never a token or a key.router.post('/mcp-oauth/grants/exists',requireBrokerEnabled,@@ -704,6 +810,20 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {if (!claims || !claims.scopes.includes('oauth:user-token')) {return res.status(403).json({ error: 'insufficient_scope' })}+ const log = req.log ?? rootLogger++ // wrc tokens never call this endpoint; a 403 is harmless. A token+ // without host_uid gets 401 so mcp-host renews it.+ const lineage = checkBrokerCallerLineage(claims, config)+ if (lineage.kind === 'lineage') {+ recordBrokerDenial(log, 'grants_exists', 'lineage', { sub: claims.sub })+ return res.status(403).json(HOST_NOT_BOUND)+ }+ if (lineage.kind === 'unauthenticated') {+ recordBrokerDenial(log, 'grants_exists', 'unauthenticated', { host: claims.hostRefs[0] })+ return res.status(401).json({ error: 'Unauthorized' })+ }+ const hostName = lineage.hostNameconst body = (req.body ?? {}) as { queries?: unknown }if (!Array.isArray(body.queries)) {@@ -712,19 +832,39 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {if (body.queries.length > MAX_EXISTS_BATCH) {return res.status(400).json({ error: 'batch_too_large' })}+ const queries: unknown[] = body.queries+ if (queries.length === 0) return res.status(200).json({ results: [] })+ const everyEntry = (exists: boolean) => ({+ results: queries.map(raw => echoGrantExistsEntry(parseGrantExistsEntry(raw), exists)),+ })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 binding = await resolveBrokerHostBinding(gateway, hostName, lineage.hostUid, config)+ if (binding.kind === 'denied') {+ mcpOauthBrokerDeniedTotal.inc({ reason: 'host_not_bound', route: 'grants_exists' }, 1)+ log.warn(+ { event: 'broker_batch_denied', host: hostName, entries: queries.length },+ 'grant-existence batch denied: Host not bound'+ )+ return res.status(200).json(everyEntry(false))+ }+ if (binding.kind === 'unavailable') {+ recordBrokerDenial(log, 'grants_exists', 'unavailable', {+ host: hostName,+ stage: 'host_binding',+ err: binding.cause,+ })+ return res.status(200).json(everyEntry(true))+ }const results = await resolveBatchGrantExistence({db: { query: (text, values) => pool.query(text, values) },gateway,+ binding,mcpServersNamespace: config.mcpServersNamespace,- log: req.log ?? rootLogger,+ log,},- body.queries+ queries)return res.status(200).json({ results })} catch (err) {diff --git a/control-api/src/services/access/brokerHostBinding.ts b/control-api/src/services/access/brokerHostBinding.tsindex 775cb8c50..88c91dd38 100644--- a/control-api/src/services/access/brokerHostBinding.ts+++ b/control-api/src/services/access/brokerHostBinding.ts@@ -62,8 +62,18 @@ export interface ContextCR {spec?: { contextId?: unknown; mcpServers?: unknown }}+export interface ResolvedHostBinding {+ kind: 'ok'+ hostName: string+ /** The Host's Context, by name: the only Context the caller may act for. */+ contextName: string+ host: HostCR+ ctx: ContextCR+ allowlist: readonly string[]+}+export type HostBinding =- | { kind: 'ok'; host: HostCR; ctx: ContextCR; allowlist: readonly string[] }+ | ResolvedHostBinding| { kind: 'denied' }| { kind: 'unavailable'; cause: unknown }@@ -110,7 +120,7 @@ export async function resolveBrokerHostBinding(const allowlist = Array.isArray(raw)? raw.filter((entry): entry is string => typeof entry === 'string'): []- return { kind: 'ok', host, ctx, allowlist }+ return { kind: 'ok', hostName, contextName: contextRef, host, ctx, allowlist }}/**diff --git a/control-api/test/fixtures/hccControlToken.ts b/control-api/test/fixtures/hccControlToken.tsindex 4f7cdb87e..ccddf86b5 100644--- a/control-api/test/fixtures/hccControlToken.ts+++ b/control-api/test/fixtures/hccControlToken.ts@@ -1,6 +1,10 @@import jwt from 'jsonwebtoken'import request from 'supertest'import { config } from '../../src/config.js'+import {+ type ResolvedHostBinding,+ resolveBrokerHostBinding,+} from '../../src/services/access/brokerHostBinding.js'import type { MockGateway } from '../mockGateway.js'type Provisioner = 'hcc' | 'wrc'@@ -49,6 +53,24 @@ export async function mintHccControlToken(return res.body.mcpHostControlToken as string}+/**+ * The live binding the broker resolves for an HCC control token of `host`+ * (uid read back from the Host CR, as the issuance route signs it), produced by+ * the real `resolveBrokerHostBinding`. For suites that drive the grant-existence+ * resolver directly; throws when the seeded state does not bind.+ */+export async function resolveHccHostBinding(+ gateway: MockGateway,+ host: string+): Promise<ResolvedHostBinding> {+ const cr = (await gateway.getResource('hosts', host, config.hostsNamespace)) as {+ metadata: { uid: string }+ }+ const binding = await resolveBrokerHostBinding(gateway, host, cr.metadata.uid, config)+ if (binding.kind !== 'ok') throw new Error(`host ${host} does not bind: ${binding.kind}`)+ return binding+}+/*** A control token shaped like those issued before host_uid existed, or forged* with the signing key. Declared exception to deriving fixtures from thediff --git a/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.tsindex a1ab0f17b..aaccb87f9 100644--- a/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts+++ b/control-api/test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts@@ -1,6 +1,8 @@-import { afterAll, beforeAll, beforeEach, describe, expect, it } from 'vitest'+import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'import { randomUUID } from 'node:crypto'import { Pool } from 'pg'+import request from 'supertest'+import { createApp } from '../src/app.js'import { config } from '../src/config.js'import type { DbClient } from '../src/db.js'import { initDb } from '../src/db.js'@@ -11,17 +13,62 @@ import {upsertOAuthGrant,} from '../src/oauth/store.js'import { resolveBatchGrantExistence } from '../src/routes/mcpOauth.js'+import {+ seedActiveMember,+ seedAgentHost,+ seedAllowlistedContext,+} from './fixtures/contextAllowlist.js'+import { mintHccControlToken, resolveHccHostBinding } from './fixtures/hccControlToken.js'import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.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:+// T1 — the batch grant-existence resolver exercised against grant state built+// by the REAL producers (`upsertOAuthGrant` / `bootstrapSharedOAuthGrant` /+// `deleteOAuthGrant`), users and Host access written by the production writers+// (`seedActiveMember`), and the Host binding produced by the real+// `resolveBrokerHostBinding`. NO hand-built oauth_grants rows and NO hand-typed+// `exists` booleans. Gated on a real Postgres:// CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \// test/routes.mcpOauth.grantsExists.realPostgres.integration.test.ts++// The membership writers and the route read through the app's shared pool;+// point it at this suite's database.+const testDb = vi.hoisted(() => ({ pool: undefined as import('pg').Pool | undefined }))++vi.mock('../src/db.js', async () => {+ const actual = await vi.importActual<typeof import('../src/db.js')>('../src/db.js')+ const current = () => {+ if (!testDb.pool) throw new Error('test pool not initialised')+ return testDb.pool+ }+ return {+ ...actual,+ pool: {+ query: (text: string, values?: unknown[]) => current().query(text, values),+ connect: () => current().connect(),+ },+ withTransaction: (work: Parameters<typeof actual.withTransaction>[0]) =>+ actual.withTransaction(work, current()),+ }+})++vi.mock('../src/services/notificationEmitter.js', () => ({+ emitNotification: vi.fn().mockResolvedValue(undefined),+ enqueueApprovalRequestedNotification: vi.fn().mockResolvedValue(undefined),+ enqueueApprovalUpdatedNotification: vi.fn().mockResolvedValue(undefined),+}))++vi.mock('../src/services/rateLimiterService.js', () => ({+ checkAndIncrement: vi.fn().mockResolvedValue({+ allowed: true,+ backendAvailable: true,+ remaining: 59,+ resetMs: Date.now() + 60_000,+ windowStartMs: Date.now(),+ count: 1,+ }),+}))+const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skip@@ -34,6 +81,10 @@ function databaseUrl(baseUrl: string, database: string): string {const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)const NS = config.mcpServersNamespaceconst CLIENT_ID = 'google-drive'+const HOST = 'agent-host'+const CONTEXT = 'ctx-authoritative'+// Allowlisted in CONTEXT; `ghost` is never installed.+const ALLOWLIST = ['gdrive-u', 'has-grant', 'no-grant', 'other-user', 'team-drive', 'ghost']describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {const database = `control_api_grants_exists_${randomUUID().replace(/-/g, '')}`@@ -41,6 +92,10 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {let dbPool: Poollet db: DbClientlet gateway: MockGateway+ // Active users who enter HOST.+ let alice: string+ let bob: string+ const originalBrokerEnabled = config.mcpOauthBrokerEnabledbeforeAll(async () => {if (!adminUrl) throw new Error('CONTROL_API_REAL_PG_ADMIN_URL is required')@@ -49,10 +104,14 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {dbPool = new Pool({ connectionString: databaseUrl(adminUrl, database) })await initDb({ connect: () => dbPool.connect() })db = { query: (text, values) => dbPool.query(text, values) }+ testDb.pool = dbPool+ alice = await seedActiveMember(db, { agents: [HOST] })+ bob = await seedActiveMember(db, { agents: [HOST] })})afterAll(async () => {try {+ testDb.pool = undefinedawait endPoolAndWaitForClients(dbPool)if (adminPool) {await adminPool.query(@@ -70,6 +129,13 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {beforeEach(async () => {await dbPool.query('DELETE FROM oauth_grants')gateway = new MockGateway(NS)+ await seedAgentHost(gateway, HOST, CONTEXT)+ await seedAllowlistedContext(gateway, CONTEXT, ALLOWLIST, config.contextsNamespace)+ config.mcpOauthBrokerEnabled = true+ })++ afterEach(() => {+ config.mcpOauthBrokerEnabled = originalBrokerEnabled})function seedUserServer(name: string): void {@@ -105,34 +171,42 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {)}- const resolve = (queries: Parameters<typeof resolveBatchGrantExistence>[1]) =>- resolveBatchGrantExistence({ db, gateway, mcpServersNamespace: NS }, queries)+ const consentUser = (recipeName: string, userId: string, crUid?: string) =>+ upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName,+ userId,+ oauthClientId: CLIENT_ID,+ provider: 'google',+ accessToken: `at-${userId}`,+ ...(crUid ? { crUid } : {}),+ })++ // The binding is resolved per sweep, as the route does on every batch.+ const resolve = async (queries: Parameters<typeof resolveBatchGrantExistence>[1]) =>+ resolveBatchGrantExistence(+ { db, gateway, binding: await resolveHccHostBinding(gateway, HOST), 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 },+ 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',- })+ await consentUser('gdrive-u', alice)- expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([- { mcpServerName: 'gdrive-u', userId: 'alice', exists: true },+ 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 },+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: bob }])).toEqual([+ { mcpServerName: 'gdrive-u', userId: bob, exists: false },])})@@ -142,81 +216,51 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {const uidOf = async (name: string) =>((await gateway.getResource('mcpservers', name, NS)) as { metadata: { uid: string } }).metadata.uid- const consent = (userId: string, crUid: string) =>- upsertOAuthGrant(db, KEY, {- grantKind: 'user',- ownerKind: 'mcpserver',- recipeNamespace: NS,- recipeName: 'gdrive-u',- userId,- oauthClientId: CLIENT_ID,- provider: 'google',- accessToken: `at-${userId}`,- crUid,- })seedUserServer('gdrive-u')- await consent('alice', await uidOf('gdrive-u'))- expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([- { mcpServerName: 'gdrive-u', userId: 'alice', exists: true },+ await consentUser('gdrive-u', alice, await uidOf('gdrive-u'))+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: alice }])).toEqual([+ { mcpServerName: 'gdrive-u', userId: alice, exists: true },])// Uninstall without purging the grant, then reinstall under the same name.await gateway.deleteResource('mcpservers', 'gdrive-u', NS)seedUserServer('gdrive-u')- await consent('bob', await uidOf('gdrive-u'))+ await consentUser('gdrive-u', bob, await uidOf('gdrive-u'))expect(await resolve([- { mcpServerName: 'gdrive-u', userId: 'alice' },- { mcpServerName: 'gdrive-u', userId: 'bob' },+ { mcpServerName: 'gdrive-u', userId: alice },+ { mcpServerName: 'gdrive-u', userId: bob },])).toEqual([- { mcpServerName: 'gdrive-u', userId: 'alice', exists: false },- { mcpServerName: 'gdrive-u', userId: 'bob', exists: true },+ { mcpServerName: 'gdrive-u', userId: alice, exists: false },+ { mcpServerName: 'gdrive-u', userId: bob, exists: true },])})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',- })+ await consentUser('gdrive-u', alice)// 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 },+ // echoed userId, not by position.+ expect(+ await resolve([+ { mcpServerName: 'gdrive-u', userId: bob },+ { mcpServerName: 'gdrive-u', userId: alice },+ ])+ ).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 consentUser('gdrive-u', alice)+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: alice }])).toEqual([+ { mcpServerName: 'gdrive-u', userId: alice, exists: true },])await deleteOAuthGrant(db, {@@ -224,12 +268,12 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {ownerKind: 'mcpserver',recipeNamespace: NS,recipeName: 'gdrive-u',- userId: 'alice',+ userId: alice,oauthClientId: CLIENT_ID,})- expect(await resolve([{ mcpServerName: 'gdrive-u', userId: 'alice' }])).toEqual([- { mcpServerName: 'gdrive-u', userId: 'alice', exists: false },+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: alice }])).toEqual([+ { mcpServerName: 'gdrive-u', userId: alice, exists: false },])})@@ -238,94 +282,139 @@ describeRealPostgres('resolveBatchGrantExistence (real Postgres)', () => {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' },- ])+ await consentUser('has-grant', alice)+ await consentUser('other-user', bob)// 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 },+ expect(+ await resolve([+ { mcpServerName: 'no-grant', userId: alice },+ { mcpServerName: 'has-grant', userId: alice },+ { mcpServerName: 'other-user', userId: alice },+ ])+ ).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.+ it('(e) context server of the Host Context: keyed by it; a lying body contextId does not change the answer', async () => {+ seedContextServer('team-drive', CONTEXT)await bootstrapSharedOAuthGrant(db, KEY, {ownerKind: 'mcpserver',recipeNamespace: NS,recipeName: 'team-drive',- contextId: 'ctx-authoritative',+ contextId: CONTEXT,oauthClientId: CLIENT_ID,- bootstrappedByUserId: 'alice',+ 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([+ expect(+ await resolve([{ mcpServerName: 'team-drive', userId: 'anyone', contextId: 'ctx-foreign' }])+ ).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',+ contextId: CONTEXT,oauthClientId: CLIENT_ID,})- const afterDelete = await resolve([- { mcpServerName: 'team-drive', userId: 'anyone', contextId: 'ctx-authoritative' },+ expect(+ await resolve([{ mcpServerName: 'team-drive', userId: 'anyone', contextId: CONTEXT }])+ ).toEqual([+ { mcpServerName: 'team-drive', userId: 'anyone', contextId: CONTEXT, exists: false },])- expect(afterDelete).toEqual([- {- mcpServerName: 'team-drive',- userId: 'anyone',- contextId: 'ctx-authoritative',- exists: false,- },+ })++ it('R6: a context server owned by another Context → false although its shared grant exists (I-1)', async () => {+ seedContextServer('team-drive', 'ctx-other')+ await bootstrapSharedOAuthGrant(db, KEY, {+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: 'team-drive',+ contextId: 'ctx-other',+ oauthClientId: CLIENT_ID,+ bootstrappedByUserId: alice,+ provider: 'google',+ accessToken: 'A',+ })+ expect(await resolve([{ mcpServerName: 'team-drive' }])).toEqual([+ { mcpServerName: 'team-drive', exists: false },+ ])+ })++ it('GE3 (S05-D10): a missing server in the allowlist fails open (exists:true)', async () => {+ // Allowlisted, never installed → getResource throws K8sNotFoundError.+ expect(await resolve([{ mcpServerName: 'ghost', userId: alice }])).toEqual([+ { mcpServerName: 'ghost', userId: alice, exists: true },+ ])+ })++ it('GE3 (S05-D10): a server outside the allowlist is false even with a grant', async () => {+ seedUserServer('elsewhere')+ await consentUser('elsewhere', alice)+ expect(await resolve([{ mcpServerName: 'elsewhere', userId: alice }])).toEqual([+ { mcpServerName: 'elsewhere', userId: alice, exists: false },+ ])+ })++ it('R7: a user who cannot enter the Host is false although the grant exists (I-3)', async () => {+ const outsider = await seedActiveMember(db, { contexts: [CONTEXT], agents: ['sibling-host'] })+ seedUserServer('gdrive-u')+ await consentUser('gdrive-u', outsider)+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: outsider }])).toEqual([+ { mcpServerName: 'gdrive-u', userId: outsider, 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 },+ it('R7e: ids that are not canonical UUIDs are false, never a fail-open error', async () => {+ seedUserServer('gdrive-u')+ // The braced and hyphen-less spellings are valid Postgres uuid input; each+ // carries its own grant, so only the format rule can refuse them.+ const variants = ['U024BE7LH', 'e2e-vitest-runtime', `{${alice}}`, alice.replace(/-/g, '')]+ for (const id of variants) await consentUser('gdrive-u', id)+ expect(await resolve(variants.map(userId => ({ mcpServerName: 'gdrive-u', userId })))).toEqual(+ variants.map(userId => ({ mcpServerName: 'gdrive-u', userId, exists: false }))+ )+ })++ it('R7e: an upper-case UUID is evaluated, not rejected by format', async () => {+ seedUserServer('gdrive-u')+ const upper = alice.toUpperCase()+ await consentUser('gdrive-u', upper)+ expect(await resolve([{ mcpServerName: 'gdrive-u', userId: upper }])).toEqual([+ { mcpServerName: 'gdrive-u', userId: upper, exists: true },+ ])+ })++ it('GE1: through the route, a Host that no longer binds answers every entry false', async () => {+ seedUserServer('gdrive-u')+ await consentUser('gdrive-u', alice)+ const app = createApp(gateway as never)+ const token = await mintHccControlToken(app, gateway, HOST)+ const sweep = () =>+ request(app)+ .post('/api/v1/mcp-oauth/grants/exists')+ .set('Authorization', `Bearer ${token}`)+ .send({ queries: [{ mcpServerName: 'gdrive-u', userId: alice }] })++ // Precondition: bound, the real grant answers.+ expect((await sweep()).body.results).toEqual([+ { mcpServerName: 'gdrive-u', userId: alice, exists: true },])++ await gateway.deleteResource('hosts', HOST, config.hostsNamespace)+ const res = await sweep()+ expect(res.status).toBe(200)+ expect(res.body.results).toEqual([{ mcpServerName: 'gdrive-u', userId: alice, exists: false }])})})diff --git a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.tsindex a4c1f1919..a95970fd1 100644--- a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts+++ b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts@@ -27,7 +27,7 @@ import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'import { resolveBatchGrantExistence } from '../src/routes/mcpOauth.js'import { resolveInvocableMcpServersForContexts } from '../src/services/access/mcpInvocable.js'import { seedActiveMember, seedAgentHost } from './fixtures/contextAllowlist.js'-import { mintHccControlToken } from './fixtures/hccControlToken.js'+import { mintHccControlToken, resolveHccHostBinding } from './fixtures/hccControlToken.js'import {CONTEXT,NS,@@ -174,10 +174,16 @@ describeRealPostgres('legacy grants seen by the broker, gate and sweep (real Posconst invocable = async (gateway: MockGateway) =>(await resolveInvocableMcpServersForContexts(gateway, NS, [CONTEXT], USER, db)).map(s => s.name)- const sweep = (gateway: MockGateway, name: string) =>- resolveBatchGrantExistence({ db, gateway, mcpServersNamespace: NS }, [- { mcpServerName: name, userId: USER },- ])+ const sweep = async (gateway: MockGateway, name: string) =>+ resolveBatchGrantExistence(+ {+ db,+ gateway,+ binding: await resolveHccHostBinding(gateway, HOST),+ mcpServersNamespace: NS,+ },+ [{ mcpServerName: name, userId: USER }]+ )describe.each<Flavor>(['user', 'context'])('%s flavor', flavor => {it('user-token: a generic reinstall gets 404 no_grant, not the legacy access token', async () => {diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.tsindex b3e4a08e2..2b8c9e177 100644--- a/control-api/test/routes.mcpOauth.test.ts+++ b/control-api/test/routes.mcpOauth.test.ts@@ -6,10 +6,7 @@ import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryimport { registry } from '../src/observability/metrics.js'import { attachServerToContext } from '../src/services/contextAllowlist.js'import { checkAndIncrement } from '../src/services/rateLimiterService.js'-import {- issueMcpHostControlJwt,- verifyMcpHostControlJwt,-} from '../src/utils/auth/mcpHostJwtToken.js'+import { verifyMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'import { membership, seedAgentHost, seedAllowlistedContext } from './fixtures/contextAllowlist.js'import {mintHccControlToken,@@ -83,15 +80,6 @@ async function liveUid(gateway: MockGateway, name: string): Promise<string> {return cr.metadata.uid}-// Control JWT for the grants/exists suite below, from the real minter (T1).-// Only an HCC-lineage control token may carry oauth:user-token.-function controlToken(scopes: Array<'oauth:user-token'> = ['oauth:user-token']): string {- return issueMcpHostControlJwt('mcp-host', 'standalone', ['agent-host'], {- scopes,- hccCredential: { hostUid: 'uid-agent-host' },- }).token-}-function nonExpiredUserGrantRow(userId: string, expiresAt: Date) {return {owner_kind: 'mcpserver',@@ -126,18 +114,22 @@ const HOST_CONTEXT = 'ctx-9'// users.id is a UUID; the broker refuses anything else before querying.const USER_1 = '0b4f3c1e-8a52-4e0f-9b7d-2d6c9e1a7f10'const USER_NO_ACCESS = '7d2e4a90-3c1b-4f6e-8d5a-1b9c0e2f4a63'+const USER_2 = 'c3a91f2e-5b7d-4e08-a6c4-9f1e2d3b4a50'const grantQueries = () =>mockPoolQuery.mock.calls.filter(([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants'))-async function deniedCount(reason: string): Promise<number> {+async function deniedCount(+ reason: string,+ route: 'user_token' | 'grants_exists' = 'user_token'+): Promise<number> {// Read by name so a build without the counter reports 0 instead of throwing.const metric = registry.getSingleMetric('mcp_oauth_broker_denied_total')if (!metric) return 0const { values } = await metric.get()- return values.find(v => v.labels.reason === reason && v.labels.route === 'user_token')?.value ?? 0+ return values.find(v => v.labels.reason === reason && v.labels.route === route)?.value ?? 0}describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {@@ -753,50 +745,150 @@ 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+// Hot-revocation poll-sweep endpoint (mini-spec 13 §4.1), bound to the calling+// Host like user-token. mcp-host keeps every partition on any non-200, and+// evicts only on a strict `exists:false`, so definitive denials travel as 200 ++// false and anything transient as 200 + true. The 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)', () => {+describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (Host binding)', () => {let gateway: MockGatewaylet app: ReturnType<typeof createApp>+ let token: string+ // Grants present in the store, as `<server>|<userId or contextId>`.+ let granted: Set<string>const originalBrokerEnabled = config.mcpOauthBrokerEnabled- beforeEach(() => {+ // Answers by SQL: the Host-entry read through the shared membership stand-in+ // (USER_1 and USER_2 enter HOST), grant reads from `granted`.+ function serveDb(opts: { accessError?: Error } = {}): void {+ membership(mockPoolQuery, { agents: { [USER_1]: [HOST], [USER_2]: [HOST] } }, (sql, values) => {+ const text = typeof sql === 'string' ? sql : ''+ if (text.includes('FROM oauth_grants')) {+ const v = values as unknown[]+ return Promise.resolve(+ granted.has(`${String(v[2])}|${String(v[3])}`)+ ? { rows: [{ exists: 1 }], rowCount: 1 }+ : { rows: [], rowCount: 0 }+ )+ }+ return Promise.resolve({ rows: [], rowCount: 0 })+ })+ if (opts.accessError) {+ const answer = mockPoolQuery.getMockImplementation()!+ mockPoolQuery.mockImplementation((sql: unknown, values: unknown) =>+ isAccessSql(sql) ? Promise.reject(opts.accessError) : answer(sql, values)+ )+ }+ }++ const isAccessSql = (sql: unknown) =>+ typeof sql === 'string' && sql.includes('lifecycle_state') && sql.includes('team_agents')+ const accessQueries = () => mockPoolQuery.mock.calls.filter(([sql]) => isAccessSql(sql))++ const post = (body: unknown, bearer: string | null = token) => {+ const req = request(app).post('/api/v1/mcp-oauth/grants/exists')+ if (bearer) req.set('Authorization', `Bearer ${bearer}`)+ return req.send(body as object)+ }++ function seedContextServer(name: string, contextRef: string | undefined): void {+ void gateway.createResource(+ 'mcpservers',+ {+ metadata: { name },+ spec: {+ ...(contextRef !== undefined ? { contextRef } : {}),+ auth: { type: 'oauth' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ grantScope: 'context',+ },+ },+ },+ MCP_NS+ )+ }++ const allow = (name: string) =>+ attachServerToContext(+ gateway as never,+ { name: HOST_CONTEXT, namespace: config.contextsNamespace },+ name+ )++ beforeEach(async () => {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 })+ granted = new Set()+ serveDb()config.mcpOauthBrokerEnabled = true+ await seedAgentHost(gateway, HOST, HOST_CONTEXT)+ await seedAllowlistedContext(+ gateway,+ HOST_CONTEXT,+ ['gdrive', 'gdrive-2', 'plain', 'ghost', 'team', 'team-foreign', 'team-noctx'],+ config.contextsNamespace+ )+ token = await mintHccControlToken(app, gateway, HOST)})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)- }+ // ── Gates before the binding ──────────────────────────────────────────────it('401 without a control JWT (same gate as user-token)', async () => {- const res = await post(null, { queries: [{ mcpServerName: 'gdrive', userId: 'u1' }] })+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] }, null)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' }],+ const noScope = await mintHccControlToken(app, gateway, HOST, [])+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] }, noScope)+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"insufficient_scope"}')+ })++ it('R1a: a workflow-recipe control token carrying the scope → 403 host_not_bound', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ granted.add(`gdrive|${USER_1}`)+ const wrc = signLegacyControlToken({+ recipeNamespace: config.sandboxNamespace,+ recipeName: 'recipe-x',+ hostRefs: [`${config.sandboxNamespace}/recipe-x`],})+ const before = await deniedCount('lineage', 'grants_exists')+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] }, wrc)expect(res.status).toBe(403)- expect(res.body.error).toBe('insufficient_scope')+ expect(res.text).toBe('{"error":"host_not_bound"}')+ expect(grantQueries()).toHaveLength(0)+ expect(await deniedCount('lineage', 'grants_exists')).toBe(before + 1)+ })++ it('R1b: an HCC token without host_uid → 401 with the requireControlCaller body, no read', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ granted.add(`gdrive|${USER_1}`)+ const legacy = signLegacyControlToken({+ recipeNamespace: config.hostsNamespace,+ recipeName: 'standalone',+ hostRefs: [HOST],+ })+ const reads = vi.spyOn(gateway, 'getResource')+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] }, legacy)+ expect(res.status).toBe(401)+ expect(res.text).toBe('{"error":"Unauthorized"}')+ expect(reads).not.toHaveBeenCalled()+ expect(grantQueries()).toHaveLength(0)})it('400 invalid_request when queries is not an array', async () => {- const res = await post(controlToken(), { queries: 'nope' })+ const res = await post({ queries: 'nope' })expect(res.status).toBe(400)expect(res.body.error).toBe('invalid_request')})@@ -804,189 +896,458 @@ describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (mini-spec 13)', ()it('400 batch_too_large when queries exceeds the cap', async () => {const queries = Array.from({ length: 1001 }, (_, i) => ({mcpServerName: `srv-${i}`,- userId: 'u1',+ userId: USER_1,}))- const res = await post(controlToken(), { queries })+ const res = await post({ 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+ it('GE5: an empty batch answers without reading Host, Context or any server', async () => {+ const reads = vi.spyOn(gateway, 'getResource')+ const res = await post({ queries: [] })+ expect(res.status).toBe(200)+ expect(res.body).toEqual({ results: [] })+ expect(reads).not.toHaveBeenCalled()+ expect(mockPoolQuery).not.toHaveBeenCalled()+ })++ // ── Batch level: the Host binding ─────────────────────────────────────────++ const batch = [+ { mcpServerName: 'gdrive', userId: USER_1 },+ { mcpServerName: 'team', contextId: HOST_CONTEXT },+ { mcpServerName: 'ghost', userId: USER_1 },+ ]++ it.each<[string, () => Promise<void> | void]>([+ ['the Host was deleted', () => gateway.deleteResource('hosts', HOST, config.hostsNamespace)],+ ['the Host is being deleted', () => gateway.markDeleting('hosts', HOST, config.hostsNamespace)],+ [+ 'the Host was recreated under the same name (new uid)',+ async () => {+ await gateway.deleteResource('hosts', HOST, config.hostsNamespace)+ await seedAgentHost(gateway, HOST, HOST_CONTEXT)+ },+ ],+ [+ 'the Host Context does not exist',+ () => gateway.deleteResource('contexts', HOST_CONTEXT, config.contextsNamespace),+ ],+ [+ 'the Host Context is being deleted',+ () => gateway.markDeleting('contexts', HOST_CONTEXT, config.contextsNamespace),+ ],+ ])('GE1: %s → 200 with every entry exists:false, logged once', async (_label, unbind) => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ seedContextServer('team', HOST_CONTEXT)+ granted.add(`gdrive|${USER_1}`).add(`team|${HOST_CONTEXT}`)+ await unbind()+ const before = await deniedCount('host_not_bound', 'grants_exists')+ const logs = captureRequestLogs()+ let res: request.Response+ try {+ res = await post({ queries: batch })+ } finally {+ logs.restore()+ }+ expect(res.status).toBe(200)+ expect(res.body.results).toEqual(batch.map(q => ({ ...q, exists: false })))+ expect(grantQueries()).toHaveLength(0)+ expect(accessQueries()).toHaveLength(0)+ expect(await deniedCount('host_not_bound', 'grants_exists')).toBe(before + 1)+ const batchDenials = logs.warn.mock.calls.filter(+ ([fields]) => (fields as { event?: string }).event === 'broker_batch_denied')- const res = await post(controlToken(), {+ expect(batchDenials).toHaveLength(1)+ expect(batchDenials[0][0]).toMatchObject({ host: HOST, entries: batch.length })+ })++ it.each<[string, 'hosts' | 'contexts']>([+ ['reading the Host', 'hosts'],+ ['reading the Context', 'contexts'],+ ])('GE2: a transient error %s → 200 with every entry exists:true (I-7)', async (_l, plural) => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ seedContextServer('team', HOST_CONTEXT)+ // No grant anywhere: only the fail-open rule can answer true.+ gateway.failGetResource(plural, { statusCode: 503 })+ const before = await deniedCount('unavailable', 'grants_exists')+ const res = await post({ queries: batch })+ expect(res.status).toBe(200)+ expect(res.body.results).toEqual(batch.map(q => ({ ...q, exists: true })))+ expect(grantQueries()).toHaveLength(0)+ expect(await deniedCount('unavailable', 'grants_exists')).toBe(before + 1)+ })++ // ── Entry level ───────────────────────────────────────────────────────────++ it('S05-D10: outside the allowlist → false without reading the server; in it but missing → true', async () => {+ seedOauthServer(gateway, { name: 'foreign', grantScope: 'user' })+ granted.add(`foreign|${USER_1}`)+ const reads = vi.spyOn(gateway, 'getResource')+ const res = await post({queries: [- { mcpServerName: 'ghost', userId: 'u1' },- { mcpServerName: 'plain', userId: 'u1' },+ { mcpServerName: 'foreign', userId: USER_1 },+ { mcpServerName: 'ghost', userId: USER_1 },],})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 },+ { mcpServerName: 'foreign', userId: USER_1, exists: false },+ { mcpServerName: 'ghost', userId: USER_1, 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()+ expect(reads.mock.calls.some(([p, n]) => p === 'mcpservers' && n === 'foreign')).toBe(false)+ expect(grantQueries()).toHaveLength(0)})- // 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' }],+ it('the allowlist match is exact, like host-context-controller (no trim)', async () => {+ seedOauthServer(gateway, { name: 'drive', grantScope: 'user' })+ await allow(' drive ')+ granted.add(`drive|${USER_1}`)+ const res = await post({ queries: [{ mcpServerName: 'drive', userId: USER_1 }] })+ expect(res.body.results).toEqual([{ mcpServerName: 'drive', userId: USER_1, exists: false }])+ })++ it('an allowlisted server being deleted or disabled → false although the grant exists', async () => {+ seedOauthServer(gateway, { name: 'leaving', grantScope: 'user' })+ seedOauthServer(gateway, { name: 'off', grantScope: 'user', enabled: false })+ await allow('leaving')+ await allow('off')+ gateway.markDeleting('mcpservers', 'leaving', MCP_NS)+ granted.add(`leaving|${USER_1}`).add(`off|${USER_1}`)+ const res = await post({+ queries: [+ { mcpServerName: 'leaving', userId: USER_1 },+ { mcpServerName: 'off', userId: USER_1 },+ ],})- 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(res.body.results).toEqual([+ { mcpServerName: 'leaving', userId: USER_1, exists: false },+ { mcpServerName: 'off', userId: USER_1, exists: false },+ ])+ expect(grantQueries()).toHaveLength(0)+ })++ it('GE2: a transient error reading an allowlisted server → true, without a grant', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ gateway.failGetResource('mcpservers', { statusCode: 500 })+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] })+ expect(res.body.results).toEqual([{ mcpServerName: 'gdrive', userId: USER_1, exists: true }])+ })++ it('a non-oauth allowlisted server → true (no not_oauth_server rule here)', async () => {+ void gateway.createResource(+ 'mcpservers',+ { metadata: { name: 'plain' }, spec: { auth: { type: 'none' } } },+ MCP_NS)- expect(grantQuery?.[1]).toEqual([+ const res = await post({ queries: [{ mcpServerName: 'plain', userId: USER_1 }] })+ expect(res.body.results).toEqual([{ mcpServerName: 'plain', userId: USER_1, exists: true }])+ expect(grantQueries()).toHaveLength(0)+ })++ it('a server that declares spec.oauth but is not auth.type oauth → true, no grant read', async () => {+ void gateway.createResource(+ 'mcpservers',+ {+ metadata: { name: 'plain' },+ spec: {+ contextRef: HOST_CONTEXT,+ auth: { type: 'none' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ grantScope: 'user',+ },+ },+ },+ MCP_NS+ )+ granted.add(`plain|${USER_1}`)+ const res = await post({ queries: [{ mcpServerName: 'plain', userId: USER_1 }] })+ expect(res.body.results).toEqual([{ mcpServerName: 'plain', userId: USER_1, exists: true }])+ expect(grantQueries()).toHaveLength(0)+ })++ it.each<[string, 'mcp_server' | 'user_access']>([+ ['reading the server', 'mcp_server'],+ ['reading Host access', 'user_access'],+ ])(+ 'a transient error %s is logged and counted once, with every entry it covers',+ async (_l, stage) => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ if (stage === 'mcp_server') gateway.failGetResource('mcpservers', { statusCode: 500 })+ else serveDb({ accessError: new Error('connection terminated') })+ const before = await deniedCount('unavailable', 'grants_exists')+ const queries = [+ { mcpServerName: 'gdrive', userId: USER_1 },+ { mcpServerName: 'gdrive', userId: USER_2 },+ { mcpServerName: 'gdrive', userId: USER_1 },+ ]+ const logs = captureRequestLogs()+ let res: request.Response+ try {+ res = await post({ queries })+ } finally {+ logs.restore()+ }+ expect(res.body.results).toEqual(queries.map(q => ({ ...q, exists: true })))+ expect(await deniedCount('unavailable', 'grants_exists')).toBe(before + 1)+ // The aggregated denial is the only warning, and it carries the cause.+ expect(logs.warn.mock.calls).toHaveLength(1)+ expect(logs.warn.mock.calls[0][0]).toMatchObject({+ event: 'mcp_oauth_broker_denied',+ reason: 'unavailable',+ mcpServerName: 'gdrive',+ entries: queries.length,+ stage,+ err: expect.anything(),+ })+ }+ )++ it('R6: a context server owned by another Context, or without contextRef → false (I-1)', async () => {+ seedContextServer('team-foreign', 'ctx-A')+ seedContextServer('team-noctx', undefined)+ granted.add('team-foreign|ctx-A')+ const res = await post({+ queries: [{ mcpServerName: 'team-foreign' }, { mcpServerName: 'team-noctx' }],+ })+ expect(res.body.results).toEqual([+ { mcpServerName: 'team-foreign', exists: false },+ { mcpServerName: 'team-noctx', exists: false },+ ])+ expect(grantQueries()).toHaveLength(0)+ })++ it('R6b: a context server of the Host Context keys by that Context, ignoring the body contextId', async () => {+ seedContextServer('team', HOST_CONTEXT)+ granted.add(`team|${HOST_CONTEXT}`)+ const res = await post({+ queries: [{ mcpServerName: 'team', userId: USER_1, contextId: 'ctx-foreign' }],+ })+ expect(res.body.results).toEqual([+ { mcpServerName: 'team', userId: USER_1, contextId: 'ctx-foreign', exists: true },+ ])+ expect(grantQueries()[0]?.[1]).toEqual(['mcpserver',MCP_NS,- 'gdrive',- 'nobody',+ 'team',+ HOST_CONTEXT,'google-drive',- await liveUid(gateway, 'gdrive'),- // Baked CR: the reader key carries its provider for unsealed legacy rows.+ await liveUid(gateway, 'team'),'google',])})- it('200: reports exists:true when the SELECT 1 finds a row', async () => {+ it('a per-user server without userId → true', 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 }])+ const res = await post({ queries: [{ mcpServerName: 'gdrive' }] })+ expect(res.body.results).toEqual([{ mcpServerName: 'gdrive', 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 () => {+ it('R7e: a userId that is not a canonical UUID → false, without querying access or grants', 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(), {+ granted.add('gdrive|U024BE7LH').add(`gdrive|{${USER_1}}`)+ const res = await post({queries: [- { mcpServerName: 'gdrive', userId: 'alice' },- { mcpServerName: 'gdrive', userId: 'bob' },+ { mcpServerName: 'gdrive', userId: 'U024BE7LH' },+ { mcpServerName: 'gdrive', userId: `{${USER_1}}` },],})- expect(res.status).toBe(200)expect(res.body.results).toEqual([- { mcpServerName: 'gdrive', userId: 'alice', exists: true },- { mcpServerName: 'gdrive', userId: 'bob', exists: false },+ { mcpServerName: 'gdrive', userId: 'U024BE7LH', exists: false },+ { mcpServerName: 'gdrive', userId: `{${USER_1}}`, exists: false },+ ])+ expect(accessQueries()).toHaveLength(0)+ expect(grantQueries()).toHaveLength(0)+ })++ it('R7: a user who cannot enter the Host → false although the grant exists (I-3)', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ granted.add(`gdrive|${USER_NO_ACCESS}`)+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_NO_ACCESS }] })+ expect(res.body.results).toEqual([+ { mcpServerName: 'gdrive', userId: USER_NO_ACCESS, exists: false },])+ expect(grantQueries()).toHaveLength(0)})- // Should-fix #1 (efficiency, mini-spec 13): within ONE batch the CR of a- // shared server is read from the apiserver ONCE, not once per entry. N per-user- // partitions of the SAME server → a single getResource('mcpservers', 'gdrive'),- // yet still N grant SELECTs (one per userId). The per-entry response is- // IDENTICAL to the un-deduped semantics — only the apiserver fan-out drops.- it('200: dedups the getResource read across N entries of the same server', async () => {+ it('R7f: a DB error reading Host access → true, without a grant (I-7)', async () => {seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })- const getResourceSpy = vi.spyOn(gateway, 'getResource')- // alice has a grant (first SELECT 1 finds a row); bob and carol do not.- mockPoolQuery.mockResolvedValueOnce({ rows: [{ exists: 1 }], rowCount: 1 })- const res = await post(controlToken(), {+ serveDb({ accessError: new Error('connection terminated') })+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] })+ expect(res.status).toBe(200)+ expect(res.body.results).toEqual([{ mcpServerName: 'gdrive', userId: USER_1, exists: true }])+ expect(grantQueries()).toHaveLength(0)+ })++ it('authorized: the real grant lookup decides, keyed by (server owner, userId)', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ granted.add(`gdrive|${USER_1}`)+ const res = await post({queries: [- { mcpServerName: 'gdrive', userId: 'alice' },- { mcpServerName: 'gdrive', userId: 'bob' },- { mcpServerName: 'gdrive', userId: 'carol' },+ { mcpServerName: 'gdrive', userId: USER_1 },+ { mcpServerName: 'gdrive', userId: USER_2 },],})- expect(res.status).toBe(200)- // Per-entry booleans + order unchanged vs. the one-read-per-entry version.expect(res.body.results).toEqual([- { mcpServerName: 'gdrive', userId: 'alice', exists: true },- { mcpServerName: 'gdrive', userId: 'bob', exists: false },- { mcpServerName: 'gdrive', userId: 'carol', exists: false },+ { mcpServerName: 'gdrive', userId: USER_1, exists: true },+ { mcpServerName: 'gdrive', userId: USER_2, exists: false },])- // The shared server CR is read from the apiserver EXACTLY ONCE for the batch.- const gdriveReads = getResourceSpy.mock.calls.filter(- ([plural, name]) => plural === 'mcpservers' && name === 'gdrive'- )- expect(gdriveReads).toHaveLength(1)- // Yet every entry still ran its own SELECT 1 (one grant lookup per userId).- const grantSelects = mockPoolQuery.mock.calls.filter(- ([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants')- )- expect(grantSelects).toHaveLength(3)- // …and each SELECT carries its own entry's userId, in order (userId is the- // 4th bind param: [ownerKind, ns, name, userId, clientId]).- expect(grantSelects.map(call => (call[1] as unknown[])[3])).toEqual(['alice', 'bob', 'carol'])- })-- // 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(grantQueries().map(([, values]) => values)).toEqual([+ [+ 'mcpserver',+ MCP_NS,+ 'gdrive',+ USER_1,+ 'google-drive',+ await liveUid(gateway, 'gdrive'),+ 'google',+ ],+ [+ 'mcpserver',+ MCP_NS,+ 'gdrive',+ USER_2,+ 'google-drive',+ await liveUid(gateway, 'gdrive'),+ 'google',+ ],+ ])+ })++ it('GE5: Host and Context once per batch, each server once, Host access once per userId', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ seedOauthServer(gateway, { name: 'gdrive-2', grantScope: 'user' })+ seedContextServer('team', HOST_CONTEXT)+ granted.add(`gdrive|${USER_1}`).add(`gdrive-2|${USER_2}`)+ const reads = vi.spyOn(gateway, 'getResource')+ const res = await post({+ queries: [+ { mcpServerName: 'gdrive', userId: USER_1 },+ { mcpServerName: 'gdrive', userId: USER_2 },+ { mcpServerName: 'gdrive-2', userId: USER_1 },+ { mcpServerName: 'gdrive-2', userId: USER_2 },+ { mcpServerName: 'team' },+ { mcpServerName: 'ghost', userId: USER_1 },+ { mcpServerName: 'ghost', userId: USER_2 },+ ],})- expect(res.status).toBe(200)- expect(res.body.results).toEqual([- { mcpServerName: 'team', userId: 'u1', contextId: 'ctx-foreign', exists: false },+ expect(res.body.results.map((r: { exists: boolean }) => r.exists)).toEqual([+ true,+ false,+ false,+ true,+ false,+ true,+ true,])- 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',- await liveUid(gateway, 'team'),- // Baked CR: the reader key carries its provider for unsealed legacy rows.- 'google',+ const count = (plural: string, name?: string) =>+ reads.mock.calls.filter(([p, n]) => p === plural && (name === undefined || n === name)).length+ expect(count('hosts')).toBe(1)+ expect(count('contexts')).toBe(1)+ expect(count('mcpservers', 'gdrive')).toBe(1)+ expect(count('mcpservers', 'gdrive-2')).toBe(1)+ expect(count('mcpservers', 'ghost')).toBe(1)+ expect(accessQueries().map(([, values]) => values)).toEqual([+ [USER_1, HOST],+ [USER_2, HOST],])})- // 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 () => {+ it('logs and counts once per (reason, server), never per entry, and never the userId', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ seedOauthServer(gateway, { name: 'foreign', grantScope: 'user' })+ const beforeNotFound = await deniedCount('server_not_found', 'grants_exists')+ const beforeNoGrant = await deniedCount('no_grant', 'grants_exists')+ const logs = captureRequestLogs()+ try {+ const res = await post({+ queries: [+ { mcpServerName: 'foreign', userId: USER_1 },+ { mcpServerName: 'foreign', userId: USER_2 },+ { mcpServerName: 'foreign', userId: USER_NO_ACCESS },+ { mcpServerName: 'gdrive', userId: USER_NO_ACCESS },+ { mcpServerName: 'gdrive', userId: 'U024BE7LH' },+ { mcpServerName: 'gdrive', userId: 'W0B2C3D4E' },+ ],+ })+ expect(res.body.results.every((r: { exists: boolean }) => !r.exists)).toBe(true)+ } finally {+ logs.restore()+ }+ expect(await deniedCount('server_not_found', 'grants_exists')).toBe(beforeNotFound + 1)+ expect(await deniedCount('no_grant', 'grants_exists')).toBe(beforeNoGrant + 1)+ const denials = [...logs.warn.mock.calls, ...logs.debug.mock.calls]+ .map(([fields]) => fields as { event?: string; reason?: string; mcpServerName?: string })+ .filter(fields => fields.event === 'mcp_oauth_broker_denied')+ expect(denials).toEqual([+ expect.objectContaining({+ reason: 'server_not_found',+ route: 'grants_exists',+ host: HOST,+ mcpServerName: 'foreign',+ entries: 3,+ }),+ expect.objectContaining({+ reason: 'no_grant',+ route: 'grants_exists',+ host: HOST,+ mcpServerName: 'gdrive',+ entries: 3,+ }),+ ])+ const everything = JSON.stringify([+ logs.warn.mock.calls,+ logs.debug.mock.calls,+ logs.info.mock.calls,+ ])+ for (const id of [USER_1, USER_2, USER_NO_ACCESS, 'U024BE7LH', 'W0B2C3D4E']) {+ expect(everything).not.toContain(id)+ }+ })++ it('channel senders (non-UUID) are logged at debug; only an entitled-looking id warns', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ seedOauthServer(gateway, { name: 'gdrive-2', grantScope: 'user' })+ const logs = captureRequestLogs()+ try {+ await post({+ queries: [+ { mcpServerName: 'gdrive', userId: 'U024BE7LH' },+ { mcpServerName: 'gdrive-2', userId: USER_NO_ACCESS },+ ],+ })+ } finally {+ logs.restore()+ }+ const denials = (calls: unknown[][]) =>+ calls+ .map(([fields]) => fields as { event?: string; mcpServerName?: string })+ .filter(fields => fields.event === 'mcp_oauth_broker_denied')+ .map(fields => fields.mcpServerName)+ expect(denials(logs.debug.mock.calls)).toEqual(['gdrive'])+ expect(denials(logs.warn.mock.calls)).toEqual(['gdrive-2'])+ })++ it('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 ''+ { mcpServerName: 'Foo/Bar', userId: USER_1 },+ { mcpServerName: 'ghost', userId: USER_2 },+ { userId: USER_1 },]- const res = await post(controlToken(), { queries })+ const res = await post({ 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 },+ { mcpServerName: 'Foo/Bar', userId: USER_1, exists: true },+ { mcpServerName: 'ghost', userId: USER_2, exists: true },+ { mcpServerName: '', userId: USER_1, 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({@@ -997,24 +1358,15 @@ describe('routes/mcp-oauth — POST /mcp-oauth/grants/exists (mini-spec 13)', ()windowStartMs: Date.now(),count: 61,})- const res = await post(controlToken(), {- queries: [{ mcpServerName: 'gdrive', userId: 'u1' }],- })+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] })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()+ expect(grantQueries()).toHaveLength(0)})- // 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' }],- })+ const res = await post({ queries: [{ mcpServerName: 'gdrive', userId: USER_1 }] })expect(res.status).toBe(404)expect(res.body.error).toBe('not_found')})diff --git a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts b/control-api/test/routes.registryUninstall.realPostgres.integration.test.tsindex a3ec58301..c99f0ec39 100644--- a/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts+++ b/control-api/test/routes.registryUninstall.realPostgres.integration.test.ts@@ -79,7 +79,8 @@ const { createOAuthCallbackRouter } = await import('../src/routes/external/oauthconst { resolveBatchGrantExistence } = await import('../src/routes/mcpOauth.js')const { getCredentialSchema, getDigest, getEntryVersion, reportInstall } =await import('../src/services/registryClient.js')-const { seedActiveMember } = await import('./fixtures/contextAllowlist.js')+const { seedActiveMember, seedAgentHost } = await import('./fixtures/contextAllowlist.js')+const { resolveHccHostBinding } = await import('./fixtures/hccControlToken.js')const adminUrl = process.env.CONTROL_API_REAL_PG_ADMIN_URLconst describeRealPostgres = adminUrl ? describe : describe.skip@@ -92,6 +93,7 @@ function databaseUrl(baseUrl: string, database: string): string {const NS = 'mcp-server'const SERVER = 'my-gmail'+const HOST = 'agent-host'/** Baked-OAuth catalog entry, same shape as the registry OAuth install tests. */const GMAIL_ENTRY = {@@ -263,9 +265,16 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)return request(app).get(`/oauth-callback/${SERVER}`).query({ code: 'AUTH_CODE', state })}- const sweep = (gw: MockGateway) =>+ // The binding is resolved per sweep, as the route does on every batch: the+ // registry writes the Context allowlist on install and uninstall.+ const sweep = async (gw: MockGateway) =>resolveBatchGrantExistence(- { db, gateway: gw as unknown as K8sGateway, mcpServersNamespace: NS },+ {+ db,+ gateway: gw as unknown as K8sGateway,+ binding: await resolveHccHostBinding(gw, HOST),+ mcpServersNamespace: NS,+ },[{ mcpServerName: SERVER, userId: user }])@@ -275,8 +284,9 @@ describeRealPostgres('registry uninstall tears OAuth grants down (real Postgres)metadata: { name: 'default-context' },spec: { contextId: 'default-context', mcpServers: [] },})+ await seedAgentHost(gw, HOST, 'default-context')const app = makeApp(gw)- user = await seedActiveMember(db, { contexts: ['default-context'] })+ user = await seedActiveMember(db, { contexts: ['default-context'], agents: [HOST] })expect((await install(app)).status).toBe(201)expect((await consent(app, gw)).status).toBe(200)