Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(control-api): u5 reactive-consent oauth state binding + authorize-url mint
Diego Zacariasc60dc0709b8c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex de12042d3..7a69f5263 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.436",+ "version": "0.1.437","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.436",+ "version": "0.1.437","dependencies": {"@clerum/image-policy": "file:../packages/image-policy","@clerum/llm-providers": "file:../packages/llm-providers",diff --git a/control-api/package.json b/control-api/package.jsonindex 6c66376d8..9ea171700 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.436",+ "version": "0.1.437","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/oauth/authorizeUrlHelper.ts b/control-api/src/oauth/authorizeUrlHelper.tsindex 1d3e91fbd..6bf08af86 100644--- a/control-api/src/oauth/authorizeUrlHelper.ts+++ b/control-api/src/oauth/authorizeUrlHelper.ts@@ -1,4 +1,7 @@import {+ type McpServerOAuthReader,+ type McpServerOAuthSubject,+ type OAuthClientDecl,RecipeNotFoundError,type RecipeReader,type RecipeWithOAuthClients,@@ -7,51 +10,69 @@ import {} from './callback.js'import { computeCodeChallengeS256, deriveCodeVerifier } from './pkce.js'import { getOAuthProviderAdapter, isKnownOAuthProvider } from './providers.js'-import { signOAuthState } from './state.js'+import { type SignStateInput, signOAuthState } from './state.js'/**- * Build the provider authorize URL for an embed-initiated OAuth flow.+ * Build the provider authorize URL for an OAuth flow initiated on behalf of a+ * subject: a WorkflowRecipe (embed/admin Connect) or an OAuth McpServer (U5+ * reactive consent).*- * The recipe must declare the matching `oauthClientId` under- * `spec.oauthClients[]`. The recipe is read from K8s so we pick up the- * recipe-author-supplied scopes; the K8s Secret is read for the real- * client_id (the provider needs it in the authorize URL).+ * The subject must declare the matching `oauthClientId` (recipe:+ * `spec.oauthClients[]`; mcp-server: `spec.oauth.id`). The subject is read from+ * K8s so we pick up the author-supplied scopes; the K8s Secret is read for the+ * real client_id (the provider needs it in the authorize URL).*- * State is signed with the supplied secret and bound to- * (recipeNamespace, recipeName, userId, oauthClientId) — the callback- * endpoint re-verifies this on the provider redirect.+ * State is signed with the supplied secret and bound to the subject+ * (recipe: (ns, name, userId, oauthClientId); mcp: (mcpServerName, userId,+ * oauthClientId)) — the callback endpoint re-verifies this on the redirect.*- * Spec §9.9.+ * Spec §9.9 (recipe) · §U5 (mcp).*/-export interface BuildAuthorizeUrlInput {- recipeNamespace: string- recipeName: string+interface BuildAuthorizeUrlCommonInput {oauthClientId: string/*** Authenticated user. For `grantKind: 'user'` this is the end-user the grant- * will belong to (rpc-proxy decodes the cookie). For `grantKind: 'service'`- * this is the initiating admin — recorded in the state for audit only.+ * will belong to (rpc-proxy decodes the session). For `grantKind: 'service'`+ * this is the initiating admin — recorded in the state for audit only. For an+ * mcp subject it is the initiating user (per-user grant owner, or shared-grant+ * bootstrapper resolved on the callback).*/userId: string/*** [SEC-1] Which kind of grant this flow will mint. Required, non-defaulted:* the embed `/oauth/authorize-url` path MUST pass `'user'`, the admin connect- * route passes `'service'`. There is no fall-through default.+ * route passes `'service'`, the mcp path passes `'user'`. No fall-through.*/grantKind: 'user' | 'service'/*** True when this flow captures background (offline) consent. Only ever true* on the embed background opt-in; the callback sets the grant's `background`- * flag iff a refresh token is returned. Default false.+ * flag iff a refresh token is returned. Default false. (Never true for mcp.)*/background?: boolean/** Public callback URL the provider will redirect to. */redirectUri: string}+export type BuildAuthorizeUrlInput =+ | (BuildAuthorizeUrlCommonInput & {+ subjectKind?: 'recipe'+ recipeNamespace: string+ recipeName: string+ })+ | (BuildAuthorizeUrlCommonInput & {+ subjectKind: 'mcp'+ mcpServerName: string+ })+export interface BuildAuthorizeUrlDeps {recipeReader: RecipeReader+ /**+ * Resolver for OAuth McpServer subjects (U5). Required to build an mcp-subject+ * authorize URL; absent for pure recipe wiring.+ */+ mcpServerReader?: McpServerOAuthReadersecretReader: SecretReaderstateSecret: string}@@ -59,6 +80,8 @@ export interface BuildAuthorizeUrlDeps {export type BuildAuthorizeUrlResult =| { kind: 'ok'; authorizeUrl: string }| { kind: 'recipe_not_found' }+ /** mcp subject: the McpServer named in the request does not exist / is not OAuth. */+ | { kind: 'server_not_found' }| { kind: 'unknown_oauth_client' }| { kind: 'background_access_not_enabled' }| { kind: 'unsupported_provider'; provider: string }@@ -68,6 +91,36 @@ export async function buildAuthorizeUrl(input: BuildAuthorizeUrlInput,deps: BuildAuthorizeUrlDeps): Promise<BuildAuthorizeUrlResult> {+ if (input.subjectKind === 'mcp') {+ // ─── mcp subject (U5) ────────────────────────────────────────────────+ if (!deps.mcpServerReader) return { kind: 'server_not_found' }+ let subject: McpServerOAuthSubject | null+ try {+ subject = await deps.mcpServerReader.read(input.mcpServerName)+ } catch (err) {+ if (err instanceof RecipeNotFoundError) return { kind: 'server_not_found' }+ throw err+ }+ if (!subject) return { kind: 'server_not_found' }++ const decl = subject.decl+ if (decl.id !== input.oauthClientId) return { kind: 'unknown_oauth_client' }++ // The state binds the initiating user + the server; grant-scope routing is+ // resolved authoritatively on the callback, so the mcp state is per-user+ // shaped regardless of grantScope (context binding is authoritative via+ // spec.contextRef, not carried here).+ return mintAuthorizeUrl(decl, subject.namespace, input, deps, {+ subjectKind: 'mcp',+ mcpServerName: input.mcpServerName,+ userId: input.userId,+ oauthClientId: input.oauthClientId,+ grantKind: input.grantKind,+ background: input.background ?? false,+ })+ }++ // ─── recipe subject (unchanged) ──────────────────────────────────────────let recipe: RecipeWithOAuthClients | nulltry {recipe = await deps.recipeReader.read(input.recipeName, input.recipeNamespace)@@ -80,10 +133,33 @@ export async function buildAuthorizeUrl(const decl = recipe.spec?.oauthClients?.find(c => c.id === input.oauthClientId)if (!decl) return { kind: 'unknown_oauth_client' }+ return mintAuthorizeUrl(decl, input.recipeNamespace, input, deps, {+ recipeNamespace: input.recipeNamespace,+ recipeName: input.recipeName,+ userId: input.userId,+ oauthClientId: input.oauthClientId,+ grantKind: input.grantKind,+ background: input.background ?? false,+ })+}++/**+ * Shared tail for both subjects: background gate, provider check, client_id+ * Secret read, state signing (subject-specific `stateInput`), PKCE challenge,+ * and the provider authorize URL. Signing is the ONLY subject-specific input —+ * the recipe `stateInput` reproduces the pre-U5 signed shape byte-for-byte.+ */+async function mintAuthorizeUrl(+ decl: OAuthClientDecl,+ secretNamespace: string,+ input: BuildAuthorizeUrlInput,+ deps: BuildAuthorizeUrlDeps,+ stateInput: SignStateInput+): Promise<BuildAuthorizeUrlResult> {// [SEC-4] A service grant, or any user flow requesting background (offline)- // consent, may only be minted for a client the recipe author explicitly opted- // into background access. Fail closed when the flag is absent — including for- // recipes that predate the field.+ // consent, may only be minted for a client whose author explicitly opted into+ // background access. Fail closed when the flag is absent. For the mcp path+ // (grantKind 'user', background false) this is a no-op.if (decl.backgroundAccess !== true && (input.grantKind === 'service' || input.background)) {return { kind: 'background_access_not_enabled' }}@@ -95,7 +171,7 @@ export async function buildAuthorizeUrl(let clientIdSecret: Record<string, string>try {- clientIdSecret = await deps.secretReader.read(decl.clientIdRef.name, input.recipeNamespace)+ clientIdSecret = await deps.secretReader.read(decl.clientIdRef.name, secretNamespace)} catch (err) {if (err instanceof SecretNotFoundError) {return { kind: 'secret_missing', secret: decl.clientIdRef.name }@@ -104,20 +180,10 @@ export async function buildAuthorizeUrl(}const clientId = clientIdSecret[decl.clientIdRef.key]if (!clientId) {- return {- kind: 'secret_missing',- secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}`,- }+ return { kind: 'secret_missing', secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}` }}- const state = signOAuthState(deps.stateSecret, {- recipeNamespace: input.recipeNamespace,- recipeName: input.recipeName,- userId: input.userId,- oauthClientId: input.oauthClientId,- grantKind: input.grantKind,- background: input.background ?? false,- })+ const state = signOAuthState(deps.stateSecret, stateInput)// PKCE (DEC-1): derive the verifier deterministically from the signed state,// then send its S256 challenge. The callback re-derives the same verifier fromdiff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.tsindex db35b8de3..4b8057ea6 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -6,8 +6,9 @@ import {getOAuthProviderAdapter,isKnownOAuthProvider,} from './providers.js'+import type { OAuthMcpStateClaims } from './state.js'import { signOAuthState, verifyOAuthStateSignature } from './state.js'-import { setUserGrantBackground, upsertOAuthGrant } from './store.js'+import { bootstrapSharedOAuthGrant, setUserGrantBackground, upsertOAuthGrant } from './store.js'/*** End-to-end handler for the auth-code OAuth callback. Independent of Express@@ -64,6 +65,35 @@ export interface RecipeReader {*/export type OwnerDeclReader = RecipeReader+/**+ * An OAuth McpServer subject, resolved for the U5 callback / authorize-URL+ * paths. Unlike {@link OwnerDeclReader} (which flattens a server to the+ * owner-agnostic `oauthClients` shape for the refresh path), this carries the+ * extra routing the consent flow needs:+ * - `namespace` — the mcp-servers namespace the server + its Secrets live in;+ * also the grant owner coordinate. Kept on the subject so the pure callback+ * never imports config.+ * - `grantScope` — `'user'` → per-user grant `(server, userId)`;+ * `'context'` → shared grant `(server, contextRef)` (U6 governance).+ * - `contextRef` — the AUTHORITATIVE Context (`spec.contextRef`), the shared+ * grant coordinate. NEVER taken from the state or a body param.+ */+export interface McpServerOAuthSubject {+ namespace: string+ decl: OAuthClientDecl+ grantScope: 'user' | 'context'+ contextRef?: string+}++export interface McpServerOAuthReader {+ /**+ * Resolve an OAuth McpServer by name from the mcp-servers namespace. Returns+ * null when the server does not exist or is not a usable OAuth server, so+ * callers fail closed. May throw {@link RecipeNotFoundError} for a hard 404.+ */+ read(mcpServerName: string): Promise<McpServerOAuthSubject | null>+}+export class SecretNotFoundError extends Error {}export class RecipeNotFoundError extends Error {}@@ -87,6 +117,22 @@ export interface CallbackDeps {db: DbClientrecipeReader: RecipeReadersecretReader: SecretReader+ /**+ * Resolver for OAuth McpServer subjects (U5). Required to process an+ * mcp-subject state; when absent, an mcp state fails closed+ * (`server_not_found`). Recipe callbacks never touch it.+ */+ mcpServerReader?: McpServerOAuthReader+ /**+ * Resolve the Contexts a user is a member of (via `user_contexts`). Required+ * ONLY for the shared-identity mcp bootstrap (`grantScope='context'`): a+ * shared grant plants a team credential for everyone in the Context, so the+ * consenting user MUST be a member first. Injected so the pure callback stays+ * testable; the route wires the real `getUserContexts`. When absent on a+ * shared-context path, that path fails closed (`context_membership_denied`).+ * The per-user path never touches it (its key IS the user).+ */+ userContextsReader?: (userId: string) => Promise<{ contextIds: string[] }>/** Injectable for tests; defaults to globalThis.fetch in production wiring. */fetchFn: typeof fetch/** HMAC secret used to sign / verify state. */@@ -113,10 +159,32 @@ export type CallbackResult =* established.*/backgroundEnabled: boolean+ /**+ * Subject that consented. Absent (undefined) for the recipe subject — the+ * recipe deep-link is FROZEN and carries no `source`. Set to `'mcp'` for an+ * OAuth McpServer subject so the route appends `&source=mcp` to the return+ * deep-link (U5).+ */+ source?: 'mcp'}| { kind: 'invalid_state'; reason: string }| { kind: 'unknown_oauth_client' }| { kind: 'recipe_not_found' }+ /** mcp subject: the McpServer named in the signed state does not exist / is not OAuth. */+ | { kind: 'server_not_found' }+ /**+ * mcp subject with `grantScope='context'` but no authoritative `spec.contextRef`+ * — the shared grant coordinate is unresolvable, so there is nothing safe to+ * persist. Fail closed (mini-spec 05 §2).+ */+ | { kind: 'server_missing_context' }+ /**+ * mcp subject with `grantScope='context'` where the consenting (signed) user+ * is NOT a member of the server's Context. A shared grant lends a team-wide+ * credential, so a non-member must not be able to bootstrap it. Fail closed →+ * 403, no persist.+ */+ | { kind: 'context_membership_denied' }| { kind: 'secret_missing'; secret: string }| { kind: 'unsupported_provider'; provider: string }| { kind: 'provider_token_exchange_failed'; status: number; body: string }@@ -131,11 +199,11 @@ export async function handleOAuthCallback(deps: CallbackDeps): Promise<CallbackResult> {// ─── 1. Verify state signature, recover binding from the claims ───────- // The callback URL no longer carries (recipeNamespace, recipeName) — they are+ // The callback URL no longer carries the subject coordinates — they are// recovered from the signed, unforgeable state. The oauthClientId still rides// the stable URL path, so cross-check it against the claims for defence in- // depth. The recipe identity itself needs no such check: the HMAC guarantees- // it, and both authorize-url minters only ever sign sandbox-namespace states.+ // depth. The subject identity itself needs no such check: the HMAC guarantees+ // it, and every authorize-url minter only signs its own namespace's states.const verified = verifyOAuthStateSignature(deps.stateSecret, input.state)if (verified.kind !== 'ok') {return { kind: 'invalid_state', reason: verified.kind }@@ -144,6 +212,13 @@ export async function handleOAuthCallback(if (claims.oauthClientId !== input.oauthClientId) {return { kind: 'invalid_state', reason: 'binding_mismatch' }}++ // Dispatch by the signed subject. mcp subjects go to their own handler; the+ // recipe path below is unchanged (byte-identical grant persistence).+ if (claims.subjectKind === 'mcp') {+ return handleMcpOAuthCallback(claims, input, deps)+ }+const recipeNamespace = claims.recipeNamespaceconst recipeName = claims.recipeNameconst oauthClientId = claims.oauthClientId@@ -166,83 +241,10 @@ export async function handleOAuthCallback(const clientDecl = recipe.spec?.oauthClients?.find(c => c.id === oauthClientId)if (!clientDecl) return { kind: 'unknown_oauth_client' }- // ─── 3. Read clientId + clientSecret from K8s Secrets ─────────────────- let clientIdSecret: Record<string, string>- try {- clientIdSecret = await deps.secretReader.read(clientDecl.clientIdRef.name, recipeNamespace)- } catch (err) {- if (err instanceof SecretNotFoundError) {- return { kind: 'secret_missing', secret: clientDecl.clientIdRef.name }- }- throw err- }- const clientId = clientIdSecret[clientDecl.clientIdRef.key]- if (!clientId)- return {- kind: 'secret_missing',- secret: `${clientDecl.clientIdRef.name}/${clientDecl.clientIdRef.key}`,- }-- let clientSecretSecret: Record<string, string>- try {- clientSecretSecret = await deps.secretReader.read(- clientDecl.clientSecretRef.name,- recipeNamespace- )- } catch (err) {- if (err instanceof SecretNotFoundError) {- return { kind: 'secret_missing', secret: clientDecl.clientSecretRef.name }- }- throw err- }- const clientSecret = clientSecretSecret[clientDecl.clientSecretRef.key]- if (!clientSecret) {- return {- kind: 'secret_missing',- secret: `${clientDecl.clientSecretRef.name}/${clientDecl.clientSecretRef.key}`,- }- }-- // ─── 4. Exchange code with provider ───────────────────────────────────- const provider = clientDecl.provider- if (!isKnownOAuthProvider(provider)) {- return { kind: 'unsupported_provider', provider }- }- const adapter = getOAuthProviderAdapter(provider)- // PKCE (DEC-1): re-derive the verifier from the EXACT round-tripped state- // string — the same signed value the authorize URL derived its challenge from.- const codeVerifier = adapter.usesPkce- ? deriveCodeVerifier(deps.stateSecret, input.state)- : undefined- const tokenRequest = adapter.buildTokenRequest({- code: input.code,- clientId,- clientSecret,- redirectUri: input.redirectUri,- codeVerifier,- })-- let parsed: ParsedTokenResponse- try {- const response = await deps.fetchFn(tokenRequest.url, {- method: tokenRequest.method,- headers: tokenRequest.headers,- body: tokenRequest.body,- signal: AbortSignal.timeout(deps.tokenRequestTimeoutMs ?? 15_000),- })- if (!response.ok) {- const body = await safeReadText(response)- return {- kind: 'provider_token_exchange_failed',- status: response.status,- body,- }- }- const responseJson = await response.json()- parsed = adapter.parseTokenResponse(responseJson)- } catch (err) {- return { kind: 'provider_response_invalid', detail: (err as Error).message }- }+ // ─── 3-4. Read secrets + exchange code ────────────────────────────────+ const exchanged = await exchangeAuthCode(clientDecl, recipeNamespace, input, deps)+ if (exchanged.kind !== 'ok') return exchanged+ const { provider, parsed } = exchanged// ─── 5. Encrypt + persist ─────────────────────────────────────────────// A `service` grant is recipe-owned: no `userId` column. A `user` grant@@ -300,6 +302,187 @@ export async function handleOAuthCallback(return { kind: 'ok', provider, userId, grantKind, backgroundRequested, backgroundEnabled }}+/**+ * mcp-subject callback (U5). The signed state binds the initiating `userId` and+ * the `mcpServerName`; the server's OAuth declaration + grant-scope routing are+ * recovered fresh from the CR (authoritative), NOT from the state or any body.+ *+ * Persistence connects to the U1 store primitives (no reimplementation):+ * - `grantScope='user'` → `upsertOAuthGrant` `(mcpserver, ns, name, userId)`.+ * - `grantScope='context'` → `bootstrapSharedOAuthGrant` `(mcpserver, ns, name,+ * spec.contextRef)`, bootstrapper = the signed `userId` (first-consent wins;+ * U6 governance). The Context comes from the AUTHORITATIVE `spec.contextRef`,+ * never the state — so no context field is (or needs to be) bound into the+ * mcp state in v1.+ */+async function handleMcpOAuthCallback(+ claims: OAuthMcpStateClaims,+ input: CallbackInput,+ deps: CallbackDeps+): Promise<CallbackResult> {+ // Fail closed: an mcp state cannot be processed without an mcp reader wired.+ if (!deps.mcpServerReader) return { kind: 'server_not_found' }++ let subject: McpServerOAuthSubject | null+ try {+ subject = await deps.mcpServerReader.read(claims.mcpServerName)+ } catch (err) {+ if (err instanceof RecipeNotFoundError) return { kind: 'server_not_found' }+ throw err+ }+ if (!subject) return { kind: 'server_not_found' }++ // Defence in depth: the resolved server's declared oauthClient must match the+ // one bound in the (already-cross-checked) signed state + callback path.+ if (subject.decl.id !== input.oauthClientId) {+ return { kind: 'invalid_state', reason: 'binding_mismatch' }+ }++ const exchanged = await exchangeAuthCode(subject.decl, subject.namespace, input, deps)+ if (exchanged.kind !== 'ok') return exchanged+ const { provider, parsed } = exchanged++ if (subject.grantScope === 'context') {+ // Shared identity — the coordinate is the server's authoritative contextRef.+ // Without it there is nothing safe to key the grant on: fail closed.+ if (!subject.contextRef) return { kind: 'server_missing_context' }+ // Defence in depth: a shared grant lends a team-wide credential to every+ // member of the Context, so the consenting (signed) user must be a member+ // of that Context before we let them bootstrap it. Fail closed when the+ // membership reader is unwired or the user is not a member — NEVER persist.+ if (!deps.userContextsReader) return { kind: 'context_membership_denied' }+ const { contextIds } = await deps.userContextsReader(claims.userId)+ if (!contextIds.includes(subject.contextRef)) {+ return { kind: 'context_membership_denied' }+ }+ await bootstrapSharedOAuthGrant(deps.db, deps.encryptionKey, {+ ownerKind: 'mcpserver',+ recipeNamespace: subject.namespace,+ recipeName: claims.mcpServerName,+ contextId: subject.contextRef,+ oauthClientId: input.oauthClientId,+ // Bootstrapper = the signed initiator. Audit-only, first-wins on conflict.+ bootstrappedByUserId: claims.userId,+ provider,+ accessToken: parsed.accessToken,+ refreshToken: parsed.refreshToken,+ accessTokenExpiresInSec: parsed.expiresIn,+ })+ } else {+ await upsertOAuthGrant(deps.db, deps.encryptionKey, {+ grantKind: 'user',+ ownerKind: 'mcpserver',+ recipeNamespace: subject.namespace,+ recipeName: claims.mcpServerName,+ userId: claims.userId,+ oauthClientId: input.oauthClientId,+ provider,+ accessToken: parsed.accessToken,+ refreshToken: parsed.refreshToken,+ accessTokenExpiresInSec: parsed.expiresIn,+ })+ }++ return {+ kind: 'ok',+ provider,+ userId: claims.userId,+ grantKind: claims.grantKind,+ // mcp interactive consent never captures background; the broker resolves+ // tokens JIT against a live session.+ backgroundRequested: false,+ backgroundEnabled: false,+ source: 'mcp',+ }+}++type ExchangeAuthCodeResult =+ | { kind: 'ok'; provider: OAuthProvider; parsed: ParsedTokenResponse }+ | { kind: 'unknown_oauth_client' }+ | { kind: 'secret_missing'; secret: string }+ | { kind: 'unsupported_provider'; provider: string }+ | { kind: 'provider_token_exchange_failed'; status: number; body: string }+ | { kind: 'provider_response_invalid'; detail: string }++/**+ * Read the (clientId, clientSecret) Secrets for a declaration, then exchange the+ * auth code with the provider. Shared verbatim by the recipe and mcp callbacks+ * so the token-exchange rule lives once (D4). The recipe path's observable+ * result kinds and ordering are unchanged.+ */+async function exchangeAuthCode(+ decl: OAuthClientDecl,+ secretNamespace: string,+ input: CallbackInput,+ deps: CallbackDeps+): Promise<ExchangeAuthCodeResult> {+ let clientIdSecret: Record<string, string>+ try {+ clientIdSecret = await deps.secretReader.read(decl.clientIdRef.name, secretNamespace)+ } catch (err) {+ if (err instanceof SecretNotFoundError) {+ return { kind: 'secret_missing', secret: decl.clientIdRef.name }+ }+ throw err+ }+ const clientId = clientIdSecret[decl.clientIdRef.key]+ if (!clientId) {+ return { kind: 'secret_missing', secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}` }+ }++ let clientSecretSecret: Record<string, string>+ try {+ clientSecretSecret = await deps.secretReader.read(decl.clientSecretRef.name, secretNamespace)+ } catch (err) {+ if (err instanceof SecretNotFoundError) {+ return { kind: 'secret_missing', secret: decl.clientSecretRef.name }+ }+ throw err+ }+ const clientSecret = clientSecretSecret[decl.clientSecretRef.key]+ if (!clientSecret) {+ return {+ kind: 'secret_missing',+ secret: `${decl.clientSecretRef.name}/${decl.clientSecretRef.key}`,+ }+ }++ const provider = decl.provider+ if (!isKnownOAuthProvider(provider)) {+ return { kind: 'unsupported_provider', provider }+ }+ const adapter = getOAuthProviderAdapter(provider)+ // PKCE (DEC-1): re-derive the verifier from the EXACT round-tripped state+ // string — the same signed value the authorize URL derived its challenge from.+ const codeVerifier = adapter.usesPkce+ ? deriveCodeVerifier(deps.stateSecret, input.state)+ : undefined+ const tokenRequest = adapter.buildTokenRequest({+ code: input.code,+ clientId,+ clientSecret,+ redirectUri: input.redirectUri,+ codeVerifier,+ })++ try {+ const response = await deps.fetchFn(tokenRequest.url, {+ method: tokenRequest.method,+ headers: tokenRequest.headers,+ body: tokenRequest.body,+ signal: AbortSignal.timeout(deps.tokenRequestTimeoutMs ?? 15_000),+ })+ if (!response.ok) {+ const body = await safeReadText(response)+ return { kind: 'provider_token_exchange_failed', status: response.status, body }+ }+ const responseJson = await response.json()+ return { kind: 'ok', provider, parsed: adapter.parseTokenResponse(responseJson) }+ } catch (err) {+ return { kind: 'provider_response_invalid', detail: (err as Error).message }+ }+}+// ─── helpers ──────────────────────────────────────────────────────────────async function safeReadText(response: Response): Promise<string> {diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.tsindex 1c379d656..4047036a0 100644--- a/control-api/src/oauth/mcpServerOAuthSpec.ts+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts@@ -55,3 +55,69 @@ export function resolveServerOAuth(server: McpServerOAuthSpecInput): ResolvedSer: undefinedreturn { oauthClientId: oauth.id, grantScope, contextRef }}++/**+ * The `spec.oauth` declaration in the `oauthClients[]`-compatible shape the+ * consent flow (U5: authorize-URL mint + callback) consumes, plus the grant+ * routing. Structurally assignable to `OAuthClientDecl` (`oauth/callback.ts`) so+ * the same broker/refresh machinery stays owner-agnostic.+ */+export interface ResolvedServerOAuthSubject {+ decl: {+ id: string+ provider: string+ clientIdRef: { name: string; key: string }+ clientSecretRef: { name: string; key: string }+ scopes?: string[]+ backgroundAccess?: boolean+ }+ grantScope: GrantScope+ /** Authoritative Context (spec.contextRef); undefined if absent. */+ contextRef?: string+}++/**+ * Resolve a McpServer's full OAuth subject (decl + grant routing) for the U5+ * consent flow. Returns null when the server carries no usable OAuth+ * declaration (missing id/provider/clientIdRef/clientSecretRef) so callers fail+ * closed. Same field-reading rule as {@link resolveServerOAuth} — kept here so+ * the authorize-URL minter and the callback never drift (D4).+ */+export function resolveServerOAuthSubject(+ server: McpServerOAuthSpecInput+): ResolvedServerOAuthSubject | null {+ const oauth = server.spec?.oauth+ if (!oauth || typeof oauth.id !== 'string' || oauth.id.length === 0) return null+ if (typeof oauth.provider !== 'string' || oauth.provider.length === 0) return null+ const clientIdRef = oauth.clientIdRef+ const clientSecretRef = oauth.clientSecretRef+ if (+ !clientIdRef ||+ typeof clientIdRef.name !== 'string' ||+ typeof clientIdRef.key !== 'string' ||+ !clientSecretRef ||+ typeof clientSecretRef.name !== 'string' ||+ typeof clientSecretRef.key !== 'string'+ ) {+ return null+ }+ const grantScope: GrantScope = oauth.grantScope === 'context' ? 'context' : 'user'+ const contextRef =+ typeof server.spec?.contextRef === 'string' && server.spec.contextRef.length > 0+ ? server.spec.contextRef+ : undefined+ return {+ decl: {+ id: oauth.id,+ provider: oauth.provider,+ clientIdRef: { name: clientIdRef.name, key: clientIdRef.key },+ clientSecretRef: { name: clientSecretRef.name, key: clientSecretRef.key },+ scopes: Array.isArray(oauth.scopes)+ ? oauth.scopes.filter((s): s is string => typeof s === 'string')+ : undefined,+ backgroundAccess: oauth.backgroundAccess === true,+ },+ grantScope,+ contextRef,+ }+}diff --git a/control-api/src/oauth/state.ts b/control-api/src/oauth/state.tsindex 5c36dca05..f72249090 100644--- a/control-api/src/oauth/state.ts+++ b/control-api/src/oauth/state.ts@@ -4,18 +4,33 @@ import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto'* State binding for an OAuth callback. The state value carried in the* provider redirect chain is HMAC-signed by control-api at authorize-URL* issuance, then re-verified on the callback. The signed binding glues the- * callback to a specific (recipe, user, oauthClientId) — a malicious recipe- * cannot replay another recipe's state and claim the resulting tokens.+ * callback to a specific subject + (user, oauthClientId) — a malicious caller+ * cannot replay another subject's state and claim the resulting tokens.*- * Spec §9.9 / Decision 20.+ * The subject is one of two kinds:+ * - a WorkflowRecipe (the historical embed/admin Connect flow), OR+ * - an OAuth McpServer (U5, reactive consent for mcp-servers).+ *+ * The recipe subject wire format is FROZEN: a recipe state carries NO+ * `subjectKind` discriminator and NO mcp fields, so an existing recipe state+ * serializes / signs byte-for-byte identically to before U5. The mcp subject is+ * strictly additive — it carries `subjectKind:'mcp'` + `mcpServerName`. Anything+ * that is neither an unmarked recipe nor a well-formed mcp subject fails closed+ * (see {@link decodePayload}): a state marked `mcp` with a missing+ * `mcpServerName`, or an unrecognized `subjectKind`, is rejected rather than+ * silently reinterpreted as a recipe.+ *+ * Spec §9.9 / Decision 20 (recipe) · §U5 (mcp).*/-export interface OAuthStateClaims {- recipeNamespace: string- recipeName: string++/** Fields common to every subject. */+interface OAuthStateCommonClaims {userId: stringoauthClientId: string/**- * `user` — embed Connect flow, grant owned by `userId`.+ * `user` — embed/mcp Connect flow, grant owned by `userId` (or, for a+ * context-identity mcp-server, bootstrapped by `userId` — resolved on the+ * callback from the server's authoritative `spec.contextRef`).* `service` — admin "connect for the recipe" flow (Path B). `userId` is the* initiating admin, recorded for audit only and NOT written to the grant.*/@@ -28,6 +43,24 @@ export interface OAuthStateClaims {nonce: string}+/**+ * Recipe subject — the FROZEN legacy shape. No `subjectKind` field is present on+ * the wire; its absence IS the discriminator.+ */+export interface OAuthRecipeStateClaims extends OAuthStateCommonClaims {+ subjectKind?: undefined+ recipeNamespace: string+ recipeName: string+}++/** OAuth McpServer subject (U5) — additive, `subjectKind:'mcp'`. */+export interface OAuthMcpStateClaims extends OAuthStateCommonClaims {+ subjectKind: 'mcp'+ mcpServerName: string+}++export type OAuthStateClaims = OAuthRecipeStateClaims | OAuthMcpStateClaims+const STATE_VERSION = 'v1'const STATE_TTL_SECONDS = 600 // 10 min — covers slow user OAuth flow but no longerconst NONCE_BYTES = 16@@ -37,6 +70,10 @@ const NONCE_BYTES = 16* URL-path-derived and cookie/peek-derived values. `grantKind` is deliberately* NOT part of the binding — it is a property of the signed state itself, with* no independent source to check it against.+ *+ * Only the recipe subject carries an external binding to re-check; the mcp+ * subject's identity is recovered from the unforgeable signed claims (there is+ * no recipe (ns, name) in the mcp callback path).*/export interface OAuthStateBinding {recipeNamespace: string@@ -45,10 +82,26 @@ export interface OAuthStateBinding {oauthClientId: string}-export type SignStateInput = OAuthStateBinding & {- grantKind: 'user' | 'service'- background: boolean-}+export type SignStateInput =+ | {+ /** Recipe subject (default). Omit `subjectKind` or pass `'recipe'`. */+ subjectKind?: 'recipe'+ recipeNamespace: string+ recipeName: string+ userId: string+ oauthClientId: string+ grantKind: 'user' | 'service'+ background: boolean+ }+ | {+ /** OAuth McpServer subject (U5). */+ subjectKind: 'mcp'+ mcpServerName: string+ userId: string+ oauthClientId: string+ grantKind: 'user' | 'service'+ background: boolean+ }/*** Sign a fresh state value. Caller embeds the returned string in the@@ -59,15 +112,35 @@ export function signOAuthState(secret: string, input: SignStateInput): string {throw new Error('signOAuthState: secret must be at least 32 characters')}const nonce = randomBytes(NONCE_BYTES).toString('base64url')- const claims: OAuthStateClaims = {- recipeNamespace: input.recipeNamespace,- recipeName: input.recipeName,- userId: input.userId,- oauthClientId: input.oauthClientId,- grantKind: input.grantKind,- background: input.background,- expiresAt: Math.floor(Date.now() / 1000) + STATE_TTL_SECONDS,- nonce,+ const expiresAt = Math.floor(Date.now() / 1000) + STATE_TTL_SECONDS++ let claims: OAuthStateClaims+ if (input.subjectKind === 'mcp') {+ // Additive mcp subject — carries the discriminator + mcpServerName.+ claims = {+ subjectKind: 'mcp',+ mcpServerName: input.mcpServerName,+ userId: input.userId,+ oauthClientId: input.oauthClientId,+ grantKind: input.grantKind,+ background: input.background,+ expiresAt,+ nonce,+ }+ } else {+ // FROZEN recipe subject — this object literal (field set + order) MUST stay+ // byte-for-byte identical to the pre-U5 shape. No `subjectKind`, no mcp+ // fields. The golden test in oauth.state.test.ts pins this.+ claims = {+ recipeNamespace: input.recipeNamespace,+ recipeName: input.recipeName,+ userId: input.userId,+ oauthClientId: input.oauthClientId,+ grantKind: input.grantKind,+ background: input.background,+ expiresAt,+ nonce,+ }}const payload = encodePayload(claims)const signature = computeSignature(secret, payload)@@ -86,11 +159,11 @@ export type VerifyOAuthStateResult =* Verify a state value's version, signature, and expiry, returning the parsed* claims on success. Unlike {@link verifyOAuthState}, this asserts NO external* binding — use it when the callback URL no longer carries the- * (recipeNamespace, recipeName) in its path and the recipe identity is recovered- * from the signed claims instead. That is safe because the HMAC signature makes- * the payload unforgeable. Callers that still hold an out-of-band value (e.g. the- * oauthClientId in the callback path) SHOULD cross-check it against the returned- * claims for defence in depth.+ * (recipeNamespace, recipeName) in its path and the subject identity is+ * recovered from the signed claims instead. That is safe because the HMAC+ * signature makes the payload unforgeable. Callers that still hold an+ * out-of-band value (e.g. the oauthClientId in the callback path) SHOULD+ * cross-check it against the returned claims for defence in depth.*/export function verifyOAuthStateSignature(secret: string, state: string): VerifyOAuthStateResult {const parts = state.split('.')@@ -124,6 +197,11 @@ export function verifyOAuthStateSignature(secret: string, state: string): Verify* The caller MUST also assert binding to the URL-path-derived* (recipeNamespace, recipeName, oauthClientId) and to the cookie-derived* userId — pass them via `expected` for an inline binding check.+ *+ * This binding check is RECIPE-ONLY: an mcp-subject state carries no recipe+ * (ns, name) to bind against, so it fails closed here (`binding_mismatch`).+ * The mcp callback path uses {@link verifyOAuthStateSignature} + a claims-side+ * cross-check instead.*/export function verifyOAuthState(secret: string,@@ -134,6 +212,12 @@ export function verifyOAuthState(if (verified.kind !== 'ok') return verifiedconst { claims } = verified+ // Fail closed: this external-binding verifier only understands recipe+ // subjects. An mcp subject has no recipe coordinates to re-assert.+ if (claims.subjectKind === 'mcp') {+ return { kind: 'binding_mismatch', reason: 'subjectKind' }+ }+if (claims.recipeNamespace !== expected.recipeNamespace) {return { kind: 'binding_mismatch', reason: 'recipeNamespace' }}@@ -159,8 +243,6 @@ function decodePayload(payload: string): OAuthStateClaims {if (typeof obj !== 'object' ||obj === null ||- typeof obj.recipeNamespace !== 'string' ||- typeof obj.recipeName !== 'string' ||typeof obj.userId !== 'string' ||typeof obj.oauthClientId !== 'string' ||(obj.grantKind !== 'user' && obj.grantKind !== 'service') ||@@ -169,7 +251,35 @@ function decodePayload(payload: string): OAuthStateClaims {) {throw new Error('decodePayload: malformed claims')}- return { ...obj, background: obj.background === true } as OAuthStateClaims+ const common: OAuthStateCommonClaims = {+ userId: obj.userId,+ oauthClientId: obj.oauthClientId,+ grantKind: obj.grantKind,+ background: obj.background === true,+ expiresAt: obj.expiresAt,+ nonce: obj.nonce,+ }++ // mcp subject — requires a well-formed mcpServerName. Fail closed otherwise.+ if (obj.subjectKind === 'mcp') {+ if (typeof obj.mcpServerName !== 'string' || obj.mcpServerName.length === 0) {+ throw new Error('decodePayload: malformed mcp claims')+ }+ return { subjectKind: 'mcp', mcpServerName: obj.mcpServerName, ...common }+ }++ // Recipe subject — the ONLY shape allowed to omit `subjectKind`. Requires the+ // recipe coordinates.+ if (obj.subjectKind === undefined) {+ if (typeof obj.recipeNamespace !== 'string' || typeof obj.recipeName !== 'string') {+ throw new Error('decodePayload: malformed recipe claims')+ }+ return { recipeNamespace: obj.recipeNamespace, recipeName: obj.recipeName, ...common }+ }++ // Any other `subjectKind` value is an unknown subject — fail closed rather+ // than defaulting to recipe.+ throw new Error('decodePayload: unknown subjectKind')}function computeSignature(secret: string, payload: string): string {diff --git a/control-api/src/routes/external/oauthCallback.ts b/control-api/src/routes/external/oauthCallback.tsindex 57e7f19cb..e43f11a95 100644--- a/control-api/src/routes/external/oauthCallback.ts+++ b/control-api/src/routes/external/oauthCallback.ts@@ -3,6 +3,8 @@ import { config } from '../../config.js'import { pool } from '../../db.js'import { K8sGateway } from '../../k8s.js'import {+ type McpServerOAuthReader,+ type McpServerOAuthSubject,RecipeNotFoundError,type RecipeReader,type RecipeWithOAuthClients,@@ -12,6 +14,11 @@ import {} from '../../oauth/callback.js'import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'import { integrationNotConfigured, isSecretNotFound } from '../../oauth/integrationNotConfigured.js'+import {+ type McpServerOAuthSpecInput,+ resolveServerOAuthSubject,+} from '../../oauth/mcpServerOAuthSpec.js'+import { getUserContexts } from '../../services/directory/index.js'import { K8sNotFoundError } from '../../services/resourceService.js'/**@@ -63,6 +70,30 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {},}+ // U5: resolve an OAuth McpServer subject when the signed state carries+ // `subjectKind:'mcp'`. Reads the CR from the mcp-servers namespace (the+ // authoritative source of oauthClientId / grantScope / contextRef — never the+ // state) and surfaces the namespace so grant persistence + Secret reads stay+ // pinned to it.+ const mcpServerReader: McpServerOAuthReader = {+ async read(mcpServerName): Promise<McpServerOAuthSubject | null> {+ let server: McpServerOAuthSpecInput+ try {+ server = (await gateway.getResource(+ 'mcpservers',+ mcpServerName,+ config.mcpServersNamespace+ )) as McpServerOAuthSpecInput+ } catch (err) {+ if (err instanceof K8sNotFoundError) return null+ throw err+ }+ const resolved = resolveServerOAuthSubject(server)+ if (!resolved) return null+ return { namespace: config.mcpServersNamespace, ...resolved }+ },+ }+// Stable callback path: only the oauthClientId rides the URL (one registered// redirect URI per provider client). The recipe (namespace, name) is recovered// from the signed state inside handleOAuthCallback, so the URI no longer churns@@ -87,6 +118,10 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {db: { query: (text, values) => pool.query(text, values) },recipeReader,secretReader,+ mcpServerReader,+ // Shared-identity mcp bootstrap requires the consenting user to be a+ // member of the server's Context (defence in depth).+ userContextsReader: getUserContexts,fetchFn: (input, init) => fetch(input, init),stateSecret: config.oauthStateHmacSecret,encryptionKey,@@ -102,6 +137,7 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {renderSuccessHtml(result.provider, oauthClientId, {backgroundRequested: result.backgroundRequested,backgroundEnabled: result.backgroundEnabled,+ source: result.source,}))case 'invalid_state':@@ -110,6 +146,12 @@ export function createOAuthCallbackRouter(gateway: K8sGateway): Router {return res.status(400).json({ error: 'unknown_oauth_client' })case 'recipe_not_found':return res.status(404).json({ error: 'recipe_not_found' })+ case 'server_not_found':+ return res.status(404).json({ error: 'server_not_found' })+ case 'server_missing_context':+ return res.status(400).json({ error: 'server_missing_context' })+ case 'context_membership_denied':+ return res.status(403).json({ error: 'context_membership_denied' })case 'secret_missing':return res.status(503).json(integrationNotConfigured(oauthClientId, result.secret))case 'unsupported_provider':@@ -154,16 +196,22 @@ export function buildPublicCallbackUrl(export function renderSuccessHtml(provider: string,oauthClientId: string,- opts?: { backgroundRequested?: boolean; backgroundEnabled?: boolean }+ opts?: { backgroundRequested?: boolean; backgroundEnabled?: boolean; source?: 'mcp' }): string {// The user's browser hits this page on the platform's origin, not inside// the embed. Spec §9.9 — bounce to `clerum://oauth-completed?…` so the- // desktop app's open-url handler dispatches the envelope into the active- // sandbox-ui embed (recipe JS subscribes via `clerum.onOauthCompleted`).+ // desktop app's open-url handler dispatches the envelope. The RECIPE deep-link+ // is FROZEN: `clientId` + `provider` only, no `source`. For an mcp subject+ // (U5) we append `&source=mcp` on the SAME `oauth-completed` host so the+ // desktop dispatcher routes it to the task resume instead of the embed. The+ // clientId is built unconditionally either way (it never depends on `source`).const safeProvider = String(provider).replace(/[^a-z0-9-]/gi, '')const deepLink = new URL('clerum://oauth-completed')deepLink.searchParams.set('clientId', oauthClientId)deepLink.searchParams.set('provider', safeProvider)+ if (opts?.source === 'mcp') {+ deepLink.searchParams.set('source', 'mcp')+ }const deepLinkHref = htmlAttrEscape(deepLink.toString())// JSON.stringify gives valid JS string literal; `<` → `<` blocks// any chance of `</script>` injection if the URL ever carried weird input.diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.tsindex 444782d9b..9cbef863e 100644--- a/control-api/src/routes/internal/oauth.ts+++ b/control-api/src/routes/internal/oauth.ts@@ -5,6 +5,8 @@ import { K8sGateway } from '../../k8s.js'import { requireInternalService } from '../../middleware/internalServiceAuth.js'import { buildAuthorizeUrl } from '../../oauth/authorizeUrlHelper.js'import {+ type McpServerOAuthReader,+ type McpServerOAuthSubject,RecipeNotFoundError,type RecipeReader,type RecipeWithOAuthClients,@@ -13,9 +15,27 @@ import {} from '../../oauth/callback.js'import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'import { integrationNotConfigured, isSecretNotFound } from '../../oauth/integrationNotConfigured.js'+import {+ type McpServerOAuthSpecInput,+ resolveServerOAuthSubject,+} from '../../oauth/mcpServerOAuthSpec.js'import { deleteOAuthGrant } from '../../oauth/store.js'import { getAccessToken } from '../../oauth/tokenHelper.js'import { K8sNotFoundError } from '../../services/resourceService.js'+import { buildPublicCallbackUrl } from '../external/oauthCallback.js'++// DNS-1123 subdomain — the shape a k8s resource name takes. Reject anything else+// up front so a malformed `mcpServerName` becomes a 400 rather than surfacing a+// non-404 apiserver error as a 500. (Mirrors routes/mcpOauth.ts.)+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)+}++/** McpServer shape used to read `spec.auth.type` for the OAuth gate. */+interface McpServerAuthResource extends McpServerOAuthSpecInput {+ spec?: McpServerOAuthSpecInput['spec'] & { auth?: { type?: unknown } }+}/*** Internal OAuth helper endpoints. rpc-proxy fronts these from the@@ -66,12 +86,161 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {},}+ // U5: resolver for OAuth McpServer subjects. Reads the CR from the mcp-servers+ // namespace (authoritative for oauthClientId / grantScope / contextRef).+ const mcpServerReader: McpServerOAuthReader = {+ async read(mcpServerName): Promise<McpServerOAuthSubject | null> {+ let server: McpServerAuthResource+ try {+ server = (await gateway.getResource(+ 'mcpservers',+ mcpServerName,+ config.mcpServersNamespace+ )) as McpServerAuthResource+ } catch (err) {+ if (err instanceof K8sNotFoundError) return null+ throw err+ }+ const resolved = resolveServerOAuthSubject(server)+ if (!resolved) return null+ return { namespace: config.mcpServersNamespace, ...resolved }+ },+ }++ // ── U5: mint a fresh authorize-URL for an OAuth mcp-server, on click ──────+ //+ // rpc-proxy fronts this from the desktop "Connect <server>" surface. The+ // `userId` is derived by rpc-proxy from the session `auth.sub` and forwarded+ // over this mutually-authenticated seam (requireInternalService('rpc-proxy')),+ // exactly like the sandbox-ui endpoints above — it is NOT a client-controlled+ // param on any end-user surface (invariant §1.1.3, U1 must-fix note). Minting+ // fresh per click keeps the state's 600s TTL counting from the user's click+ // and binds the state to that initiator.+ //+ // `oauthClientId` + `grantScope` + the Context come from the McpServer CR+ // (authoritative), never the body. A body `contextId` for a context-identity+ // server is only cross-checked against `spec.contextRef` (defence in depth).+ router.post(+ '/internal/mcp-oauth/authorize-url',+ requireInternalService('rpc-proxy'),+ async (req, res, next) => {+ try {+ const { mcpServerName, userId, contextId } = (req.body ?? {}) as {+ mcpServerName?: unknown+ userId?: unknown+ contextId?: unknown+ }+ if (typeof mcpServerName !== 'string' || !isValidK8sName(mcpServerName)) {+ return res.status(400).json({ error: 'invalid_request' })+ }+ if (typeof userId !== 'string' || userId.length === 0) {+ return res.status(400).json({ error: 'invalid_request' })+ }+ if (contextId !== undefined && typeof contextId !== 'string') {+ return res.status(400).json({ error: 'invalid_request' })+ }++ // Read the server to derive oauthClientId + grant routing. Never trust+ // the body for these.+ let server: McpServerAuthResource+ try {+ server = (await gateway.getResource(+ 'mcpservers',+ mcpServerName,+ config.mcpServersNamespace+ )) as McpServerAuthResource+ } catch (err) {+ if (err instanceof K8sNotFoundError) {+ return res.status(404).json({ error: 'server_not_found' })+ }+ throw err+ }++ const authType = server?.spec?.auth?.type+ const resolved = resolveServerOAuthSubject(server)+ if (authType !== 'oauth' || !resolved) {+ return res.status(400).json({ error: 'not_oauth_server' })+ }++ // Context-identity servers: the AUTHORITATIVE Context is spec.contextRef.+ // A body contextId, if present, must match it (cross-context guard).+ if (resolved.grantScope === 'context') {+ if (!resolved.contextRef) {+ return res.status(400).json({ error: 'server_missing_context' })+ }+ if (typeof contextId === 'string' && contextId !== resolved.contextRef) {+ return res.status(400).json({ error: 'context_mismatch' })+ }+ }++ const oauthClientId = resolved.decl.id+ const redirectUri = buildPublicCallbackUrl(req, oauthClientId, config.oauthCallbackBaseUrl)++ const result = await buildAuthorizeUrl(+ {+ subjectKind: 'mcp',+ mcpServerName,+ oauthClientId,+ // Initiator forwarded from the session by rpc-proxy (see note above).+ userId,+ // mcp reactive consent mints per-user-shaped states; grant-scope+ // routing (user vs shared) is resolved authoritatively on the+ // callback from spec.contextRef.+ grantKind: 'user',+ background: false,+ redirectUri,+ },+ {+ recipeReader,+ mcpServerReader,+ secretReader,+ stateSecret: config.oauthStateHmacSecret,+ }+ )++ switch (result.kind) {+ case 'ok':+ req.log?.info(+ {+ event: 'mcp_oauth_authorize_url_minted',+ mcpServerName,+ grantScope: resolved.grantScope,+ oauthClientId,+ },+ 'mcp oauth authorize url minted'+ )+ return res.status(200).json({ authorizeUrl: result.authorizeUrl })+ case 'server_not_found':+ case 'recipe_not_found':+ return res.status(404).json({ error: 'server_not_found' })+ case 'unknown_oauth_client':+ case 'background_access_not_enabled':+ return res.status(400).json({ error: 'unknown_oauth_client' })+ case 'unsupported_provider':+ return res+ .status(400)+ .json({ error: 'unsupported_provider', provider: result.provider })+ case 'secret_missing':+ return res.status(503).json(integrationNotConfigured(oauthClientId, result.secret))+ default:+ // Exhaustiveness guard: a future BuildAuthorizeUrlResult kind must+ // never leave the request hanging without a response.+ result satisfies never+ return res.status(500).json({ error: 'internal_error' })+ }+ } catch (err) {+ next(err)+ }+ }+ )+router.post('/internal/sandbox-ui/oauth/authorize-url',requireInternalService('rpc-proxy'),async (req, res, next) => {try {- const { recipeNs, recipeName, oauthClientId, userId, redirectUri, background } = req.body ?? {}+ const { recipeNs, recipeName, oauthClientId, userId, redirectUri, background } =+ req.body ?? {}if (typeof recipeNs !== 'string' ||typeof recipeName !== 'string' ||diff --git a/control-api/test/oauth.callback.mcp.test.ts b/control-api/test/oauth.callback.mcp.test.tsnew file mode 100644index 000000000..fcf217c50--- /dev/null+++ b/control-api/test/oauth.callback.mcp.test.ts@@ -0,0 +1,250 @@+import { describe, expect, it, vi } from 'vitest'+import {+ type CallbackDeps,+ type CallbackInput,+ type McpServerOAuthReader,+ type McpServerOAuthSubject,+ RecipeNotFoundError,+ type RecipeReader,+ handleOAuthCallback,+} from '../src/oauth/callback.js'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'+import { signOAuthState } from '../src/oauth/state.js'++/**+ * U5 — the mcp-subject OAuth callback. Fixtures are derived from the REAL+ * `signOAuthState` (T1: no hand-forged state) and the observable outcome asserted+ * is the persisted grant + the `source:'mcp'` return (T4), not intermediate calls.+ */++const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'+const ENCRYPTION_KEY = deriveOAuthEncryptionKey(+ '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'+)+const MCP_NS = 'mcp-server'+const REDIRECT_URI = 'https://control.example.com/api/v1/oauth-callback/google-drive'+const USER_ID = 'user-uuid-9'++function mcpState(overrides: Partial<Parameters<typeof signOAuthState>[1]> = {}): string {+ return signOAuthState(STATE_SECRET, {+ subjectKind: 'mcp',+ mcpServerName: 'gdrive',+ userId: USER_ID,+ oauthClientId: 'google-drive',+ grantKind: 'user',+ background: false,+ ...overrides,+ } as Parameters<typeof signOAuthState>[1])+}++function buildInput(overrides: Partial<CallbackInput> = {}): CallbackInput {+ return {+ oauthClientId: 'google-drive',+ code: 'AUTH_CODE',+ state: mcpState(),+ redirectUri: REDIRECT_URI,+ ...overrides,+ }+}++// The subject `decl` is derived from the REAL producer (`resolveServerOAuthSubject`)+// out of a raw McpServer fixture (T1) — not hand-built — so the callback is fed+// exactly the shape production wiring emits.+function gdriveSubject(+ opts: { grantScope?: 'user' | 'context'; contextRef?: string } = {}+): McpServerOAuthSubject {+ const rawServer = {+ metadata: { name: 'gdrive', namespace: MCP_NS },+ spec: {+ ...(opts.contextRef !== undefined ? { contextRef: opts.contextRef } : {}),+ auth: { type: 'oauth' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ scopes: ['https://www.googleapis.com/auth/drive.readonly'],+ backgroundAccess: false,+ ...(opts.grantScope ? { grantScope: opts.grantScope } : {}),+ },+ },+ }+ const resolved = resolveServerOAuthSubject(rawServer)+ if (!resolved) throw new Error('fixture: resolveServerOAuthSubject returned null')+ return { namespace: MCP_NS, ...resolved }+}++interface StubDb {+ query: ReturnType<typeof vi.fn>+}++function buildDeps(opts: {+ subject?: McpServerOAuthSubject | null+ subjectError?: unknown+ /** Contexts the signed user belongs to (shared-bootstrap membership gate). Default: member of ctx-A. */+ memberContexts?: string[]+}): { deps: CallbackDeps; db: StubDb } {+ const db: StubDb = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 1 }) }++ // A recipeReader that would explode if the mcp path ever hit it — proves the+ // dispatch never falls through to the recipe branch.+ const recipeReader: RecipeReader = {+ read: vi.fn(async () => {+ throw new Error('recipeReader must not be used for an mcp subject')+ }),+ }++ const mcpServerReader: McpServerOAuthReader = {+ read: vi.fn(async () => {+ if (opts.subjectError) throw opts.subjectError+ return opts.subject ?? null+ }),+ }++ const secretReader = {+ read: vi.fn(async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' })),+ }++ const fetchFn = vi.fn(async () => ({+ ok: true,+ status: 200,+ json: async () => ({+ access_token: 'GDRIVE-ACCESS',+ refresh_token: 'GDRIVE-REFRESH',+ expires_in: 3600,+ token_type: 'Bearer',+ }),+ text: async () => '',+ }))++ const memberContexts = opts.memberContexts ?? ['ctx-A']+ const userContextsReader = vi.fn(async () => ({ contextIds: memberContexts }))++ return {+ deps: {+ db: db as unknown as CallbackDeps['db'],+ recipeReader,+ mcpServerReader,+ userContextsReader,+ secretReader: secretReader as unknown as CallbackDeps['secretReader'],+ fetchFn: fetchFn as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey: ENCRYPTION_KEY,+ },+ db,+ }+}++describe('handleOAuthCallback — mcp subject (U5)', () => {+ it('persists a per-user grant keyed by (mcpserver owner, userId) and returns source:mcp', async () => {+ const { deps, db } = buildDeps({ subject: gdriveSubject({ grantScope: 'user' }) })+ const result = await handleOAuthCallback(buildInput(), deps)++ expect(result).toEqual({+ kind: 'ok',+ provider: 'google',+ userId: USER_ID,+ grantKind: 'user',+ backgroundRequested: false,+ backgroundEnabled: false,+ source: 'mcp',+ })++ expect(db.query).toHaveBeenCalledTimes(1)+ const [sql, params] = db.query.mock.calls[0] as [string, unknown[]]+ expect(sql).toContain('INSERT INTO oauth_grants')+ expect(sql).toContain(+ 'ON CONFLICT (owner_kind, recipe_namespace, recipe_name, user_id, oauth_client_id)'+ )+ // owner_kind, ns, name, userId, oauthClientId — the mcp-server owner coords.+ expect(params[0]).toBe('mcpserver')+ expect(params[1]).toBe(MCP_NS)+ expect(params[2]).toBe('gdrive')+ expect(params[3]).toBe(USER_ID)+ expect(params[4]).toBe('google-drive')+ expect(params[5]).toBe('google') // provider+ expect(typeof params[6]).toBe('string')+ expect((params[6] as string).startsWith('v1.')).toBe(true) // encrypted access token+ })++ it('context server: bootstraps a SHARED grant keyed by the authoritative contextRef, user_id NULL', async () => {+ const { deps, db } = buildDeps({+ subject: gdriveSubject({ grantScope: 'context', contextRef: 'ctx-A' }),+ })+ const result = await handleOAuthCallback(buildInput(), deps)+ expect(result.kind).toBe('ok')++ expect(db.query).toHaveBeenCalledTimes(1)+ const [sql, params] = db.query.mock.calls[0] as [string, unknown[]]+ // The shared bootstrap INSERT … ON CONFLICT DO NOTHING (first-wins).+ expect(sql).toContain('INSERT INTO oauth_grants')+ expect(sql).toContain("'shared'")+ expect(sql).toContain('DO NOTHING')+ // owner_kind, ns, name, context_id(=contextRef), oauthClientId, bootstrappedBy+ expect(params[0]).toBe('mcpserver')+ expect(params[1]).toBe(MCP_NS)+ expect(params[2]).toBe('gdrive')+ expect(params[3]).toBe('ctx-A') // authoritative context, from the subject not the state+ expect(params[4]).toBe('google-drive')+ expect(params[5]).toBe(USER_ID) // bootstrapped_by = the signed initiator+ })++ it('context server: a NON-member of the Context is denied (403) and NO shared grant is written', async () => {+ // Signed user consents, but is not a member of the server's contextRef.+ const { deps, db } = buildDeps({+ subject: gdriveSubject({ grantScope: 'context', contextRef: 'ctx-A' }),+ memberContexts: ['ctx-other', 'ctx-else'], // NOT ctx-A+ })+ const result = await handleOAuthCallback(buildInput(), deps)+ expect(result.kind).toBe('context_membership_denied')+ // Observable outcome (T4): the shared row was never inserted.+ expect(db.query).not.toHaveBeenCalled()+ })++ it('context server: fails closed when no userContextsReader is wired', async () => {+ const { deps, db } = buildDeps({+ subject: gdriveSubject({ grantScope: 'context', contextRef: 'ctx-A' }),+ })+ const result = await handleOAuthCallback(buildInput(), {+ ...deps,+ userContextsReader: undefined,+ })+ expect(result.kind).toBe('context_membership_denied')+ expect(db.query).not.toHaveBeenCalled()+ })++ it('context server WITHOUT contextRef fails closed (server_missing_context), no persist', async () => {+ const { deps, db } = buildDeps({+ subject: gdriveSubject({ grantScope: 'context', contextRef: undefined }),+ })+ const result = await handleOAuthCallback(buildInput(), deps)+ expect(result.kind).toBe('server_missing_context')+ expect(db.query).not.toHaveBeenCalled()+ })++ it('unknown server → server_not_found (reader returns null)', async () => {+ const { deps, db } = buildDeps({ subject: null })+ const result = await handleOAuthCallback(buildInput(), deps)+ expect(result.kind).toBe('server_not_found')+ expect(db.query).not.toHaveBeenCalled()+ })++ it('reader throwing RecipeNotFoundError → server_not_found', async () => {+ const { deps } = buildDeps({ subjectError: new RecipeNotFoundError('gone') })+ const result = await handleOAuthCallback(buildInput(), deps)+ expect(result.kind).toBe('server_not_found')+ })++ it('rejects when the callback-path oauthClientId disagrees with the signed state', async () => {+ const { deps } = buildDeps({ subject: gdriveSubject() })+ const result = await handleOAuthCallback(buildInput({ oauthClientId: 'other' }), deps)+ expect(result.kind).toBe('invalid_state')+ })++ it('fails closed when no mcpServerReader is wired', async () => {+ const { deps } = buildDeps({ subject: gdriveSubject() })+ const result = await handleOAuthCallback(buildInput(), { ...deps, mcpServerReader: undefined })+ expect(result.kind).toBe('server_not_found')+ })+})diff --git a/control-api/test/oauth.mcpServerOAuthSpec.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.test.tsnew file mode 100644index 000000000..b7a7e5ee4--- /dev/null+++ b/control-api/test/oauth.mcpServerOAuthSpec.test.ts@@ -0,0 +1,112 @@+import { describe, expect, it } from 'vitest'+import {+ type McpServerOAuthSpecInput,+ resolveServerOAuth,+ resolveServerOAuthSubject,+} from '../src/oauth/mcpServerOAuthSpec.js'++/**+ * Direct branch coverage for the pure producers in mcpServerOAuthSpec — the+ * fail-closed `null` returns and grant-scope / contextRef defaulting. Every+ * downstream seam (broker, callback, authorize-URL) trusts these to reject a+ * malformed `spec.oauth`, so they get a table test of their own (T1: the+ * producer is exercised where it lives, not only through a consumer).+ */++function server(+ oauth: Record<string, unknown> | undefined,+ contextRef?: unknown+): McpServerOAuthSpecInput {+ return {+ spec: { ...(oauth ? { oauth } : {}), ...(contextRef !== undefined ? { contextRef } : {}) },+ }+}++const FULL_OAUTH = {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'creds', key: 'client-id' },+ clientSecretRef: { name: 'creds', key: 'client-secret' },+ scopes: ['a', 'b'],+ backgroundAccess: true,+}++describe('resolveServerOAuthSubject — fail-closed branches (U5)', () => {+ it('returns the full decl + routing for a well-formed context server', () => {+ const r = resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'context' }, 'ctx-A'))+ expect(r).not.toBeNull()+ expect(r?.decl).toEqual({+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'creds', key: 'client-id' },+ clientSecretRef: { name: 'creds', key: 'client-secret' },+ scopes: ['a', 'b'],+ backgroundAccess: true,+ })+ expect(r?.grantScope).toBe('context')+ expect(r?.contextRef).toBe('ctx-A')+ })++ it('returns null when spec.oauth is absent', () => {+ expect(resolveServerOAuthSubject(server(undefined))).toBeNull()+ })++ it('returns null when id is missing or empty', () => {+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, id: undefined }))).toBeNull()+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, id: '' }))).toBeNull()+ })++ it('returns null when provider is missing or empty', () => {+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, provider: undefined }))).toBeNull()+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, provider: '' }))).toBeNull()+ })++ it('returns null when clientIdRef (or its key) is missing', () => {+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientIdRef: undefined }))).toBeNull()+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientIdRef: { name: 'creds' } }))+ ).toBeNull()+ })++ it('returns null when clientSecretRef (or its key) is missing', () => {+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, clientSecretRef: undefined }))+ ).toBeNull()+ expect(+ resolveServerOAuthSubject(+ server({ ...FULL_OAUTH, clientSecretRef: { key: 'client-secret' } })+ )+ ).toBeNull()+ })++ it('defaults grantScope to "user" for missing / non-"context" values', () => {+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }))?.grantScope).toBe('user')+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'garbage' }))?.grantScope+ ).toBe('user')+ expect(+ resolveServerOAuthSubject(server({ ...FULL_OAUTH, grantScope: 'context' }))?.grantScope+ ).toBe('context')+ })++ it('normalizes an empty / absent contextRef to undefined', () => {+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }, ''))?.contextRef).toBeUndefined()+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }))?.contextRef).toBeUndefined()+ expect(resolveServerOAuthSubject(server({ ...FULL_OAUTH }, 'ctx-Z'))?.contextRef).toBe('ctx-Z')+ })++ it('drops non-string scope entries (never emits a non-string scope)', () => {+ const r = resolveServerOAuthSubject(server({ ...FULL_OAUTH, scopes: ['ok', 5, null, 'yes'] }))+ expect(r?.decl.scopes).toEqual(['ok', 'yes'])+ })++ // Cross-check the two producers agree on oauthClientId + grantScope + contextRef.+ it('agrees with resolveServerOAuth on id / grantScope / contextRef', () => {+ const input = server({ ...FULL_OAUTH, grantScope: 'context' }, 'ctx-A')+ const subject = resolveServerOAuthSubject(input)+ const resolved = resolveServerOAuth(input)+ expect(subject?.decl.id).toBe(resolved?.oauthClientId)+ expect(subject?.grantScope).toBe(resolved?.grantScope)+ expect(subject?.contextRef).toBe(resolved?.contextRef)+ })+})diff --git a/control-api/test/oauth.state.test.ts b/control-api/test/oauth.state.test.tsindex fd3e4021b..02b7fb453 100644--- a/control-api/test/oauth.state.test.ts+++ b/control-api/test/oauth.state.test.ts@@ -1,5 +1,5 @@-import { createHmac } from 'node:crypto'import { describe, expect, it } from 'vitest'+import { createHmac } from 'node:crypto'import { signOAuthState, verifyOAuthState, verifyOAuthStateSignature } from '../src/oauth/state.js'const SECRET = 'unit-test-state-hmac-secret-32-bytes-pad'@@ -131,6 +131,167 @@ describe('signOAuthState / verifyOAuthState (O3.1)', () => {})})+describe('OAuth state — recipe subject wire format is FROZEN (U5 byte-identity)', () => {+ // The exact field set + order the pre-U5 recipe state serialized with. The+ // authorize-URL helper signs with this exact input shape (background defaulted+ // to false). If U5 leaks a `subjectKind`/`mcpServerName` field, or reorders,+ // this decode-and-rebuild guard fails.+ const RECIPE_INPUT = {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'crm',+ userId: 'user-uuid-1',+ oauthClientId: 'salesforce',+ grantKind: 'user' as const,+ background: false,+ }+ const FROZEN_KEYS = [+ 'recipeNamespace',+ 'recipeName',+ 'userId',+ 'oauthClientId',+ 'grantKind',+ 'background',+ 'expiresAt',+ 'nonce',+ ]++ it('carries NO subject discriminator and NO mcp fields for a recipe subject', () => {+ const state = signOAuthState(SECRET, RECIPE_INPUT)+ const payload = state.split('.')[1]+ const obj = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))+ expect(Object.keys(obj)).toEqual(FROZEN_KEYS)+ expect('subjectKind' in obj).toBe(false)+ expect('mcpServerName' in obj).toBe(false)+ })++ it('serializes byte-for-byte as JSON.stringify of the frozen field order', () => {+ const state = signOAuthState(SECRET, RECIPE_INPUT)+ const payload = state.split('.')[1]+ const obj = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'))+ // Re-serialize in the exact frozen order using ONLY the wire values; a byte+ // match proves the serialization order + field set is unchanged from pre-U5.+ const rebuilt = Buffer.from(+ JSON.stringify({+ recipeNamespace: obj.recipeNamespace,+ recipeName: obj.recipeName,+ userId: obj.userId,+ oauthClientId: obj.oauthClientId,+ grantKind: obj.grantKind,+ background: obj.background,+ expiresAt: obj.expiresAt,+ nonce: obj.nonce,+ })+ ).toString('base64url')+ expect(rebuilt).toBe(payload)+ // And the signature covers exactly that payload.+ const sig = createHmac('sha256', SECRET).update(`v1.${payload}`).digest('base64url')+ expect(state.split('.')[2]).toBe(sig)+ })++ it('an explicit subjectKind:"recipe" produces the same frozen wire (no discriminator)', () => {+ const withTag = signOAuthState(SECRET, { ...RECIPE_INPUT, subjectKind: 'recipe' as const })+ const obj = JSON.parse(Buffer.from(withTag.split('.')[1], 'base64url').toString('utf8'))+ expect('subjectKind' in obj).toBe(false)+ expect(Object.keys(obj)).toEqual(FROZEN_KEYS)+ })+})++describe('OAuth state — mcp subject round-trip + fail-closed (U5)', () => {+ const MCP_INPUT = {+ subjectKind: 'mcp' as const,+ mcpServerName: 'gdrive',+ userId: 'user-uuid-9',+ oauthClientId: 'google-drive',+ grantKind: 'user' as const,+ background: false,+ }++ it('round-trips subjectKind + mcpServerName + userId + oauthClientId', () => {+ const state = signOAuthState(SECRET, MCP_INPUT)+ const r = verifyOAuthStateSignature(SECRET, state)+ expect(r.kind).toBe('ok')+ if (r.kind === 'ok') {+ expect(r.claims.subjectKind).toBe('mcp')+ // Narrow to the mcp variant to read mcpServerName.+ if (r.claims.subjectKind === 'mcp') {+ expect(r.claims.mcpServerName).toBe('gdrive')+ }+ expect(r.claims.userId).toBe('user-uuid-9')+ expect(r.claims.oauthClientId).toBe('google-drive')+ // A recipe field must NOT be present on an mcp subject.+ expect((r.claims as Record<string, unknown>).recipeNamespace).toBeUndefined()+ }+ })++ it('rejects a forged signature on an mcp state', () => {+ const state = signOAuthState(SECRET, MCP_INPUT)+ const bad = verifyOAuthStateSignature('different-secret-32-bytes-padding-here', state)+ expect(bad.kind).toBe('invalid_signature')+ })++ it('rejects a tampered mcpServerName (signature no longer matches)', () => {+ const state = signOAuthState(SECRET, MCP_INPUT)+ const [version, payload, signature] = state.split('.')+ const tampered = Buffer.from(+ JSON.stringify({+ ...JSON.parse(Buffer.from(payload, 'base64url').toString()),+ mcpServerName: 'attacker-server',+ })+ ).toString('base64url')+ const r = verifyOAuthStateSignature(SECRET, [version, tampered, signature].join('.'))+ expect(r.kind).toBe('invalid_signature')+ })++ it('fails closed on a validly-signed mcp state that is missing mcpServerName', () => {+ // Sign a hand-built payload (mcp discriminator, no mcpServerName) with the+ // REAL secret so only the shape — not the signature — can be the failure.+ const bad = {+ subjectKind: 'mcp',+ userId: 'u',+ oauthClientId: 'c',+ grantKind: 'user',+ background: false,+ expiresAt: Math.floor(Date.now() / 1000) + 600,+ nonce: 'n',+ }+ const payload = Buffer.from(JSON.stringify(bad)).toString('base64url')+ const sig = createHmac('sha256', SECRET).update(`v1.${payload}`).digest('base64url')+ const r = verifyOAuthStateSignature(SECRET, `v1.${payload}.${sig}`)+ // Signature is valid, but the malformed mcp shape is rejected at decode.+ expect(r.kind).toBe('invalid_format')+ })++ it('fails closed on an unknown subjectKind (never defaults to recipe)', () => {+ const bad = {+ subjectKind: 'evil',+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'crm',+ userId: 'u',+ oauthClientId: 'c',+ grantKind: 'user',+ background: false,+ expiresAt: Math.floor(Date.now() / 1000) + 600,+ nonce: 'n',+ }+ const payload = Buffer.from(JSON.stringify(bad)).toString('base64url')+ const sig = createHmac('sha256', SECRET).update(`v1.${payload}`).digest('base64url')+ const r = verifyOAuthStateSignature(SECRET, `v1.${payload}.${sig}`)+ expect(r.kind).toBe('invalid_format')+ })++ it('the recipe external-binding verifier fails closed on an mcp state', () => {+ const state = signOAuthState(SECRET, MCP_INPUT)+ const r = verifyOAuthState(SECRET, state, {+ recipeNamespace: 'sandbox-recipes',+ recipeName: 'gdrive',+ userId: 'user-uuid-9',+ oauthClientId: 'google-drive',+ })+ expect(r.kind).toBe('binding_mismatch')+ if (r.kind === 'binding_mismatch') expect(r.reason).toBe('subjectKind')+ })+})+describe('verifyOAuthStateSignature (signature-only, for the path-less callback)', () => {it('verifies signature + expiry and returns claims with NO external binding check', () => {const state = signOAuthState(SECRET, BINDING)@@ -181,6 +342,8 @@ describe('verifyOAuthStateSignature (signature-only, for the path-less callback)})).toString('base64url')const sig = createHmac('sha256', SECRET).update(`${version}.${expired}`).digest('base64url')- expect(verifyOAuthStateSignature(SECRET, [version, expired, sig].join('.')).kind).toBe('expired')+ expect(verifyOAuthStateSignature(SECRET, [version, expired, sig].join('.')).kind).toBe(+ 'expired'+ )})})diff --git a/control-api/test/oauth.successHtml.test.ts b/control-api/test/oauth.successHtml.test.tsindex 18d2d181b..a76d78eb8 100644--- a/control-api/test/oauth.successHtml.test.ts+++ b/control-api/test/oauth.successHtml.test.ts@@ -40,6 +40,27 @@ describe('renderSuccessHtml (spec §9.9 OAuth callback success page)', () => {expect(metaContent).not.toMatch(/&(?!amp;|quot;|lt;|gt;|#)/)})+ it('recipe subject (no source opt) emits a FROZEN deep-link with NO source param', () => {+ const html = renderSuccessHtml('slack', 'slack-bot')+ const metaContent = /content="0;url=([^"]+)"/.exec(html)?.[1] ?? ''+ expect(metaContent).not.toContain('source')+ // Same when opts is present but source is absent.+ const html2 = renderSuccessHtml('slack', 'slack-bot', { backgroundEnabled: true })+ expect(/content="0;url=([^"]+)"/.exec(html2)?.[1] ?? '').not.toContain('source')+ })++ it('mcp subject appends &source=mcp on the SAME oauth-completed host, keeping clientId', () => {+ const html = renderSuccessHtml('google', 'google-drive', { source: 'mcp' })+ const metaContent = /content="0;url=([^"]+)"/.exec(html)?.[1] ?? ''+ // HTML-attribute context escapes `&` → `&`; decode for a clean parse.+ const url = new URL(metaContent.replace(/&/g, '&'))+ expect(url.protocol).toBe('clerum:')+ expect(url.host).toBe('oauth-completed')+ expect(url.searchParams.get('clientId')).toBe('google-drive')+ expect(url.searchParams.get('provider')).toBe('google')+ expect(url.searchParams.get('source')).toBe('mcp')+ })+it('JSON-escapes the URL inside the inline <script> to block </script> injection', () => {// Even if a clientId carried `</script>`, the JSON.stringify+\\u003c// replace should keep it from closing the inline script tag.diff --git a/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.tsnew file mode 100644index 000000000..d3bcd2b3d--- /dev/null+++ b/control-api/test/routes.internal.mcpOauthAuthorizeUrl.test.ts@@ -0,0 +1,194 @@+import { beforeEach, describe, expect, it, vi } from 'vitest'+import request from 'supertest'+import { createApp } from '../src/app.js'+import { config } from '../src/config.js'+import { verifyOAuthStateSignature } from '../src/oauth/state.js'+import { MockGateway } from './mockGateway.js'++/**+ * U5 — internal endpoint that mints a fresh authorize-URL for an OAuth+ * mcp-server, on click. rpc-proxy is the sole authorized caller+ * (requireInternalService('rpc-proxy')); the `userId` is forwarded over that+ * mutually-authenticated seam (rpc-proxy derives it from the session auth.sub).+ * The `oauthClientId` + Context come from the McpServer CR, never the body.+ */++const mockPoolQuery = vi.fn()+vi.mock('../src/db.js', () => ({+ pool: { query: (...args: unknown[]) => mockPoolQuery(...args) },+}))++const MCP_NS = config.mcpServersNamespace++function seedOauthServer(+ gateway: MockGateway,+ opts: { name: string; grantScope?: 'user' | 'context'; contextRef?: string } = { name: 'gdrive' }+): void {+ void gateway.createResource(+ 'mcpservers',+ {+ metadata: { name: opts.name },+ spec: {+ contextRef: opts.contextRef ?? 'ctx-9',+ auth: { type: 'oauth' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ scopes: ['https://www.googleapis.com/auth/drive.readonly'],+ ...(opts.grantScope ? { grantScope: opts.grantScope } : {}),+ },+ },+ },+ MCP_NS+ )+ // client_id must be resolvable for the authorize URL to be built.+ gateway.seedSecret('google-creds', MCP_NS, {+ data: {+ 'client-id': Buffer.from('GOOGLE_CLIENT_ID').toString('base64'),+ 'client-secret': Buffer.from('GOOGLE_CLIENT_SECRET').toString('base64'),+ },+ })+}++function post(app: ReturnType<typeof createApp>) {+ return request(app).post('/api/v1/internal/mcp-oauth/authorize-url')+}++describe('POST /api/v1/internal/mcp-oauth/authorize-url (U5)', () => {+ let gateway: MockGateway+ let app: ReturnType<typeof createApp>++ beforeEach(() => {+ gateway = new MockGateway(MCP_NS)+ app = createApp(gateway as never)+ mockPoolQuery.mockReset()+ mockPoolQuery.mockResolvedValue({ rows: [], rowCount: 0 })+ })++ it('401 without any service token', async () => {+ seedOauthServer(gateway)+ const res = await post(app).send({ mcpServerName: 'gdrive', userId: 'user-1' })+ expect(res.status).toBe(401)+ })++ it('401 for an authenticated NON-rpc-proxy service (external-rest-api)', async () => {+ seedOauthServer(gateway)+ const res = await post(app)+ .set('Authorization', 'Bearer dev-external-rest-api-token')+ .set('x-service-token', 'external-rest-api')+ .send({ mcpServerName: 'gdrive', userId: 'user-1' })+ expect(res.status).toBe(401)+ })++ it('mints an authorize-URL whose signed state binds the forwarded userId + the SERVER oauthClientId', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'user' })+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ // A bogus oauthClientId in the body MUST be ignored — it is derived from+ // the server. userId is the value forwarded from the session.+ .send({ mcpServerName: 'gdrive', userId: 'user-7', oauthClientId: 'attacker-client' })++ if (res.status !== 200) {+ throw new Error(`got ${res.status}: ${JSON.stringify(res.body)}\n${res.text}`)+ }+ const authorizeUrl: string = res.body.authorizeUrl+ expect(authorizeUrl).toContain('https://accounts.google.com/')++ const state = new URL(authorizeUrl).searchParams.get('state') ?? ''+ const verified = verifyOAuthStateSignature(config.oauthStateHmacSecret, state)+ expect(verified.kind).toBe('ok')+ if (verified.kind === 'ok') {+ expect(verified.claims.subjectKind).toBe('mcp')+ if (verified.claims.subjectKind === 'mcp') {+ expect(verified.claims.mcpServerName).toBe('gdrive')+ }+ // userId comes from the seam-forwarded body value…+ expect(verified.claims.userId).toBe('user-7')+ // …but oauthClientId is the server's, NOT the attacker body value.+ expect(verified.claims.oauthClientId).toBe('google-drive')+ }+ })++ it('400 invalid_request when userId is absent (nothing to bind the state to)', async () => {+ seedOauthServer(gateway)+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'gdrive' })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('invalid_request')+ })++ it('404 server_not_found for an unknown server', async () => {+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'ghost', userId: 'user-1' })+ expect(res.status).toBe(404)+ expect(res.body.error).toBe('server_not_found')+ })++ it('400 not_oauth_server for a non-oauth server', async () => {+ void gateway.createResource(+ 'mcpservers',+ { metadata: { name: 'plain' }, spec: { auth: { type: 'none' } } },+ MCP_NS+ )+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'plain', userId: 'user-1' })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('not_oauth_server')+ })++ it('context server: rejects a cross-context body contextId with 400 context_mismatch', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'gdrive', userId: 'user-2', contextId: 'ctx-B' })+ expect(res.status).toBe(400)+ expect(res.body.error).toBe('context_mismatch')+ })++ it('context server: accepts a matching body contextId and mints the URL', async () => {+ seedOauthServer(gateway, { name: 'gdrive', grantScope: 'context', contextRef: 'ctx-A' })+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'gdrive', userId: 'user-2', contextId: 'ctx-A' })+ expect(res.status).toBe(200)+ expect(res.body.authorizeUrl).toContain('https://accounts.google.com/')+ })++ it('503 integration_not_configured when the client_id Secret is absent', async () => {+ // Server exists but no google-creds Secret seeded.+ void gateway.createResource(+ 'mcpservers',+ {+ metadata: { name: 'gdrive' },+ spec: {+ contextRef: 'ctx-9',+ auth: { type: 'oauth' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ },+ },+ },+ MCP_NS+ )+ const res = await post(app)+ .set('Authorization', 'Bearer dev-rpc-proxy-token')+ .set('x-service-token', 'rpc-proxy')+ .send({ mcpServerName: 'gdrive', userId: 'user-1' })+ expect(res.status).toBe(503)+ expect(res.body.error).toBe('integration_not_configured')+ })+})