Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): bind OAuth broker user-token to the authenticated Host (S-05 F1)
Diego Zacariascda5f04b5c36
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 0c1a426fe..62bd0a5d1 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -556,6 +556,7 @@ jobs:pluginWorkloadSdkSteplessQuota.realPostgres.integration.test.ts \entityChangeFeed.realPostgres.integration.test.ts \routes.mcp-host.renewal.realPostgres.integration.test.ts \+ routes.mcpOauth.brokerBinding.realPostgres.integration.test.ts \db.realPostgresMigration.integration.test.ts- name: Install gfs-controller dependenciesdiff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex d6ceb0eae..fee88a17c 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.816",+ "version": "0.1.817","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.816",+ "version": "0.1.817","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 05de184ba..e5d0b39ce 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.816",+ "version": "0.1.817","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/observability/metrics.ts b/control-api/src/observability/metrics.tsindex 763431d09..049239098 100644--- a/control-api/src/observability/metrics.ts+++ b/control-api/src/observability/metrics.ts@@ -220,6 +220,16 @@ export const mcpHostJwtReissueTotal = getOrCreateCounter({labelNames: ['result'] as const as Array<'result'>,})+// OAuth mcp-server broker refused a caller on its Host binding. reason:+// lineage | unauthenticated | host_not_bound | server_not_found |+// context_ref_mismatch | no_grant | unavailable. route: user_token |+// grants_exists. The mcp-server and Host go to the log, never a label.+export const mcpOauthBrokerDeniedTotal = getOrCreateCounter({+ name: 'mcp_oauth_broker_denied_total',+ help: 'Count of OAuth broker requests denied by the Host binding, by reason and route.',+ labelNames: ['reason', 'route'] as const as Array<'reason' | 'route'>,+})+// MCP server uninstall: a cleanup step failed. Every stage except// oauth_grants_post_delete runs before the CR delete and leaves the CR in place for a// retry (the request answers "repair required"); a sustained rate means uninstallsdiff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex 744c742f8..f118ea9a4 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -26,6 +26,17 @@ import {import { getAccessTokenReactive } from '../oauth/reactiveTokenHelper.js'import { type OAuthGrantKey, oauthGrantExists } from '../oauth/store.js'import { type Logger, rootLogger } from '../observability/logger.js'+import { mcpOauthBrokerDeniedTotal } from '../observability/metrics.js'+import {+ checkBrokerCallerLineage,+ hasContextIdMismatch,+ hostAccessForUser,+ isCanonicalUuid,+ isLive,+ isValidK8sName,+ resolveBrokerHostBinding,+} from '../services/access/brokerHostBinding.js'+import { isK8sResourceNotFound } from '../services/access/mcpInvocable.js'import { K8sNotFoundError } from '../services/resourceService.js'import {type McpHostControlClaims,@@ -46,27 +57,33 @@ import { extractBearerToken } from '../utils/extractBearerToken.js'* Gate: the control JWT + scope `oauth:user-token`. No new static credential* and no new broker-token minting infra (the híbrido design, §U1).*- * Identity provenance:+ * Binding: the body only names the mcp-server and, for per-user servers, the+ * end user. Everything else comes from the authenticated caller:+ * - The control JWT must belong to a host-context-controller Host+ * (`hostRefs[0]` + `host_uid`), and that Host must be live with the same+ * uid, so a token cannot outlive or be replayed against a recreated Host.+ * - The Context is the Host's `spec.contextRef`, never a body field: a+ * caller cannot name another Context to obtain its shared token.+ * - The mcp-server must be in that Context's allowlist (exact match, as+ * host-context-controller applies it), enabled and live. Anything else+ * answers the same 404 as a missing server, read before the CR is fetched,+ * so the broker is no existence oracle across Contexts.+ * - A per-user token requires the body `userId` to be an active user who+ * enters this Host (directly or through an active team). The `userId`+ * itself is still asserted by mcp-host, not proven by a signature here.* - `oauthClientId` is derived from the McpServer's `spec.oauth.id`, NEVER* from the request body.- * - `userId` / `contextId` ride the request body. This is the accepted pattern- * of the mutually-authenticated mcp-host ↔ control-api seam (same as- * `routes/internal/oauth.ts`): the caller is authenticated by its control- * JWT and asserts, over that trusted channel, which end-user session /- * Context pod the token is for. control-api authorizes the grant against the- * forwarded `userId`/`contextId` (defense in depth — a wrong value simply- * resolves to `no_grant`). It is therefore INCORRECT to say "userId is never- * a body param" here.** Flavor dispatch — read from the server's `spec.oauth.grantScope`:* - `user` → grant key `(server, userId)` — per-user identity.- * - `context` → grant key `(server, contextId)` — shared identity.+ * - `context` → grant key `(server, contextRef)` — shared identity.* Both branches ship in v1; the `context` branch is governed/exercised by U6.*/export interface McpServerResource {- metadata?: { name?: string; namespace?: string; uid?: string }+ metadata?: { name?: string; namespace?: string; uid?: string; deletionTimestamp?: unknown }spec?: {+ enabled?: unknownauth?: { type?: unknown }oauth?: McpServerOAuthDecl// `spec.contextRef` is REQUIRED + singular on the CRD ("the context this@@ -156,13 +173,22 @@ export function normalizeMcpServerOwnerDecl(}}-// DNS-1123 subdomain, the shape a k8s resource name takes. Reject anything else-// up front so a malformed `mcpServerName` (e.g. "Foo/Bar") becomes a 400 rather-// than surfacing a non-404 apiserver error as a 500.-const K8S_NAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/-function isValidK8sName(name: string): boolean {- return name.length > 0 && name.length <= 253 && K8S_NAME_RE.test(name)-}+type BrokerDenialReason =+ | 'lineage'+ | 'unauthenticated'+ | 'host_not_bound'+ | 'server_not_found'+ | 'context_ref_mismatch'+ | 'no_grant'+ | 'unavailable'++// Fixed bodies: denials must not vary with what was found, and a 503 never+// forwards the apiserver or DB error (an RBAC 403 from Kubernetes would+// otherwise reach the client through the shared error handler).+const HOST_NOT_BOUND = { error: 'host_not_bound' }+const SERVER_NOT_FOUND = { error: 'server_not_found' }+const STATE_UNAVAILABLE = { error: 'host_state_unavailable' }+const NO_GRANT = { error: 'no_grant' }// Upper bound on the grant-existence batch. mcp-host caps its per-user OAuth// partitions at OAUTH_USER_PARTITION_MAX=500, so one sweep never legitimately@@ -438,23 +464,66 @@ 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+ const deny = (+ reason: BrokerDenialReason,+ status: number,+ body: Record<string, string>,+ 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'+ )+ return res.status(status).json(body)+ }++ const lineage = checkBrokerCallerLineage(claims, config)+ if (lineage.kind === 'lineage') {+ return deny('lineage', 403, HOST_NOT_BOUND, { sub: claims.sub })+ }+ if (lineage.kind === 'unauthenticated') {+ return deny('unauthenticated', 401, { error: 'Unauthorized' }, { host: claims.hostRefs[0] })+ }+ const hostName = lineage.hostNametry {const body = (req.body ?? {}) as {mcpServerName?: unknownuserId?: unknown- contextId?: unknown}const mcpServerName = body.mcpServerNameconst userId = body.userId- const contextId = body.contextIdif (typeof mcpServerName !== 'string' || !isValidK8sName(mcpServerName)) {return res.status(400).json({ error: 'invalid_request' })}+ const where = { host: hostName, mcpServerName }++ const binding = await resolveBrokerHostBinding(gateway, hostName, lineage.hostUid, config)+ if (binding.kind === 'denied') return deny('host_not_bound', 403, HOST_NOT_BOUND, where)+ if (binding.kind === 'unavailable') {+ return deny('unavailable', 503, STATE_UNAVAILABLE, {+ ...where,+ stage: 'host_binding',+ err: binding.cause,+ })+ }+ if (hasContextIdMismatch(binding.ctx)) {+ log.warn(+ { event: 'context_id_mismatch', host: hostName, context: binding.ctx.metadata?.name },+ 'context spec.contextId differs from its name'+ )+ }+ const hostContext = binding.host.spec?.contextRef as string- // Read the McpServer to derive `oauthClientId` + `grantScope` from the- // server's declaration — never from the body.- let server: McpServerResource | null+ // Allowlist before the CR read: a server outside this Host's Context+ // must cost the same as one that does not exist.+ if (!binding.allowlist.includes(mcpServerName)) {+ return deny('server_not_found', 404, SERVER_NOT_FOUND, where)+ }+ let server: McpServerResourcetry {server = (await gateway.getResource('mcpservers',@@ -462,17 +531,32 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {config.mcpServersNamespace)) as McpServerResource} catch (err) {- if (err instanceof K8sNotFoundError) {- return res.status(404).json({ error: 'server_not_found' })+ if (isK8sResourceNotFound(err)) {+ return deny('server_not_found', 404, SERVER_NOT_FOUND, where)}- throw err+ return deny('unavailable', 503, STATE_UNAVAILABLE, {+ ...where,+ stage: 'mcp_server',+ err,+ })+ }+ if (!server || !isLive(server.metadata) || server.spec?.enabled === false) {+ return deny('server_not_found', 404, SERVER_NOT_FOUND, where)}- const authType = server?.spec?.auth?.type+ const authType = server.spec?.auth?.typeconst resolved = resolveServerOAuth(server)if (authType !== 'oauth' || !resolved) {return res.status(400).json({ error: 'not_oauth_server' })}++ // 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) {+ return deny('context_ref_mismatch', 404, SERVER_NOT_FOUND, where)+ }+// Checked up front, not only through the refresh reader: a still-fresh// access token is served without ever reading the owner declaration.assertRemoteOAuthSpecCoherent(server, 'token')@@ -480,27 +564,32 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {// Bifurcate by grantScope read from the server. The KEY comes from the// shared derivation (`buildMcpServerGrantKey`, D4) so the mint, the// rpc-proxy grant-presence gate and the grant-existence sweep never- // drift. The mint keeps its own request-validation guards, which map to- // specific error codes the shared builder's null return cannot express.+ // drift.let userForKey: string | undefined- if (resolved.grantScope === 'context') {- // AUTHORITATIVE Context = server.spec.contextRef, NEVER the body.- // Trusting a body contextId would let a caller with the scope request- // {server, contextId: <someone else's Context>} and receive that- // Context's shared token (cross-context token theft). The body value,- // if present, is only cross-checked against the authoritative one.- if (!resolved.contextRef) {- // A context-identity server MUST carry contextRef (CRD-required).- // Fail closed if it somehow doesn't.- return res.status(400).json({ error: 'server_missing_context' })- }- if (typeof contextId === 'string' && contextId !== resolved.contextRef) {- return res.status(400).json({ error: 'context_mismatch' })- }- } else {+ if (resolved.grantScope === 'user') {if (typeof userId !== 'string' || userId.length === 0) {return res.status(400).json({ error: 'invalid_request' })}+ // A user who cannot enter this Host looks exactly like one who never+ // connected the server.+ let access: 'allowed' | 'denied'+ try {+ access = await hostAccessForUser(pool, userId, hostName)+ } catch (err) {+ return deny('unavailable', 503, STATE_UNAVAILABLE, {+ ...where,+ stage: 'user_access',+ err,+ })+ }+ if (access === 'denied') {+ // Channel senders (Slack, email, Telegram ids) are not users.id and+ // reach here on every mint by design; only an entitled-looking id+ // that cannot enter the Host is worth a warning.+ return isCanonicalUuid(userId)+ ? deny('no_grant', 404, NO_GRANT, { ...where, cause: 'no_host_access' })+ : deny('no_grant', 404, NO_GRANT, { ...where, cause: 'non_uuid_user_id' }, 'debug')+ }userForKey = userId}const key: OAuthGrantKey | null = buildMcpServerGrantKey(resolved, {@@ -509,8 +598,9 @@ export function createMcpOauthRouter(gateway: K8sGateway): Router {userId: userForKey,})if (!key) {- // Unreachable: the guards above already rejected the null cases. Fail- // closed defensively rather than mint against a malformed key.+ // Unreachable: the guards above already rejected the null cases (a+ // context server without contextRef never equals the Host's Context).+ // Fail closed defensively rather than mint against a malformed key.return res.status(400).json({ error: 'invalid_request' })}diff --git a/control-api/src/services/access/brokerHostBinding.ts b/control-api/src/services/access/brokerHostBinding.tsnew file mode 100644index 000000000..775cb8c50--- /dev/null+++ b/control-api/src/services/access/brokerHostBinding.ts@@ -0,0 +1,162 @@+import type { DbClient } from '../../db.js'+import type { K8sGateway } from '../../k8s.js'+import { type McpHostControlClaims, isHccControlLineage } from '../../utils/auth/mcpHostJwtToken.js'+import { isK8sResourceNotFound } from './mcpInvocable.js'++/**+ * Binding of an OAuth-broker caller to the Host it runs for. The broker+ * (`user-token`, `grants/exists`) never trusts the request body for the+ * Context: it derives it from the authenticated Host, with the same relation+ * host-context-controller uses to hand mcp-servers to that Host (Context by+ * name, live, allowlist matched exactly). The broker must not be more+ * permissive than the controller that decides what the Host may reach.+ */++// DNS-1123 subdomain, the shape a k8s resource name takes. Checked before any+// apiserver read: a malformed name would otherwise surface a non-404 apiserver+// error, and an empty one would address the collection instead of an object.+const K8S_NAME_RE = /^[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/+export function isValidK8sName(name: string): boolean {+ return name.length > 0 && name.length <= 253 && K8S_NAME_RE.test(name)+}++// Stricter than Postgres' `::uuid` cast (which also accepts braces and no+// hyphens): anything that passes here is guaranteed to cast, so a channel+// provider id or a test sender is a definitive denial, never a DB error.+const CANONICAL_UUID_RE =+ /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/+export function isCanonicalUuid(value: string): boolean {+ return CANONICAL_UUID_RE.test(value)+}++export type CallerLineage =+ | { kind: 'ok'; hostName: string; hostUid: string }+ | { kind: 'lineage' }+ | { kind: 'unauthenticated' }++/**+ * Synchronous caller checks. Lineage goes first so a workflow-recipe token gets+ * a definitive 403 instead of a 401 that would make it renew for nothing; an+ * HCC token without host_uid predates the claim and is sent to renew.+ */+export function checkBrokerCallerLineage(+ claims: McpHostControlClaims,+ cfg: { hostsNamespace: string }+): CallerLineage {+ if (!isHccControlLineage(claims, cfg.hostsNamespace)) return { kind: 'lineage' }+ if (typeof claims.host_uid !== 'string' || claims.host_uid.length === 0) {+ return { kind: 'unauthenticated' }+ }+ return { kind: 'ok', hostName: claims.hostRefs[0], hostUid: claims.host_uid }+}++type ObjectMeta = { name?: unknown; uid?: unknown; deletionTimestamp?: unknown }++export interface HostCR {+ metadata?: ObjectMeta+ spec?: { contextRef?: unknown }+}++export interface ContextCR {+ metadata?: ObjectMeta+ spec?: { contextId?: unknown; mcpServers?: unknown }+}++export type HostBinding =+ | { kind: 'ok'; host: HostCR; ctx: ContextCR; allowlist: readonly string[] }+ | { kind: 'denied' }+ | { kind: 'unavailable'; cause: unknown }++export type BrokerBindingGateway = Pick<K8sGateway, 'getResource'>++/** Not being deleted: the apiserver keeps a deleting object readable until finalizers run. */+export function isLive(meta: { deletionTimestamp?: unknown } | undefined): boolean {+ return meta?.deletionTimestamp === undefined || meta.deletionTimestamp === null+}++/**+ * Live Host → Context resolution. Namespaces are always explicit: without one+ * the gateway falls back to a cluster-wide list. Not-found and every failed+ * condition are a definitive denial; any other read error is `unavailable`, so+ * callers never forward an apiserver RBAC/availability error to the client.+ * A draining Host still resolves: its pod keeps serving until it is gone.+ */+export async function resolveBrokerHostBinding(+ gateway: BrokerBindingGateway,+ hostName: string,+ hostUid: string,+ cfg: { hostsNamespace: string; contextsNamespace: string }+): Promise<HostBinding> {+ let host: HostCR+ try {+ host = (await gateway.getResource('hosts', hostName, cfg.hostsNamespace)) as HostCR+ } catch (err) {+ return isK8sResourceNotFound(err) ? { kind: 'denied' } : { kind: 'unavailable', cause: err }+ }+ if (!host || !isLive(host.metadata) || host.metadata?.uid !== hostUid) return { kind: 'denied' }++ const contextRef = host.spec?.contextRef+ if (typeof contextRef !== 'string' || !isValidK8sName(contextRef)) return { kind: 'denied' }++ let ctx: ContextCR+ try {+ ctx = (await gateway.getResource('contexts', contextRef, cfg.contextsNamespace)) as ContextCR+ } catch (err) {+ return isK8sResourceNotFound(err) ? { kind: 'denied' } : { kind: 'unavailable', cause: err }+ }+ if (!ctx || ctx.metadata?.name !== contextRef || !isLive(ctx.metadata)) return { kind: 'denied' }++ const raw = ctx.spec?.mcpServers+ const allowlist = Array.isArray(raw)+ ? raw.filter((entry): entry is string => typeof entry === 'string')+ : []+ return { kind: 'ok', host, ctx, allowlist }+}++/**+ * The admin API lets `spec.contextId` differ from the Context's name. The+ * broker keys nothing by contextId, so a mismatch is only worth a warning:+ * denying on it would silently cut OAuth for every Host of that Context.+ */+export function hasContextIdMismatch(ctx: ContextCR): boolean {+ const contextId = ctx.spec?.contextId+ return typeof contextId === 'string' && contextId !== ctx.metadata?.name+}++// Same entry rule rpc-proxy applies to let a user into a Host: an active user+// with the agent assigned directly or through any active team membership.+// Context membership (`user_contexts`) deliberately does not count: it never+// admits a user to a Host, and counting it would let any Context member's+// identity be used from every Host of that Context.+const HOST_ACCESS_SQL = `+ SELECT 1+ FROM users u+ WHERE u.id = $1::uuid+ AND u.lifecycle_state = 'active'+ AND (+ EXISTS (SELECT 1 FROM user_agents ua WHERE ua.user_id = u.id AND ua.agent_name = $2)+ OR EXISTS (+ SELECT 1+ FROM team_members tm+ JOIN team_agents ta ON ta.team_id = tm.team_id+ WHERE tm.user_id = u.id+ AND tm.status = 'active'+ AND ta.agent_name = $2+ )+ )+ LIMIT 1`++/**+ * Whether `userId` may act through Host `hostName`. A non-canonical id is a+ * denial without touching the DB. Throws on a DB error so the caller decides+ * between fail-closed (token mint) and fail-open (existence sweep).+ */+export async function hostAccessForUser(+ db: Pick<DbClient, 'query'>,+ userId: string,+ hostName: string+): Promise<'allowed' | 'denied'> {+ if (!isCanonicalUuid(userId)) return 'denied'+ const result = await db.query(HOST_ACCESS_SQL, [userId, hostName])+ return (result.rowCount ?? 0) > 0 ? 'allowed' : 'denied'+}diff --git a/control-api/test/fixtures/contextAllowlist.ts b/control-api/test/fixtures/contextAllowlist.tsindex e5b4fe4c0..a4699421c 100644--- a/control-api/test/fixtures/contextAllowlist.ts+++ b/control-api/test/fixtures/contextAllowlist.ts@@ -78,6 +78,14 @@ export function membershipResult(): QueryResult | null {const text = typeof sql === 'string' ? sql : ''const userId = Array.isArray(values) ? String(values[0]) : ''+ // The broker's Host-entry read (`hostAccessForUser`) also names user_agents in+ // a subquery, so it is matched first. Unit stand-in: direct agent rows only;+ // lifecycle_state and team membership are covered against real Postgres.+ if (text.includes('lifecycle_state') && text.includes('team_agents')) {+ const hostName = Array.isArray(values) ? String(values[1]) : ''+ const allowed = (membership.agents?.[userId] ?? []).includes(hostName)+ return allowed ? { rows: [{ allowed: 1 }], rowCount: 1 } : { rows: [], rowCount: 0 }+ }if (text.includes('FROM user_contexts')) {const ids = membership.contexts?.[userId] ?? []return { rows: ids.map(context_id => ({ context_id })), rowCount: ids.length }diff --git a/control-api/test/fixtures/hccControlToken.ts b/control-api/test/fixtures/hccControlToken.tsnew file mode 100644index 000000000..4f7cdb87e--- /dev/null+++ b/control-api/test/fixtures/hccControlToken.ts@@ -0,0 +1,86 @@+import jwt from 'jsonwebtoken'+import request from 'supertest'+import { config } from '../../src/config.js'+import type { MockGateway } from '../mockGateway.js'++type Provisioner = 'hcc' | 'wrc'++/**+ * Internal control JWT a provisioner (host-context-controller / workflow-recipes)+ * presents to the issuance route, signed with that provisioner's HMAC secret.+ */+export function signInternalControlJwt(iss: Provisioner | string): string {+ const secret =+ iss === 'hcc' ? config.internalControlJwtHccHmacSecret : config.internalControlJwtWrcHmacSecret+ return jwt.sign({ iss, aud: 'control-api', sub: `${iss}-provisioner` }, secret, {+ algorithm: 'HS256',+ expiresIn: 60,+ jwtid: `${iss}-test-jti-${Date.now()}-${Math.random().toString(36).slice(2)}`,+ })+}++/**+ * The control token ("gafete") host-context-controller obtains for `host`,+ * minted through the real issuance route with the uid of the Host CR the+ * gateway holds. Going through the route (not the signing function) means a+ * route that stops forwarding host_uid turns every broker suite red.+ */+export async function mintHccControlToken(+ app: Parameters<typeof request>[0],+ gateway: MockGateway,+ host: string,+ scopes: string[] = ['oauth:user-token']+): Promise<string> {+ const cr = (await gateway.getResource('hosts', host, config.hostsNamespace)) as {+ metadata: { uid: string }+ }+ const res = await request(app)+ .post(`/api/v1/auth/mcp-host/${config.hostsNamespace}/standalone/tokens`)+ .set('Authorization', `Bearer ${signInternalControlJwt('hcc')}`)+ .send({+ includeMcpHostControlToken: true,+ workflowControlScopes: scopes,+ host,+ hostUid: cr.metadata.uid,+ })+ if (res.status !== 200) {+ throw new Error(`hcc control token issuance failed: ${res.status} ${res.text}`)+ }+ return res.body.mcpHostControlToken as string+}++/**+ * A control token shaped like those issued before host_uid existed, or forged+ * with the signing key. Declared exception to deriving fixtures from the+ * producer: the current issuer strips `oauth:user-token` from any non-HCC+ * token and always signs host_uid on HCC ones, so it can no longer emit these+ * shapes, yet live or stolen tokens may still carry them. Claims mirror what+ * `issueMcpHostControlJwt` signs.+ */+export function signLegacyControlToken(claims: {+ recipeNamespace: string+ recipeName: string+ hostRefs: string[]+ scopes?: string[]+ host_uid?: string+}): string {+ return jwt.sign(+ {+ sub: `${claims.recipeNamespace}/${claims.recipeName}`,+ recipeNamespace: claims.recipeNamespace,+ recipeName: claims.recipeName,+ hostRefs: claims.hostRefs,+ typ: 'service',+ scopes: claims.scopes ?? ['oauth:user-token'],+ ...(claims.host_uid !== undefined ? { host_uid: claims.host_uid } : {}),+ },+ config.adminJwtPrivateKey,+ {+ algorithm: 'RS256',+ issuer: config.adminJwtIssuer,+ audience: 'mcp-host',+ jwtid: `legacy-${Date.now()}-${Math.random().toString(36).slice(2)}`,+ expiresIn: 300,+ }+ )+}diff --git a/control-api/test/helpers/requestLogCapture.ts b/control-api/test/helpers/requestLogCapture.tsindex 683e7bdfb..0bd0ece55 100644--- a/control-api/test/helpers/requestLogCapture.ts+++ b/control-api/test/helpers/requestLogCapture.ts@@ -9,15 +9,16 @@ import { rootLogger } from '../../src/observability/logger.js'export function captureRequestLogs() {const info = vi.fn()const warn = vi.fn()+ const debug = vi.fn()const fakeChild: Record<string, unknown> = {info,warn,error: vi.fn(),- debug: vi.fn(),+ debug,trace: vi.fn(),fatal: vi.fn(),}fakeChild.child = () => fakeChildconst spy = vi.spyOn(rootLogger, 'child').mockReturnValue(fakeChild as never)- return { info, warn, restore: () => spy.mockRestore() }+ return { info, warn, debug, restore: () => spy.mockRestore() }}diff --git a/control-api/test/mockGateway.ts b/control-api/test/mockGateway.tsindex be70a60fd..dac950260 100644--- a/control-api/test/mockGateway.ts+++ b/control-api/test/mockGateway.ts@@ -262,6 +262,18 @@ export class MockGateway {this.getResourceFailures.set(plural, queue)}+ /**+ * Test helper: put a stored resource in the "being deleted" state the+ * apiserver reports while finalizers run (`metadata.deletionTimestamp` set,+ * object still readable). `createResource` drops that field, so this is the+ * only way to model it.+ */+ markDeleting(plural: ResourceType, name: string, namespace?: string): void {+ const row = this.store[plural].get(this.key(name, namespace))+ if (!row) throw new Error(`markDeleting: ${plural}/${name} not found`)+ ;(row.metadata as Record<string, unknown>).deletionTimestamp = new Date().toISOString()+ }+async getResource(plural: ResourceType, name: string, namespace?: string): Promise<unknown> {const queuedFailure = this.getResourceFailures.get(plural)if (queuedFailure && queuedFailure.length > 0) {diff --git a/control-api/test/oauth.remoteSpecCoherence.test.ts b/control-api/test/oauth.remoteSpecCoherence.test.tsindex f03970598..9ddbe4bb0 100644--- a/control-api/test/oauth.remoteSpecCoherence.test.ts+++ b/control-api/test/oauth.remoteSpecCoherence.test.ts@@ -12,8 +12,8 @@ import {import { signOAuthState } from '../src/oauth/state.js'import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'-import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'-import { membership, seedAllowlistedContext } from './fixtures/contextAllowlist.js'+import { membership, seedAgentHost, seedAllowlistedContext } from './fixtures/contextAllowlist.js'+import { mintHccControlToken } from './fixtures/hccControlToken.js'import {type InstalledMcpServer,WORKIQ_GUID_SCOPE,@@ -65,6 +65,9 @@ vi.mock('../src/services/rateLimiterService.js', () => ({const MCP_NS = config.mcpServersNamespaceconst CONTEXT = 'ctx-9'+const RUNTIME_HOST = 'agent-host'+// users.id is a UUID: the broker refuses any other end-user id.+const RUNTIME_USER = '3f9a1c2e-6b4d-4e8f-a1c3-5d7e9f0b2a46'const PRE_REGISTERED_CLIENT_ID = 'client-abc'const CIMD_SELF = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'const RPC_PROXY_TOKEN = 'dev-rpc-proxy-token'@@ -628,7 +631,11 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_iit(`${c.label}: POST /mcp-oauth/user-token → ${c.consentOnly ? '200, the stored token is served' : '409 even with a fresh stored token'}`, async () => {const oauth = c.oauth()const uid = await seed('srv', oauth, c.remote?.())- mockPoolQuery.mockImplementation((sql: unknown) => {+ // The runtime caller is a live Host of CONTEXT, through whose allowlist the+ // server is reached, and the end user enters that Host.+ await seedAgentHost(gateway, RUNTIME_HOST, CONTEXT)+ const token = await mintHccControlToken(app, gateway, RUNTIME_HOST)+ membership(mockPoolQuery, { agents: { [RUNTIME_USER]: [RUNTIME_HOST] } }, sql => {const text = typeof sql === 'string' ? sql : ''if (text.includes('FROM oauth_grants')) {return Promise.resolve({@@ -637,7 +644,7 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_iowner_kind: 'mcpserver',recipe_namespace: MCP_NS,recipe_name: 'srv',- user_id: 'user-1',+ user_id: RUNTIME_USER,context_id: null,bootstrapped_by_user_id: null,oauth_client_id: oauth.id,@@ -656,14 +663,10 @@ describe('routes refuse an incoherent remote server with 409 remote_oauth_spec_i}return Promise.resolve({ rows: [], rowCount: 0 })})- const token = issueMcpHostControlJwt('mcp-host', 'standalone', ['agent-host'], {- scopes: ['oauth:user-token'],- hccCredential: { hostUid: 'uid-agent-host' },- }).tokenconst res = await request(app).post('/api/v1/mcp-oauth/user-token').set('Authorization', `Bearer ${token}`)- .send({ mcpServerName: 'srv', userId: 'user-1' })+ .send({ mcpServerName: 'srv', userId: RUNTIME_USER })if (c.consentOnly) {expect(res.status).toBe(200)expect(JSON.stringify(res.body)).toContain('LIVE-ACCESS')diff --git a/control-api/test/routes.mcpOauth.brokerBinding.property.test.ts b/control-api/test/routes.mcpOauth.brokerBinding.property.test.tsnew file mode 100644index 000000000..6503b494c--- /dev/null+++ b/control-api/test/routes.mcpOauth.brokerBinding.property.test.ts@@ -0,0 +1,185 @@+import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import fc from 'fast-check'+import request from 'supertest'+import { createApp } from '../src/app.js'+import { config } from '../src/config.js'+import { discoverRemoteOAuth } from '../src/oauth/discovery.js'+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'+import { attachServerToContext } from '../src/services/contextAllowlist.js'+import { membership, seedAgentHost, seedAllowlistedContext } from './fixtures/contextAllowlist.js'+import { mintHccControlToken } from './fixtures/hccControlToken.js'+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'+import { MockGateway } from './mockGateway.js'++/**+ * P-I5: seen from a Host, "does not exist", "outside my Context's allowlist",+ * "being deleted", "disabled" and, for shared servers, "owned by another+ * Context" are indistinguishable: same status, same bytes, and no grant or+ * Secret is read. The server's shape (OAuth, incoherent remote spec, not OAuth,+ * unsupported provider) must not leak through either, which pins the+ * allowlist/state checks before the OAuth and coherence checks.+ */++const mockPoolQuery = vi.fn()+vi.mock('../src/db.js', () => ({+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },+}))+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 MCP_NS = config.mcpServersNamespace+const HOST = 'agent-host'+const HOST_CONTEXT = 'ctx-host'+const OTHER_CONTEXT = 'ctx-other'+const SERVER = 'probe'+const USER = '5e1d7a3c-9b2f-4c8e-a6d0-3f7b1e9c2a58'++type State =+ | 'missing'+ | 'outside_allowlist'+ | 'deleting'+ | 'disabled'+ | 'foreign_owner'+ | 'no_owner'+type Shape = 'oauth' | 'remote_incoherent' | 'not_oauth' | 'unsupported_provider'++let remoteIncoherent: (grantScope: 'user' | 'context') => Record<string, unknown>++beforeAll(async () => {+ const outcome = await discoverRemoteOAuth(PILOTS.sentry.mcpUrl, {+ transport: makeDiscoveryTransport(PILOTS.sentry),+ resolveDns: async () => ['93.184.216.34'],+ })+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)+ // The builder's confidential output with clientMode flipped to public: the+ // in-place edit a direct write would make, which the CRD now rejects.+ remoteIncoherent = grantScope => ({+ ...(buildRemoteOAuthSpec(outcome.result, {+ clientMode: 'confidential',+ grantScope,+ clientSecretName: 'probe-oauth-client',+ preRegisteredClientId: 'client-abc',+ }) as unknown as Record<string, unknown>),+ clientMode: 'public',+ })+})++function serverSpec(+ shape: Shape,+ grantScope: 'user' | 'context',+ owner: string | undefined+): Record<string, unknown> {+ const base = owner === undefined ? {} : { contextRef: owner }+ if (shape === 'not_oauth') return { ...base, auth: { type: 'none' } }+ if (shape === 'remote_incoherent') {+ return { ...base, auth: { type: 'oauth' }, oauth: remoteIncoherent(grantScope) }+ }+ return {+ ...base,+ auth: { type: 'oauth' },+ oauth: {+ id: 'probe-client',+ provider: shape === 'unsupported_provider' ? 'no-such-provider' : 'google',+ clientIdRef: { name: 'probe-creds', key: 'client-id' },+ clientSecretRef: { name: 'probe-creds', key: 'client-secret' },+ grantScope,+ },+ }+}++const caseArb = fc.oneof(+ fc.record({+ state: fc.constantFrom<State>('missing', 'outside_allowlist', 'deleting', 'disabled'),+ shape: fc.constantFrom<Shape>(+ 'oauth',+ 'remote_incoherent',+ 'not_oauth',+ 'unsupported_provider'+ ),+ grantScope: fc.constantFrom<'user' | 'context'>('user', 'context'),+ withUserId: fc.boolean(),+ withContextId: fc.boolean(),+ }),+ // The owner rule only applies to shared OAuth servers.+ fc.record({+ state: fc.constantFrom<State>('foreign_owner', 'no_owner'),+ shape: fc.constantFrom<Shape>('oauth', 'remote_incoherent'),+ grantScope: fc.constant<'user' | 'context'>('context'),+ withUserId: fc.boolean(),+ withContextId: fc.boolean(),+ })+)++describe('P-I5: uniform server_not_found across the Context boundary', () => {+ const originalBrokerEnabled = config.mcpOauthBrokerEnabled++ beforeEach(() => {+ config.mcpOauthBrokerEnabled = true+ })++ afterEach(() => {+ config.mcpOauthBrokerEnabled = originalBrokerEnabled+ })++ it('every hidden state answers 404 {"error":"server_not_found"} without reading grants or Secrets', async () => {+ await fc.assert(+ fc.asyncProperty(caseArb, async c => {+ mockPoolQuery.mockReset()+ membership(mockPoolQuery, { agents: { [USER]: [HOST] } })+ const gateway = new MockGateway(MCP_NS)+ const app = createApp(gateway as never)+ await seedAgentHost(gateway, HOST, HOST_CONTEXT)+ await seedAllowlistedContext(gateway, HOST_CONTEXT, [], config.contextsNamespace)+ await seedAllowlistedContext(gateway, OTHER_CONTEXT, [SERVER], config.contextsNamespace)+ const token = await mintHccControlToken(app, gateway, HOST)++ const owner =+ c.state === 'no_owner'+ ? undefined+ : c.state === 'foreign_owner' || c.state === 'outside_allowlist'+ ? OTHER_CONTEXT+ : HOST_CONTEXT+ if (c.state !== 'missing') {+ const spec = serverSpec(c.shape, c.grantScope, owner)+ if (c.state === 'disabled') spec.enabled = false+ await gateway.createResource('mcpservers', { metadata: { name: SERVER }, spec }, MCP_NS)+ if (c.state === 'deleting') gateway.markDeleting('mcpservers', SERVER, MCP_NS)+ }+ if (c.state !== 'outside_allowlist') {+ await attachServerToContext(+ gateway as never,+ { name: HOST_CONTEXT, namespace: config.contextsNamespace },+ SERVER+ )+ }+ const secretReads = vi.spyOn(gateway, 'getSecret')++ const res = await request(app)+ .post('/api/v1/mcp-oauth/user-token')+ .set('Authorization', `Bearer ${token}`)+ .send({+ mcpServerName: SERVER,+ ...(c.withUserId ? { userId: USER } : {}),+ ...(c.withContextId ? { contextId: HOST_CONTEXT } : {}),+ })++ expect(res.status).toBe(404)+ expect(res.text).toBe('{"error":"server_not_found"}')+ const grantReads = mockPoolQuery.mock.calls.filter(+ ([sql]) => typeof sql === 'string' && sql.includes('oauth_grants')+ )+ expect(grantReads).toHaveLength(0)+ expect(secretReads).not.toHaveBeenCalled()+ }),+ { numRuns: 200 }+ )+ })+})diff --git a/control-api/test/routes.mcpOauth.brokerBinding.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.brokerBinding.realPostgres.integration.test.tsnew file mode 100644index 000000000..c999fd0c5--- /dev/null+++ b/control-api/test/routes.mcpOauth.brokerBinding.realPostgres.integration.test.ts@@ -0,0 +1,322 @@+/**+ * The broker's user rule (`POST /mcp-oauth/user-token`, per-user servers): a+ * token is served only to an active user who enters the calling Host, either+ * directly (`user_agents`) or through an active team membership whose team has+ * the Host (`team_agents`). Context membership alone does not count.+ *+ * Runs through the real app against a real Postgres: the rule is a join over+ * `users.lifecycle_state`, `team_members.status` and a UUID column, which a+ * mocked pool cannot exercise. Memberships are written by the production+ * writers (seedActiveMember → setUserAgents/setUserContexts, createTeamForUser,+ * setTeamAgents, softDeleteMember, retireDesktopUser); grants by+ * `upsertOAuthGrant`.+ *+ * CONTROL_API_REAL_PG_ADMIN_URL=postgres://<user>:<pass>@<host>:5432 npm test -- \+ * test/routes.mcpOauth.brokerBinding.realPostgres.integration.test.ts+ */+import { afterAll, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'+import fc from 'fast-check'+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'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { upsertOAuthGrant } from '../src/oauth/store.js'+import { setTeamAgents } from '../src/services/directory/agentAccess.js'+import { softDeleteMember } from '../src/services/directory/membership.js'+import { createTeamForUser } from '../src/services/directory/teams.js'+import { retireDesktopUser } from '../src/services/directory/users.js'+import {+ seedActiveMember,+ seedAgentHost,+ seedAllowlistedContext,+ seedControlAdmin,+} from './fixtures/contextAllowlist.js'+import { mintHccControlToken } from './fixtures/hccControlToken.js'+import { endPoolAndWaitForClients } from './helpers/realPostgresTeardown.js'+import { MockGateway } from './mockGateway.js'++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_URL+const describeRealPostgres = adminUrl ? describe : describe.skip++function databaseUrl(baseUrl: string, database: string): string {+ const url = new URL(baseUrl)+ url.pathname = `/${database}`+ return url.toString()+}++const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)+const NS = config.mcpServersNamespace+const HOST = 'agent-host'+// Another agent of the same Context: entering it must not open HOST.+const SIBLING_HOST = 'sibling-host'+const CONTEXT = 'ctx-binding'+const SERVER = 'gdrive'++describeRealPostgres('broker user rule: entry to the calling Host (real Postgres)', () => {+ const database = `control_api_broker_binding_${randomUUID().replace(/-/g, '')}`+ let adminPool: Pool+ let dbPool: Pool+ let db: DbClient+ let gateway: MockGateway+ let app: ReturnType<typeof createApp>+ let token: string+ let operator: string+ const originalBrokerEnabled = config.mcpOauthBrokerEnabled++ 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) }+ testDb.pool = dbPool+ config.mcpOauthBrokerEnabled = true+ operator = await seedControlAdmin(db)+ })++ afterAll(async () => {+ try {+ config.mcpOauthBrokerEnabled = originalBrokerEnabled+ testDb.pool = undefined+ if (dbPool) await endPoolAndWaitForClients(dbPool)+ 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, '""')}"`)+ }+ } finally {+ await adminPool?.end()+ }+ })++ beforeEach(async () => {+ await dbPool.query('DELETE FROM oauth_grants')+ gateway = new MockGateway(NS)+ app = createApp(gateway as never)+ await gateway.createResource(+ 'mcpservers',+ {+ metadata: { name: SERVER },+ spec: {+ contextRef: CONTEXT,+ auth: { type: 'oauth' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ grantScope: 'user',+ },+ },+ },+ NS+ )+ await seedAgentHost(gateway, HOST, CONTEXT)+ await seedAgentHost(gateway, SIBLING_HOST, CONTEXT)+ await seedAllowlistedContext(gateway, CONTEXT, [SERVER], config.contextsNamespace)+ token = await mintHccControlToken(app, gateway, HOST)+ })++ /** A connected grant for `userId`, sealed to the installed server. */+ async function connect(userId: string): Promise<void> {+ const cr = (await gateway.getResource('mcpservers', SERVER, NS)) as {+ metadata: { uid: string }+ }+ await upsertOAuthGrant(db, KEY, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: NS,+ recipeName: SERVER,+ userId,+ oauthClientId: 'google-drive',+ provider: 'google',+ accessToken: `AT-${userId}`,+ accessTokenExpiresInSec: 3600,+ crUid: cr.metadata.uid,+ })+ }++ const mint = (userId: string) =>+ request(app)+ .post('/api/v1/mcp-oauth/user-token')+ .set('Authorization', `Bearer ${token}`)+ .send({ mcpServerName: SERVER, userId })++ async function expectServed(userId: string): Promise<void> {+ const res = await mint(userId)+ expect(res.status).toBe(200)+ expect(res.body.token).toBe(`AT-${userId}`)+ }++ async function expectNoGrant(userId: string): Promise<void> {+ const res = await mint(userId)+ expect(res.status).toBe(404)+ expect(res.text).toBe('{"error":"no_grant"}')+ }++ async function teamWithHost(userId: string, agents: string[]): Promise<string> {+ const team = await createTeamForUser(userId, `team-${randomUUID()}`)+ await setTeamAgents(team.id, agents, operator)+ return team.id+ }++ async function retire(userId: string): Promise<void> {+ await retireDesktopUser(+ { kind: 'control_admin', controlAdminId: operator },+ userId,+ 'broker binding real-pg',+ `retire-${userId}`,+ null,+ { retainWithoutLinkHistory: true }+ )+ }++ it('R7d: served when the user has the Host assigned directly (I-6)', async () => {+ const user = await seedActiveMember(db, { agents: [HOST] })+ await connect(user)+ await expectServed(user)+ })++ it('R7d: served when the user enters the Host through an active team (I-6)', async () => {+ const user = await seedActiveMember(db, {})+ await teamWithHost(user, [HOST])+ await connect(user)+ await expectServed(user)+ })++ it('R7: a user of another agent of the same Context gets no_grant (I-3)', async () => {+ const user = await seedActiveMember(db, { contexts: [CONTEXT], agents: [SIBLING_HOST] })+ await connect(user)+ await expectNoGrant(user)+ })++ it('R7a: Context membership alone (user_contexts) does not open the Host', async () => {+ const user = await seedActiveMember(db, { contexts: [CONTEXT] })+ await connect(user)+ await expectNoGrant(user)+ })++ it('R7b: a retired user gets no_grant although the grant remains', async () => {+ const user = await seedActiveMember(db, { agents: [HOST] })+ await connect(user)+ await retire(user)+ await expectNoGrant(user)+ })++ it('R7c: a deleted team membership no longer opens the Host', async () => {+ const user = await seedActiveMember(db, {})+ const teamId = await teamWithHost(user, [HOST])+ await connect(user)+ await softDeleteMember(teamId, user, operator)+ await expectNoGrant(user)+ })++ it('R7e: ids that are not canonical UUIDs are a definitive no_grant, never a 5xx', async () => {+ const user = await seedActiveMember(db, { agents: [HOST] })+ // The braced and hyphen-less spellings of an entitled user's id are valid+ // Postgres uuid input; each carries its own grant so only the format rule+ // can refuse them.+ const variants = [+ 'U024BE7LH',+ '[email protected]',+ 'e2e-vitest-runtime',+ `{${user}}`,+ user.replace(/-/g, ''),+ ]+ for (const id of variants) {+ await connect(id)+ const res = await mint(id)+ expect(res.status, id).toBe(404)+ expect(res.text, id).toBe('{"error":"no_grant"}')+ }+ })++ it('R7e: an upper-case UUID is evaluated, not rejected by format', async () => {+ const user = await seedActiveMember(db, { agents: [HOST] })+ const upper = user.toUpperCase()+ await connect(upper)+ await expectServed(upper)+ })++ // R7g / P-I3, P-I6: the route agrees with the reference model+ // active ∧ (HOST ∈ user_agents ∨ ∃ active membership whose team has HOST)+ // over generated memberships written by the production writers.+ it('R7g: the served set equals the reference model for generated memberships', async () => {+ const membershipArb = fc.record({+ active: fc.boolean(),+ direct: fc.boolean(),+ contextMember: fc.boolean(),+ teams: fc.array(fc.record({ membershipActive: fc.boolean(), teamHasHost: fc.boolean() }), {+ maxLength: 2,+ }),+ })+ await fc.assert(+ fc.asyncProperty(fc.array(membershipArb, { minLength: 1, maxLength: 3 }), async users => {+ await dbPool.query('DELETE FROM oauth_grants')+ for (const m of users) {+ const userId = await seedActiveMember(db, {+ agents: m.direct ? [HOST] : [SIBLING_HOST],+ contexts: m.contextMember ? [CONTEXT] : [],+ })+ for (const t of m.teams) {+ const teamId = await teamWithHost(userId, t.teamHasHost ? [HOST] : [SIBLING_HOST])+ if (!t.membershipActive) await softDeleteMember(teamId, userId, operator)+ }+ if (!m.active) await retire(userId)+ await connect(userId)++ const expected =+ m.active && (m.direct || m.teams.some(t => t.membershipActive && t.teamHasHost))+ const res = await mint(userId)+ expect(res.status).toBe(expected ? 200 : 404)+ if (!expected) expect(res.text).toBe('{"error":"no_grant"}')+ }+ }),+ { numRuns: 25 }+ )+ }, 120_000)+})diff --git a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.tsindex 2b2b58f3e..a4c1f1919 100644--- a/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts+++ b/control-api/test/routes.mcpOauth.legacyGrantLaneFence.realPostgres.integration.test.ts@@ -26,7 +26,8 @@ import { initDb } from '../src/db.js'import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'import { resolveBatchGrantExistence } from '../src/routes/mcpOauth.js'import { resolveInvocableMcpServersForContexts } from '../src/services/access/mcpInvocable.js'-import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'+import { seedActiveMember, seedAgentHost } from './fixtures/contextAllowlist.js'+import { mintHccControlToken } from './fixtures/hccControlToken.js'import {CONTEXT,NS,@@ -56,6 +57,8 @@ vi.mock('../src/db.js', async () => {query: (text: string, values?: unknown[]) => current().query(text, values),connect: () => current().connect(),},+ withTransaction: (work: Parameters<typeof actual.withTransaction>[0]) =>+ actual.withTransaction(work, current()),}})@@ -87,21 +90,16 @@ function databaseUrl(baseUrl: string, database: string): string {const KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)const LEGACY_AT = 'LEGACY-AT-google'-const USER = 'alice'+const HOST = 'agent-host'type Flavor = 'user' | 'context'-function controlToken(): string {- return issueMcpHostControlJwt('mcp-host', 'standalone', ['agent-host'], {- scopes: ['oauth:user-token'],- hccCredential: { hostUid: 'uid-agent-host' },- }).token-}-describeRealPostgres('legacy grants seen by the broker, gate and sweep (real Postgres)', () => {const database = `control_api_legacy_lane_routes_${randomUUID().replace(/-/g, '')}`let adminPool: Poollet dbPool: Poollet db: DbClient+ // An active user who enters HOST, the Host of CONTEXT that calls the broker.+ let USER: stringconst originalBrokerEnabled = config.mcpOauthBrokerEnabledbeforeAll(async () => {@@ -112,6 +110,7 @@ describeRealPostgres('legacy grants seen by the broker, gate and sweep (real Posawait initDb({ connect: () => dbPool.connect() })db = { query: (text, values) => dbPool.query(text, values) }testDb.pool = dbPool+ USER = await seedActiveMember(db, { agents: [HOST] })})afterAll(async () => {@@ -159,14 +158,18 @@ describeRealPostgres('legacy grants seen by the broker, gate and sweep (real Pos{ metadata: { name: CONTEXT }, spec: { contextId: CONTEXT, mcpServers: [name] } },NS)+ await seedAgentHost(gateway, HOST, CONTEXT)return { name, gateway }}- const userToken = (gateway: MockGateway, name: string) =>- request(createApp(gateway as never))+ const userToken = async (gateway: MockGateway, name: string) => {+ const app = createApp(gateway as never)+ const token = await mintHccControlToken(app, gateway, HOST)+ return request(app).post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)+ .set('Authorization', `Bearer ${token}`).send({ mcpServerName: name, userId: USER })+ }const invocable = async (gateway: MockGateway) =>(await resolveInvocableMcpServersForContexts(gateway, NS, [CONTEXT], USER, db)).map(s => s.name)diff --git a/control-api/test/routes.mcpOauth.test.ts b/control-api/test/routes.mcpOauth.test.tsindex 51da560f2..b3e4a08e2 100644--- a/control-api/test/routes.mcpOauth.test.ts+++ b/control-api/test/routes.mcpOauth.test.ts@@ -3,8 +3,20 @@ import request from 'supertest'import { createApp } from '../src/app.js'import { config } from '../src/config.js'import { deriveOAuthEncryptionKey, encryptOAuthSecret } from '../src/oauth/encryption.js'+import { registry } from '../src/observability/metrics.js'+import { attachServerToContext } from '../src/services/contextAllowlist.js'import { checkAndIncrement } from '../src/services/rateLimiterService.js'-import { issueMcpHostControlJwt } from '../src/utils/auth/mcpHostJwtToken.js'+import {+ issueMcpHostControlJwt,+ verifyMcpHostControlJwt,+} from '../src/utils/auth/mcpHostJwtToken.js'+import { membership, seedAgentHost, seedAllowlistedContext } from './fixtures/contextAllowlist.js'+import {+ mintHccControlToken,+ signInternalControlJwt,+ signLegacyControlToken,+} from './fixtures/hccControlToken.js'+import { captureRequestLogs } from './helpers/requestLogCapture.js'import { MockGateway } from './mockGateway.js'const mockPoolQuery = vi.fn()@@ -37,13 +49,14 @@ const ENCRYPTION_KEY = deriveOAuthEncryptionKey(config.oauthEncryptionKey)function seedOauthServer(gateway: MockGateway,- opts: { name: string; grantScope?: 'user' | 'context'; contextRef?: string }+ opts: { name: string; grantScope?: 'user' | 'context'; contextRef?: string; enabled?: boolean }): void {void gateway.createResource('mcpservers',{metadata: { name: opts.name },spec: {+ ...(opts.enabled !== undefined ? { enabled: opts.enabled } : {}),// contextRef is CRD-required + singular — the AUTHORITATIVE Context.contextRef: opts.contextRef ?? 'ctx-9',auth: { type: 'oauth' },@@ -70,8 +83,8 @@ async function liveUid(gateway: MockGateway, name: string): Promise<string> {return cr.metadata.uid}-// Control JWT derived from the REAL minter (T1) — no hand-forged token. Only an-// HCC-lineage control token may carry oauth:user-token, so it is minted for a Host.+// 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,@@ -98,31 +111,95 @@ function nonExpiredUserGrantRow(userId: string, expiresAt: Date) {}}+function sharedGrantRow(contextId: string, expiresAt: Date) {+ return {+ ...nonExpiredUserGrantRow('', expiresAt),+ grant_kind: 'shared',+ user_id: null,+ context_id: contextId,+ bootstrapped_by_user_id: USER_1,+ }+}++const HOST = 'agent-host'+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 grantQueries = () =>+ mockPoolQuery.mock.calls.filter(+ ([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants')+ )++async function deniedCount(reason: string): 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 0+ const { values } = await metric.get()+ return values.find(v => v.labels.reason === reason && v.labels.route === 'user_token')?.value ?? 0+}+describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {let gateway: MockGatewaylet app: ReturnType<typeof createApp>+ let token: string+ let grantRows: unknown[]const originalBrokerEnabled = config.mcpOauthBrokerEnabled- beforeEach(() => {+ // The DB answers by SQL, not by call position: the Host-entry read goes+ // through the shared membership stand-in (USER_1 enters HOST), grant reads+ // return `grantRows`.+ function serveDb(opts: { accessError?: Error } = {}): void {+ membership(mockPoolQuery, { agents: { [USER_1]: [HOST] } }, sql => {+ const text = typeof sql === 'string' ? sql : ''+ if (text.includes('FROM oauth_grants')) {+ return Promise.resolve({ rows: grantRows, rowCount: grantRows.length })+ }+ return Promise.resolve({ rows: [], rowCount: 0 })+ })+ if (opts.accessError) {+ const answer = mockPoolQuery.getMockImplementation()!+ mockPoolQuery.mockImplementation((sql: unknown, values: unknown) =>+ typeof sql === 'string' && sql.includes('lifecycle_state') && sql.includes('team_agents')+ ? Promise.reject(opts.accessError)+ : answer(sql, values)+ )+ }+ }++ const post = (body: Record<string, unknown>, bearer: string = token) =>+ request(app)+ .post('/api/v1/mcp-oauth/user-token')+ .set('Authorization', `Bearer ${bearer}`)+ .send(body)++ beforeEach(async () => {gateway = new MockGateway(MCP_NS)app = createApp(gateway as never)mockPoolQuery.mockReset()- mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })+ grantRows = []+ serveDb()// These specs assert the broker's live behavior, so run them with the// kill-switch ON. The flag defaults OFF (fail-closed); the OFF→404 spec// below flips it back to exercise the disabled path.config.mcpOauthBrokerEnabled = true+ await seedAgentHost(gateway, HOST, HOST_CONTEXT)+ await seedAllowlistedContext(gateway, HOST_CONTEXT, ['gdrive', 'plain', 'no-ctx'])+ token = await mintHccControlToken(app, gateway, HOST)})afterEach(() => {config.mcpOauthBrokerEnabled = originalBrokerEnabled})+ // ── R0: gates that precede the binding, unchanged ─────────────────────────+it('401 without a control JWT', async () => {seedOauthServer(gateway, { name: 'gdrive' })const res = await request(app).post('/api/v1/mcp-oauth/user-token')- .send({ mcpServerName: 'gdrive', userId: 'user-1' })+ .send({ mcpServerName: 'gdrive', userId: USER_1 })expect(res.status).toBe(401)})@@ -131,148 +208,355 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {// keying the limiter by sub would drop all of them in one bucket. The bucket// key must be the verified per-host principal (hostRefs[0]) instead.seedOauthServer(gateway, { name: 'gdrive' })+ await seedAgentHost(gateway, 'host-a', HOST_CONTEXT)+ await seedAgentHost(gateway, 'host-b', HOST_CONTEXT)+ const tokenA = await mintHccControlToken(app, gateway, 'host-a')+ const tokenB = await mintHccControlToken(app, gateway, 'host-b')vi.mocked(checkAndIncrement).mockClear()- const tokenA = issueMcpHostControlJwt('mcp-host', 'standalone', ['host-a'], {- scopes: ['oauth:user-token'],- hccCredential: { hostUid: 'uid-host-a' },- }).token- const tokenB = issueMcpHostControlJwt('mcp-host', 'standalone', ['host-b'], {- scopes: ['oauth:user-token'],- hccCredential: { hostUid: 'uid-host-b' },- }).token-- await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${tokenA}`)- .send({ mcpServerName: 'gdrive', userId: 'user-1' })- await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${tokenB}`)- .send({ mcpServerName: 'gdrive', userId: 'user-1' })+ await post({ mcpServerName: 'gdrive', userId: USER_1 }, tokenA)+ await post({ mcpServerName: 'gdrive', userId: USER_1 }, tokenB)const keys = vi.mocked(checkAndIncrement).mock.calls.map(call => call[0])expect(keys).toHaveLength(2)expect(keys[0]).toBe('mcp-oauth:mcp-host/host/host-a')expect(keys[1]).toBe('mcp-oauth:mcp-host/host/host-b')- expect(keys[0]).not.toBe(keys[1])})it('403 with a valid control JWT that lacks the oauth:user-token scope', async () => {seedOauthServer(gateway, { name: 'gdrive' })- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken([])}`)- .send({ mcpServerName: 'gdrive', userId: 'user-1' })+ const noScope = await mintHccControlToken(app, gateway, HOST, [])+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 }, noScope)expect(res.status).toBe(403)- expect(res.body.error).toBe('insufficient_scope')+ expect(res.text).toBe('{"error":"insufficient_scope"}')})- it('200 {token,expiresAt} for a per-user grant, keyed by (mcpserver owner, userId)', async () => {+ // ── Rule 1a: caller lineage ───────────────────────────────────────────────++ it('R1a: a workflow-recipe control token carrying the scope → 403 host_not_bound (I-4)', async () => {seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })- const future = new Date(Date.now() + 3600_000)- mockPoolQuery.mockResolvedValueOnce({- rows: [nonExpiredUserGrantRow('user-1', future)],- rowCount: 1,+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ const wrc = signLegacyControlToken({+ recipeNamespace: config.sandboxNamespace,+ recipeName: 'recipe-x',+ hostRefs: [`${config.sandboxNamespace}/recipe-x`],})+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 }, wrc)+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ expect(grantQueries()).toHaveLength(0)+ })+ it('R1a: the real issuer no longer gives a workflow-recipe control token the scope', async () => {const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'user-1', contextId: 'ctx-9' })+ .post(`/api/v1/auth/mcp-host/${config.sandboxNamespace}/recipe-x/tokens`)+ .set('Authorization', `Bearer ${signInternalControlJwt('wrc')}`)+ .send({ includeMcpHostControlToken: true, workflowControlScopes: ['oauth:user-token'] })+ expect(res.status).toBe(200)+ const claims = verifyMcpHostControlJwt(res.body.mcpHostControlToken)+ expect(claims?.scopes).not.toContain('oauth:user-token')+ })++ it.each([+ ['the reserved name standalone', { hostRefs: ['standalone'] }],+ ['a namespaced hostRef', { hostRefs: ['ns/agent-host'] }],+ ['two hostRefs', { hostRefs: ['agent-host', 'other-host'] }],+ ['a recipe name other than standalone', { recipeName: 'other', hostRefs: ['agent-host'] }],+ ['another namespace', { recipeNamespace: 'elsewhere', hostRefs: ['agent-host'] }],+ ])('R1a: an HCC-like token with %s → 403 host_not_bound', async (_label, shape) => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ const forged = signLegacyControlToken({+ recipeNamespace: config.hostsNamespace,+ recipeName: 'standalone',+ host_uid: 'uid-anything',+ ...shape,+ } as Parameters<typeof signLegacyControlToken>[0])+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 }, forged)+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ })++ // ── Rule 1b: host_uid present ─────────────────────────────────────────────++ it('R1b: an HCC token without host_uid → 401 with the requireControlCaller body', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ const legacy = signLegacyControlToken({+ recipeNamespace: config.hostsNamespace,+ recipeName: 'standalone',+ hostRefs: [HOST],+ })+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 }, legacy)+ expect(res.status).toBe(401)+ expect(res.text).toBe('{"error":"Unauthorized"}')+ expect(grantQueries()).toHaveLength(0)+ })++ it('400 invalid_request for a malformed (non-k8s) server name, before any getResource', async () => {+ const reads = vi.spyOn(gateway, 'getResource')+ const res = await post({ mcpServerName: 'Foo/Bar', userId: USER_1 })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('invalid_request')+ expect(reads).not.toHaveBeenCalled()+ })++ // ── Rule 2: live Host with the token's uid ────────────────────────────────++ it('R2a: Host deleted after issuance → 403 host_not_bound', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ await gateway.deleteResource('hosts', HOST, config.hostsNamespace)+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ expect(grantQueries()).toHaveLength(0)+ })++ it('R2a: Host being deleted → 403 host_not_bound', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ gateway.markDeleting('hosts', HOST, config.hostsNamespace)+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ })++ it('R2b: Host recreated under the same name (new uid) → 403 host_not_bound (I-8)', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ await gateway.deleteResource('hosts', HOST, config.hostsNamespace)+ await seedAgentHost(gateway, HOST, HOST_CONTEXT)+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ expect(grantQueries()).toHaveLength(0)+ })+ it('R2c: a draining Host still obtains its token', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ const host = (await gateway.getResource('hosts', HOST, config.hostsNamespace)) as {+ status?: Record<string, unknown>+ }+ host.status = { lifecycle: { state: 'draining' } }+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })expect(res.status).toBe(200)expect(res.body.token).toBe('GDRIVE-ACCESS')- expect(res.body.expiresAt).toBe(future.toISOString())+ })- // Grant lookup scoped to the mcpserver owner + asserted userId, oauthClientId- // derived from the server (never the body).- const grantQuery = mockPoolQuery.mock.calls.find(- ([sql]) =>- typeof sql === 'string' &&- sql.includes('FROM oauth_grants') &&- sql.includes("grant_kind = 'user'")+ it.each([+ ['an apiserver outage', { statusCode: 503 }],+ ['an RBAC refusal', { statusCode: 403, body: { message: 'hosts is forbidden' } }],+ ])('R2d: %s reading the Host → 503 fixed body, no grant read', async (_label, err) => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ gateway.failGetResource('hosts', err)+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(503)+ expect(res.text).toBe('{"error":"host_state_unavailable"}')+ expect(grantQueries()).toHaveLength(0)+ })++ // ── Rule 3: the Host's Context ────────────────────────────────────────────++ it('R3: the Host Context does not exist → 403 host_not_bound', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ await gateway.deleteResource('contexts', HOST_CONTEXT, config.contextsNamespace)+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ })++ it('R3: the Host Context is being deleted → 403 host_not_bound', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ gateway.markDeleting('contexts', HOST_CONTEXT, config.contextsNamespace)+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ })++ it.each([+ ['empty', ''],+ ['not a k8s name', 'Bad/Name'],+ ])('R3: host.spec.contextRef %s → 403 without reading contexts', async (_label, ref) => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ await seedAgentHost(gateway, 'odd-host', ref)+ const odd = await mintHccControlToken(app, gateway, 'odd-host')+ const reads = vi.spyOn(gateway, 'getResource')+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 }, odd)+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ expect(reads.mock.calls.some(([plural]) => plural === 'contexts')).toBe(false)+ })++ it('R3: the Context is read from contextsNamespace, not the mcp-servers namespace', async () => {+ const originalContextsNamespace = config.contextsNamespace+ config.contextsNamespace = 'contexts-elsewhere'+ try {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ await seedAgentHost(gateway, 'split-host', 'ctx-split')+ // Only the contexts namespace holds this Context.+ await seedAllowlistedContext(gateway, 'ctx-split', ['gdrive'], config.contextsNamespace)+ const split = await mintHccControlToken(app, gateway, 'split-host')+ mockPoolQuery.mockReset()+ membership(mockPoolQuery, { agents: { [USER_1]: ['split-host'] } }, sql =>+ Promise.resolve(+ typeof sql === 'string' && sql.includes('FROM oauth_grants')+ ? { rows: grantRows, rowCount: grantRows.length }+ : { rows: [], rowCount: 0 }+ )+ )+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 }, split)+ expect(res.status).toBe(200)+ expect(res.body.token).toBe('GDRIVE-ACCESS')+ } finally {+ config.contextsNamespace = originalContextsNamespace+ }+ })++ it('R3: a Context object whose name differs from host.spec.contextRef → 403 host_not_bound', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ // Stub: the apiserver answers the Context read with another object.+ const read = gateway.getResource.bind(gateway)+ vi.spyOn(gateway, 'getResource').mockImplementation(async (plural, name, ns) => {+ const row = (await read(plural, name, ns)) as { metadata: Record<string, unknown> }+ return plural === 'contexts'+ ? { ...row, metadata: { ...row.metadata, name: 'ctx-other' } }+ : row+ })+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(403)+ expect(res.text).toBe('{"error":"host_not_bound"}')+ expect(grantQueries()).toHaveLength(0)+ })++ it('R3: a transient error reading the Context → 503', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ gateway.failGetResource('contexts', { statusCode: 500 })+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(503)+ expect(res.text).toBe('{"error":"host_state_unavailable"}')+ })++ it('R3b: spec.contextId differing from the Context name is served and only logged', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ await seedAgentHost(gateway, 'renamed-host', 'ctx-renamed')+ await gateway.createResource(+ 'contexts',+ { metadata: { name: 'ctx-renamed' }, spec: { contextId: 'legacy-id', mcpServers: [] } },+ config.contextsNamespace)- expect(grantQuery?.[1]).toEqual([- 'mcpserver',- MCP_NS,- 'gdrive',- 'user-1',- 'google-drive',- await liveUid(gateway, 'gdrive'),- // Baked CR: the reader key carries its provider for unsealed legacy rows.- 'google',- ])+ await attachServerToContext(+ gateway as never,+ { name: 'ctx-renamed', namespace: config.contextsNamespace },+ 'gdrive'+ )+ const renamed = await mintHccControlToken(app, gateway, 'renamed-host')+ mockPoolQuery.mockReset()+ membership(mockPoolQuery, { agents: { [USER_1]: ['renamed-host'] } }, sql =>+ Promise.resolve(+ typeof sql === 'string' && sql.includes('FROM oauth_grants')+ ? { rows: grantRows, rowCount: grantRows.length }+ : { rows: [], rowCount: 0 }+ )+ )+ const logs = captureRequestLogs()+ try {+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 }, renamed)+ expect(res.status).toBe(200)+ expect(logs.warn).toHaveBeenCalledWith(+ expect.objectContaining({ event: 'context_id_mismatch', host: 'renamed-host' }),+ expect.any(String)+ )+ } finally {+ logs.restore()+ }})- it('404 no_grant when no row exists', async () => {+ // ── Rule 4: allowlist, then the CR ────────────────────────────────────────++ it('R4: missing, outside the allowlist, being deleted and disabled all answer the same 404 (I-2, I-5)', async () => {seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'nobody' })+ seedOauthServer(gateway, { name: 'foreign', grantScope: 'user' })+ seedOauthServer(gateway, { name: 'leaving', grantScope: 'user' })+ seedOauthServer(gateway, { name: 'off', grantScope: 'user', enabled: false })+ for (const name of ['ghost', 'leaving', 'off']) {+ await attachServerToContext(+ gateway as never,+ { name: HOST_CONTEXT, namespace: config.contextsNamespace },+ name+ )+ }+ gateway.markDeleting('mcpservers', 'leaving', MCP_NS)+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]++ for (const name of ['ghost', 'foreign', 'leaving', 'off']) {+ const res = await post({ mcpServerName: name, userId: USER_1 })+ expect(res.status, name).toBe(404)+ expect(res.text, name).toBe('{"error":"server_not_found"}')+ }+ expect(grantQueries()).toHaveLength(0)+ })++ it('R4b: the allowlist match is exact, like host-context-controller (no trim)', async () => {+ seedOauthServer(gateway, { name: 'drive', grantScope: 'user' })+ await attachServerToContext(+ gateway as never,+ { name: HOST_CONTEXT, namespace: config.contextsNamespace },+ ' drive '+ )+ const res = await post({ mcpServerName: 'drive', userId: USER_1 })expect(res.status).toBe(404)- expect(res.body.error).toBe('no_grant')+ expect(res.text).toBe('{"error":"server_not_found"}')})- it('404 server_not_found for an unknown server', async () => {- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'ghost', userId: 'user-1' })+ it('R4c: a server outside the allowlist is never read from the apiserver', async () => {+ seedOauthServer(gateway, { name: 'foreign', grantScope: 'user' })+ const reads = vi.spyOn(gateway, 'getResource')+ const res = await post({ mcpServerName: 'foreign', userId: USER_1 })expect(res.status).toBe(404)- expect(res.body.error).toBe('server_not_found')+ expect(reads.mock.calls.some(([plural]) => plural === 'mcpservers')).toBe(false)+ })++ it('R4: a transient error reading an allowlisted server → 503', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ gateway.failGetResource('mcpservers', { statusCode: 500 })+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(503)+ expect(res.text).toBe('{"error":"host_state_unavailable"}')})- it('400 not_oauth_server for a non-oauth server', async () => {+ // ── Rule 5 ────────────────────────────────────────────────────────────────++ it('R5: 400 not_oauth_server for a non-oauth server of the own Context', async () => {void gateway.createResource('mcpservers',{ metadata: { name: 'plain' }, spec: { auth: { type: 'none' } } },MCP_NS)- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'plain', userId: 'user-1' })+ const res = await post({ mcpServerName: 'plain', userId: USER_1 })expect(res.status).toBe(400)expect(res.body.error).toBe('not_oauth_server')})- it('context flavor: key uses the AUTHORITATIVE spec.contextRef, not the body; user_id NULL', async () => {- seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })- const future = new Date(Date.now() + 3600_000)- mockPoolQuery.mockResolvedValueOnce({- rows: [- {- ...nonExpiredUserGrantRow('', future),- grant_kind: 'shared',- user_id: null,- context_id: 'ctx-A',- bootstrapped_by_user_id: 'user-1',- },- ],- rowCount: 1,- })+ // ── Rule 6: context-scope owner ───────────────────────────────────────────- // Body omits contextId entirely — the server's contextRef is authoritative.- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'user-2' })+ it('context flavor: key uses the Host Context (= owner), not the body; user_id NULL', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: HOST_CONTEXT })+ grantRows = [sharedGrantRow(HOST_CONTEXT, new Date(Date.now() + 3600_000))]++ const res = await post({ mcpServerName: 'gdrive', userId: USER_NO_ACCESS })expect(res.status).toBe(200)- const grantQuery = mockPoolQuery.mock.calls.find(- ([sql]) =>- typeof sql === 'string' &&- sql.includes('FROM oauth_grants') &&- sql.includes("grant_kind = 'shared'")- )- // owner, ns, name, contextId(=contextRef), clientId — userId NOT a coordinate.+ const grantQuery = grantQueries().find(([sql]) => String(sql).includes("grant_kind = 'shared'"))expect(grantQuery?.[1]).toEqual(['mcpserver',MCP_NS,'gdrive',- 'ctx-A',+ HOST_CONTEXT,'google-drive',await liveUid(gateway, 'gdrive'),// Baked CR: the reader key carries its provider for unsealed legacy rows.@@ -280,73 +564,26 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {])})- // Guardian (T5): a caller with the scope must NOT be able to fetch another- // Context's shared token by asserting a foreign contextId in the body. The- // server's spec.contextRef is 'ctx-A'; a request naming 'ctx-B' is rejected- // BEFORE any grant lookup — the ctx-B token is never observable (T4).- it('rejects a cross-context body contextId with 400 context_mismatch and never queries the foreign grant', async () => {+ it('R6: a context server owned by another Context → 404 server_not_found + metric, no grant read (I-1)', async () => {+ // Before the binding, this request handed ctx-A's shared token to any Host.seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })+ grantRows = [sharedGrantRow('ctx-A', new Date(Date.now() + 3600_000))]+ const before = await deniedCount('context_ref_mismatch')- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'user-2', contextId: 'ctx-B' })-- expect(res.status).toBe(400)- expect(res.body.error).toBe('context_mismatch')- expect(res.body.token).toBeUndefined()- // No grant lookup ran at all — the foreign coordinate never reached the DB.- const grantQuery = mockPoolQuery.mock.calls.find(- ([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants')- )- expect(grantQuery).toBeUndefined()- })-- // Happy-negative for the context branch (U1 dispatch, U6 activation): when NO- // shared grant exists for the server's authoritative contextRef, the broker- // returns 404 no_grant — the same fail-closed outcome the user branch gives,- // driven through the REAL shared getOAuthGrant SQL (mockPoolQuery → 0 rows).- it('context flavor: 404 no_grant when no shared grant exists for spec.contextRef', async () => {- seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })- // Default mock already resolves { rows: [], rowCount: 0 } → getOAuthGrant null.- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'user-2' })+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })expect(res.status).toBe(404)- expect(res.body.error).toBe('no_grant')- expect(res.body.token).toBeUndefined()- // The lookup that ran was the SHARED coordinate keyed by contextRef, no userId.- const grantQuery = mockPoolQuery.mock.calls.find(- ([sql]) =>- typeof sql === 'string' &&- sql.includes('FROM oauth_grants') &&- sql.includes("grant_kind = 'shared'")- )- expect(grantQuery?.[1]).toEqual([- 'mcpserver',- MCP_NS,- 'gdrive',- 'ctx-A',- 'google-drive',- await liveUid(gateway, 'gdrive'),- // Baked CR: the reader key carries its provider for unsealed legacy rows.- 'google',- ])+ expect(res.text).toBe('{"error":"server_not_found"}')+ expect(grantQueries()).toHaveLength(0)+ expect(await deniedCount('context_ref_mismatch')).toBe(before + 1)})- // Fail-closed: a context-flavor server that is missing its CRD-required- // spec.contextRef must NOT resolve to any grant. The broker rejects with 400- // server_missing_context BEFORE any DB lookup (mini-spec 05 §2 — the shared- // key coordinate is unresolvable, so there is nothing safe to query).- it('context flavor: 400 server_missing_context when spec.contextRef is absent, no grant lookup', async () => {+ it('R6: a context server without contextRef → the same 404, no grant read', async () => {void gateway.createResource('mcpservers',{metadata: { name: 'no-ctx' },spec: {- // contextRef deliberately omitted.auth: { type: 'oauth' },oauth: {id: 'google-drive',@@ -359,51 +596,129 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {},MCP_NS)- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'no-ctx', userId: 'user-2' })+ const res = await post({ mcpServerName: 'no-ctx', userId: USER_1 })+ expect(res.status).toBe(404)+ expect(res.text).toBe('{"error":"server_not_found"}')+ expect(grantQueries()).toHaveLength(0)+ })- expect(res.status).toBe(400)- expect(res.body.error).toBe('server_missing_context')- const grantQuery = mockPoolQuery.mock.calls.find(- ([sql]) => typeof sql === 'string' && sql.includes('FROM oauth_grants')- )- expect(grantQuery).toBeUndefined()+ it('R6b: a body contextId is ignored — a foreign value neither denies nor redirects the key', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: HOST_CONTEXT })+ grantRows = [sharedGrantRow(HOST_CONTEXT, new Date(Date.now() + 3600_000))]+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1, contextId: 'ctx-B' })+ expect(res.status).toBe(200)+ expect(res.body.token).toBe('GDRIVE-ACCESS')+ const keys = grantQueries().map(([, values]) => (values as unknown[])[3])+ expect(keys).toEqual([HOST_CONTEXT])})- it('accepts a body contextId that matches spec.contextRef', async () => {- seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })+ it('context flavor: 404 no_grant when no shared grant exists for the Host Context', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: HOST_CONTEXT })+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(404)+ expect(res.body).toEqual({ error: 'no_grant' })+ })++ // ── Rule 7: the end user enters this Host ─────────────────────────────────++ it('200 {token,expiresAt} for a per-user grant, keyed by (mcpserver owner, userId)', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })const future = new Date(Date.now() + 3600_000)- mockPoolQuery.mockResolvedValueOnce({- rows: [- {- ...nonExpiredUserGrantRow('', future),- grant_kind: 'shared',- user_id: null,- context_id: 'ctx-A',- bootstrapped_by_user_id: 'user-1',- },- ],- rowCount: 1,- })- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'user-2', contextId: 'ctx-A' })+ grantRows = [nonExpiredUserGrantRow(USER_1, future)]++ const res = await post({ mcpServerName: 'gdrive', userId: USER_1, contextId: HOST_CONTEXT })+expect(res.status).toBe(200)expect(res.body.token).toBe('GDRIVE-ACCESS')+ expect(res.body.expiresAt).toBe(future.toISOString())+ const grantQuery = grantQueries().find(([sql]) => String(sql).includes("grant_kind = 'user'"))+ expect(grantQuery?.[1]).toEqual([+ 'mcpserver',+ MCP_NS,+ 'gdrive',+ USER_1,+ 'google-drive',+ await liveUid(gateway, 'gdrive'),+ // Baked CR: the reader key carries its provider for unsealed legacy rows.+ 'google',+ ])})- it('400 invalid_request for a malformed (non-k8s) server name, before any getResource', async () => {- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'Foo/Bar', userId: 'user-1' })+ it('404 no_grant when the user enters the Host but never connected', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(404)+ expect(res.body).toEqual({ error: 'no_grant' })+ })++ it('R7: a user who cannot enter the Host gets no_grant without any grant read (I-3)', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_NO_ACCESS, new Date(Date.now() + 3600_000))]+ const res = await post({ mcpServerName: 'gdrive', userId: USER_NO_ACCESS })+ expect(res.status).toBe(404)+ expect(res.text).toBe('{"error":"no_grant"}')+ expect(grantQueries()).toHaveLength(0)+ })++ it('R7: 400 invalid_request for a user server without userId', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ const res = await post({ mcpServerName: 'gdrive' })expect(res.status).toBe(400)expect(res.body.error).toBe('invalid_request')})+ it('R7f: a DB error reading Host access → 503 fixed body, no grant read', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]+ serveDb({ accessError: new Error('connection terminated') })+ const before = await deniedCount('unavailable')+ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+ expect(res.status).toBe(503)+ expect(res.text).toBe('{"error":"host_state_unavailable"}')+ expect(grantQueries()).toHaveLength(0)+ expect(await deniedCount('unavailable')).toBe(before + 1)+ })++ it('logs the denial with server and Host, never the userId', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ const logs = captureRequestLogs()+ try {+ await post({ mcpServerName: 'gdrive', userId: USER_NO_ACCESS })+ } finally {+ logs.restore()+ }+ const denial = logs.warn.mock.calls.find(+ ([fields]) => (fields as { event?: string }).event === 'mcp_oauth_broker_denied'+ )+ expect(denial?.[0]).toMatchObject({ reason: 'no_grant', host: HOST, mcpServerName: 'gdrive' })+ expect(JSON.stringify(logs.warn.mock.calls)).not.toContain(USER_NO_ACCESS)+ })++ it('no_grant by Host access logs at warn; a non-UUID channel sender only at debug', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ const before = await deniedCount('no_grant')+ const logs = captureRequestLogs()+ try {+ const entitledLooking = await post({ mcpServerName: 'gdrive', userId: USER_NO_ACCESS })+ const channelSender = await post({ mcpServerName: 'gdrive', userId: 'U024BE7LH' })+ expect(entitledLooking.text).toBe('{"error":"no_grant"}')+ expect(channelSender.text).toBe('{"error":"no_grant"}')+ } finally {+ logs.restore()+ }+ const denials = (calls: unknown[][]) =>+ calls+ .map(([fields]) => fields as { event?: string; reason?: string; cause?: string })+ .filter(fields => fields.event === 'mcp_oauth_broker_denied')+ expect(denials(logs.warn.mock.calls)).toEqual([+ expect.objectContaining({ reason: 'no_grant', cause: 'no_host_access' }),+ ])+ expect(denials(logs.debug.mock.calls)).toEqual([+ expect.objectContaining({ reason: 'no_grant', cause: 'non_uuid_user_id' }),+ ])+ expect(await deniedCount('no_grant')).toBe(before + 2)+ })+// Finding R1-H1: the broker is gated behind a kill-switch that defaults OFF,// so it cannot serve provider tokens in production until the U4 mcp-host// runtime lands. When disabled, a fully well-formed AND authorized request —@@ -414,45 +729,22 @@ describe('routes/mcp-oauth — POST /mcp-oauth/user-token (U1)', () => {it('OFF (default): a well-formed authorized request returns 404 not_found and never resolves a grant', async () => {config.mcpOauthBrokerEnabled = falseseedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })- // A grant that WOULD resolve to a 200 token if the endpoint served — so- // the 404 can only come from the gate, not from a missing grant.- const future = new Date(Date.now() + 3600_000)- mockPoolQuery.mockResolvedValueOnce({- rows: [nonExpiredUserGrantRow('user-1', future)],- rowCount: 1,- })-- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'user-1', contextId: 'ctx-9' })-- // Load-bearing (T4): assert the observable HTTP response, not an internal- // call count. This assertion fails against the pre-gate parent (which- // always serves → 200 with the seeded grant).+ grantRows = [nonExpiredUserGrantRow(USER_1, new Date(Date.now() + 3600_000))]++ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })+expect(res.status).toBe(404)expect(res.body.error).toBe('not_found')expect(res.body.token).toBeUndefined()- // Never reached grant resolution — no oauth_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)})it('ON: the same request resolves normally (behavior unchanged)', async () => {- config.mcpOauthBrokerEnabled = trueseedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })const future = new Date(Date.now() + 3600_000)- mockPoolQuery.mockResolvedValueOnce({- rows: [nonExpiredUserGrantRow('user-1', future)],- rowCount: 1,- })-- const res = await request(app)- .post('/api/v1/mcp-oauth/user-token')- .set('Authorization', `Bearer ${controlToken()}`)- .send({ mcpServerName: 'gdrive', userId: 'user-1', contextId: 'ctx-9' })+ grantRows = [nonExpiredUserGrantRow(USER_1, future)]++ const res = await post({ mcpServerName: 'gdrive', userId: USER_1 })expect(res.status).toBe(200)expect(res.body.token).toBe('GDRIVE-ACCESS')