Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat(oauth): remote MCP oauth connected lane (C4)
Diego Zacarias7bfc2e9a947d
diff --git a/control-api/package.json b/control-api/package.jsonindex 5a7c785da..68e2a3c02 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.592",+ "version": "0.1.593","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 6bf08af86..a43a90781 100644--- a/control-api/src/oauth/authorizeUrlHelper.ts+++ b/control-api/src/oauth/authorizeUrlHelper.ts@@ -9,7 +9,11 @@ import {type SecretReader,} from './callback.js'import { computeCodeChallengeS256, deriveCodeVerifier } from './pkce.js'-import { getOAuthProviderAdapter, isKnownOAuthProvider } from './providers.js'+import {+ buildRemoteAuthorizeUrl,+ getOAuthProviderAdapter,+ isKnownOAuthProvider,+} from './providers.js'import { type SignStateInput, signOAuthState } from './state.js'/**@@ -164,23 +168,48 @@ async function mintAuthorizeUrl(return { kind: 'background_access_not_enabled' }}+ // Remote lane (`source:'remote'`): the authorize URL is built from the pinned+ // discovery-derived `authorizationEndpoint` with a PUBLIC client_id (`decl.id`,+ // backfilled for every mode — DEC-23), mandatory PKCE S256, and RFC 8707+ // `resource`. No secret material rides the URL and no K8s Secret is read.+ if (decl.remote) {+ const state = signOAuthState(deps.stateSecret, stateInput)+ const codeChallenge = computeCodeChallengeS256(deriveCodeVerifier(deps.stateSecret, state))+ const authorizeUrl = buildRemoteAuthorizeUrl(decl.remote.authorizationEndpoint, {+ clientId: decl.id,+ redirectUri: input.redirectUri,+ state,+ scopes: decl.scopes ?? [],+ codeChallenge,+ resource: decl.remote.resource,+ })+ return { kind: 'ok', authorizeUrl }+ }+if (!isKnownOAuthProvider(decl.provider)) {return { kind: 'unsupported_provider', provider: decl.provider }}const adapter = getOAuthProviderAdapter(decl.provider)+ // Baked/recipe lane: clientIdRef is always present (only the remote lane, handled+ // above, omits it). Guard fail-closed rather than dereference undefined.+ if (!decl.clientIdRef) {+ return { kind: 'secret_missing', secret: `${decl.id}/client_id` }+ }+ const clientIdRef = decl.clientIdRef+let clientIdSecret: Record<string, string>try {- clientIdSecret = await deps.secretReader.read(decl.clientIdRef.name, secretNamespace)+ clientIdSecret = await deps.secretReader.read(clientIdRef.name, secretNamespace)} catch (err) {if (err instanceof SecretNotFoundError) {- return { kind: 'secret_missing', secret: decl.clientIdRef.name }+ return { kind: 'secret_missing', secret: clientIdRef.name }}throw err}- const clientId = clientIdSecret[decl.clientIdRef.key]+ const clientId = clientIdSecret[clientIdRef.key]if (!clientId) {- return { kind: 'secret_missing', secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}` }+ return { kind: 'secret_missing', secret: `${clientIdRef.name}/${clientIdRef.key}` }}const state = signOAuthState(deps.stateSecret, stateInput)diff --git a/control-api/src/oauth/callback.ts b/control-api/src/oauth/callback.tsindex 4ef1815da..da4ba5104 100644--- a/control-api/src/oauth/callback.ts+++ b/control-api/src/oauth/callback.ts@@ -1,15 +1,69 @@import type { DbClient } from '../db.js'+import type { PinnedTransport } from '../http/pinnedFetch.js'+import { pinnedFetch } from '../http/pinnedFetch.js'+import type { DnsResolver } from '../http/validateMcpServerSpec.js'+import { getDynamicClient } from './dynamicClientStore.js'import { deriveCodeVerifier } from './pkce.js'import {type OAuthProvider,type ParsedTokenResponse,+ buildRemoteTokenRequest,getOAuthProviderAdapter,isKnownOAuthProvider,+ parseRemoteTokenResponse,} from './providers.js'import type { OAuthMcpStateClaims } from './state.js'import { signOAuthState, verifyOAuthStateSignature } from './state.js'import { bootstrapSharedOAuthGrant, setUserGrantBackground, upsertOAuthGrant } from './store.js'+/**+ * Reserved last URL segment of the STABLE remote OAuth callback+ * (`/api/v1/oauth-callback/remote`). The remote lane (CIMD/DCR) registers ONE+ * fixed redirect_uri, so the URL segment is a constant and the real client+ * binding rides the signed state (`subjectKind:'mcp'` + `mcpServerName`, both+ * re-resolved authoritatively). `cimd.ts` derives `REMOTE_CALLBACK_PATH` from+ * this. Kept here (not in `cimd.ts`) to avoid an import cycle+ * (callback → cimd → external/oauthCallback → callback).+ */+export const REMOTE_CALLBACK_CLIENT_SEGMENT = 'remote'++/**+ * Discriminator for WHERE an mcp-server's OAuth client credentials live+ * (DEC-18). Present only on a `source:'remote'` subject; baked/recipe decls read+ * their K8s Secret via `clientIdRef`/`clientSecretRef` directly and carry none.+ * - `k8s-secret` → pre-registered confidential: read the named Secret.+ * - `dcr-store` → DCR-confidential: read the encrypted `dynamic_clients` row.+ * - `public` → CIMD/DCR-public: no secret; `client_id` IS `oauth.id`.+ */+export type ServerOAuthSecretSource =+ | {+ kind: 'k8s-secret'+ clientIdRef: { name: string; key: string }+ clientSecretRef: { name: string; key: string }+ }+ | { kind: 'dcr-store' }+ | { kind: 'public' }++/**+ * Remote MCP-OAuth routing pinned on the CR at install (C1.5/C2/C3). Present only+ * for a `source:'remote'` client; drives the discovery-derived exchange/refresh/+ * authorize instead of a baked provider adapter. All endpoints are attacker-+ * controlled (discovery-derived) ⇒ every fetch through them is IP-pinned (DEC-17).+ */+export interface RemoteClientRouting {+ authorizationEndpoint: string+ tokenEndpoint: string+ /** RFC 8707 resource indicator, echoed in authorize + token/refresh. */+ resource?: string+ clientMode: 'public' | 'confidential'+ /** D-8: token in the body vs Authorization header (mcp-host concern; carried for parity). */+ bearerInBody: boolean+ /** D-8: fail-closed — false ⇒ NEVER attempt a refresh. */+ supportsRefresh: boolean+ /** RFC 9207 issuer to validate the callback `iss` against, when advertised. */+ issForCallback?: string+}+/*** End-to-end handler for the auth-code OAuth callback. Independent of Express* so we can unit-test it with stubs for K8s + DB + fetch. The route handler@@ -21,7 +75,13 @@ import { bootstrapSharedOAuthGrant, setUserGrantBackground, upsertOAuthGrant } fexport interface OAuthClientDecl {id: stringprovider: string- clientIdRef: { name: string; key: string }+ /**+ * Confidential-client id reference. Optional (C4/DEC-23): a remote PUBLIC or+ * DCR client has no K8s ref — its `client_id` is `oauth.id` (`decl.id`) or the+ * encrypted `dynamic_clients` row. Baked/recipe decls always carry it; the+ * baked paths guard fail-closed if it is somehow absent (unreachable there).+ */+ clientIdRef?: { name: string; key: string }/*** Confidential-client secret reference. Optional (E-19.2): a PUBLIC OAuth* client declares no secret, so the callback reads only the client_id Secret@@ -37,6 +97,17 @@ export interface OAuthClientDecl {* recipe predating the field reads as `undefined` → fail closed).*/backgroundAccess?: boolean+ /**+ * Remote MCP-OAuth routing (`source:'remote'`). Present ⇒ the discovery-derived+ * lane: exchange/refresh/authorize use the pinned endpoints + `secretSource`+ * instead of a baked provider adapter. Absent ⇒ baked/recipe (byte-identical).+ */+ remote?: RemoteClientRouting+ /**+ * Where the remote client credentials live (DEC-18). Present only alongside+ * `remote`; absent ⇒ the legacy K8s `clientIdRef`/`clientSecretRef` path.+ */+ secretSource?: ServerOAuthSecretSource}export interface RecipeWithOAuthClients {@@ -139,7 +210,12 @@ export interface CallbackDeps {* 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. */+ /**+ * Injectable for tests; defaults to globalThis.fetch in production wiring.+ * BAKED lane ONLY — the remote lane (`source:'remote'`) never uses it (DEC-17):+ * its endpoint is discovery-derived, so it goes through the IP-pinned+ * `pinnedFetch` to close the DNS-rebinding TOCTOU (H2).+ */fetchFn: typeof fetch/** HMAC secret used to sign / verify state. */stateSecret: string@@ -147,12 +223,22 @@ export interface CallbackDeps {encryptionKey: Buffer/** Optional override for token-exchange request timeout. Default 15s. */tokenRequestTimeoutMs?: number+ /**+ * Remote lane only: injectable DNS resolver + pinned transport for+ * `pinnedFetch`. Production leaves both undefined (real resolve + real+ * `node:https`); tests inject to assert `connectedIP === validatedIP`.+ */+ resolveDns?: DnsResolver+ pinnedTransport?: PinnedTransport}+/** Provider label persisted / displayed. `'remote'` for the discovery-derived lane. */+export type GrantProviderLabel = OAuthProvider | 'remote'+export type CallbackResult =| {kind: 'ok'- provider: OAuthProvider+ provider: GrantProviderLabeluserId: stringgrantKind: 'user' | 'service'/** Whether the user explicitly requested background access in this flow. */@@ -223,7 +309,16 @@ export async function handleOAuthCallback(return { kind: 'invalid_state', reason: verified.kind }}const claims = verified.claims- if (claims.oauthClientId !== input.oauthClientId) {+ // Defence-in-depth: the URL segment must equal the signed client id — EXCEPT on+ // the stable remote callback (`/oauth-callback/remote`), where CIMD/DCR register+ // one fixed redirect_uri and the segment is the reserved constant, not the+ // client id. There the binding rides the HMAC state (`subjectKind:'mcp'` ++ // `mcpServerName`) and is re-checked below against the freshly-resolved subject+ // (`subject.decl.id === claims.oauthClientId`). Recipe subjects always enforce+ // the segment==id check (the reserved segment is mcp-only).+ const isRemoteStableSegment =+ claims.subjectKind === 'mcp' && input.oauthClientId === REMOTE_CALLBACK_CLIENT_SEGMENT+ if (!isRemoteStableSegment && claims.oauthClientId !== input.oauthClientId) {return { kind: 'invalid_state', reason: 'binding_mismatch' }}@@ -256,7 +351,7 @@ export async function handleOAuthCallback(if (!clientDecl) return { kind: 'unknown_oauth_client' }// ─── 3-4. Read secrets + exchange code ────────────────────────────────- const exchanged = await exchangeAuthCode(clientDecl, recipeNamespace, input, deps)+ const exchanged = await exchangeAuthCode(clientDecl, recipeNamespace, undefined, input, deps)if (exchanged.kind !== 'ok') return exchangedconst { provider, parsed } = exchanged@@ -347,8 +442,12 @@ async function handleMcpOAuthCallback(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) {+ // client id bound in the signed state. Check against `claims.oauthClientId`+ // (NOT `input.oauthClientId`): on the stable remote callback the URL segment is+ // the reserved `remote` constant, not the client id — the state carries the real+ // one. For the baked mcp lane `claims.oauthClientId === input.oauthClientId`+ // (enforced above), so this stays equivalent.+ if (subject.decl.id !== claims.oauthClientId) {return { kind: 'invalid_state', reason: 'binding_mismatch' }}@@ -383,7 +482,13 @@ async function handleMcpOAuthCallback(contextRef = subject.contextRef}- const exchanged = await exchangeAuthCode(subject.decl, subject.namespace, input, deps)+ const exchanged = await exchangeAuthCode(+ subject.decl,+ subject.namespace,+ claims.mcpServerName,+ input,+ deps+ )if (exchanged.kind !== 'ok') return exchangedconst { provider, parsed } = exchanged@@ -394,7 +499,11 @@ async function handleMcpOAuthCallback(recipeNamespace: subject.namespace,recipeName: claims.mcpServerName,contextId: contextRef,- oauthClientId: input.oauthClientId,+ // Grant coordinate = the resolved client id (`oauth.id`), NEVER the URL+ // segment: on the stable remote callback `input.oauthClientId` is the literal+ // `remote`. `subject.decl.id === claims.oauthClientId` (checked above), and it+ // matches what the token broker keys by (`resolveServerOAuth`, D4).+ oauthClientId: subject.decl.id,// Bootstrapper = the signed initiator. Audit-only, first-wins on conflict.bootstrappedByUserId: claims.userId,provider,@@ -409,7 +518,8 @@ async function handleMcpOAuthCallback(recipeNamespace: subject.namespace,recipeName: claims.mcpServerName,userId: claims.userId,- oauthClientId: input.oauthClientId,+ // See the shared-grant branch: coordinate is `oauth.id`, not the URL segment.+ oauthClientId: subject.decl.id,provider,accessToken: parsed.accessToken,refreshToken: parsed.refreshToken,@@ -434,7 +544,7 @@ async function handleMcpOAuthCallback(}type ExchangeAuthCodeResult =- | { kind: 'ok'; provider: OAuthProvider; parsed: ParsedTokenResponse }+ | { kind: 'ok'; provider: GrantProviderLabel; parsed: ParsedTokenResponse }| { kind: 'unknown_oauth_client' }| { kind: 'secret_missing'; secret: string }| { kind: 'unsupported_provider'; provider: string }@@ -450,21 +560,36 @@ type ExchangeAuthCodeResult =async function exchangeAuthCode(decl: OAuthClientDecl,secretNamespace: string,+ /** mcp-server name (grant/dynamic-client coordinate); undefined for the recipe lane. */+ serverName: string | undefined,input: CallbackInput,deps: CallbackDeps): Promise<ExchangeAuthCodeResult> {+ // Remote lane (`source:'remote'`): discovery-derived endpoint ⇒ IP-pinned POST+ // (DEC-17), public token client, credentials per `secretSource`. Byte-identical+ // baked path is below (unchanged).+ if (decl.remote) {+ return exchangeRemoteAuthCode(decl, secretNamespace, serverName, input, deps)+ }++ // Baked/recipe lane. clientIdRef is always present here (remote is the only+ // decl that omits it); guard fail-closed rather than dereference undefined.+ if (!decl.clientIdRef) {+ return { kind: 'secret_missing', secret: `${decl.id}/client_id` }+ }+ const clientIdRef = decl.clientIdReflet clientIdSecret: Record<string, string>try {- clientIdSecret = await deps.secretReader.read(decl.clientIdRef.name, secretNamespace)+ clientIdSecret = await deps.secretReader.read(clientIdRef.name, secretNamespace)} catch (err) {if (err instanceof SecretNotFoundError) {- return { kind: 'secret_missing', secret: decl.clientIdRef.name }+ return { kind: 'secret_missing', secret: clientIdRef.name }}throw err}- const clientId = clientIdSecret[decl.clientIdRef.key]+ const clientId = clientIdSecret[clientIdRef.key]if (!clientId) {- return { kind: 'secret_missing', secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}` }+ return { kind: 'secret_missing', secret: `${clientIdRef.name}/${clientIdRef.key}` }}// Public client (E-19.2): no clientSecretRef ⇒ skip the second Secret read and@@ -531,6 +656,167 @@ async function exchangeAuthCode(}}+/**+ * Remote-lane auth-code exchange (`source:'remote'`). Discovery-derived token+ * endpoint ⇒ IP-pinned POST (DEC-17, closes the H2 DNS-rebinding TOCTOU). Public+ * token client with credentials resolved per `secretSource`. Always PKCE S256.+ */+async function exchangeRemoteAuthCode(+ decl: OAuthClientDecl,+ secretNamespace: string,+ serverName: string | undefined,+ input: CallbackInput,+ deps: CallbackDeps+): Promise<ExchangeAuthCodeResult> {+ // `decl.remote` presence is the branch guard in the caller.+ const remote = decl.remote as RemoteClientRouting+ const credResult = await resolveRemoteClientCredential(decl, secretNamespace, serverName, deps)+ if (!credResult.ok) return { kind: 'secret_missing', secret: credResult.secret }++ // PKCE (DEC-1 / §6 #3): the remote lane is ALWAYS S256 — re-derive the verifier+ // from the exact round-tripped state, same as the baked PKCE adapters.+ const codeVerifier = deriveCodeVerifier(deps.stateSecret, input.state)+ const tokenRequest = buildRemoteTokenRequest(+ remote.tokenEndpoint,+ {+ code: input.code,+ clientId: credResult.cred.clientId,+ clientSecret: credResult.cred.clientSecret,+ redirectUri: input.redirectUri,+ codeVerifier,+ },+ remote.resource+ )+ const posted = await postRemoteTokenForm(+ remote.tokenEndpoint,+ 'spec.oauth.tokenEndpoint',+ tokenRequest,+ {+ resolveDns: deps.resolveDns,+ pinnedTransport: deps.pinnedTransport,+ timeoutMs: deps.tokenRequestTimeoutMs,+ }+ )+ if (!posted.ok) {+ if (typeof posted.status === 'number') {+ return { kind: 'provider_token_exchange_failed', status: posted.status, body: posted.detail }+ }+ return { kind: 'provider_response_invalid', detail: posted.detail }+ }+ try {+ return {+ kind: 'ok',+ provider: 'remote',+ parsed: parseRemoteTokenResponse(JSON.parse(posted.bodyText)),+ }+ } catch (err) {+ return { kind: 'provider_response_invalid', detail: (err as Error).message }+ }+}++/** Resolved remote client credentials for a token/refresh POST. */+export interface RemoteClientCredential {+ clientId: string+ /** Absent for a public client. */+ clientSecret?: string+}++export type RemoteCredentialResult =+ | { ok: true; cred: RemoteClientCredential }+ | { ok: false; secret: string }++/**+ * Resolve the remote client's `(clientId, clientSecret)` from the `secretSource`+ * discriminator (DEC-18) — the SINGLE place the three remote secret sources are+ * read, shared by the exchange (here) and the refresh (`tokenHelper.ts`) so the+ * two never drift (D4). Never logs or returns secret material on the error path+ * (names only). `serverName` is the `dynamic_clients` coordinate (DCR only).+ */+export async function resolveRemoteClientCredential(+ decl: OAuthClientDecl,+ secretNamespace: string,+ serverName: string | undefined,+ deps: { db: DbClient; encryptionKey: Buffer; secretReader: SecretReader }+): Promise<RemoteCredentialResult> {+ const source = decl.secretSource+ // A remote decl always carries a secretSource; fail closed if it somehow does not.+ if (!source) return { ok: false, secret: `${decl.id}/secret_source_missing` }+ if (source.kind === 'public') {+ // CIMD/DCR-public: the public client_id IS `oauth.id`; no secret.+ return { ok: true, cred: { clientId: decl.id } }+ }+ if (source.kind === 'dcr-store') {+ if (!serverName) return { ok: false, secret: `dynamic_clients/${decl.id}` }+ const row = await getDynamicClient(deps.db, deps.encryptionKey, {+ serverNamespace: secretNamespace,+ serverName,+ })+ if (!row) return { ok: false, secret: `dynamic_clients/${serverName}` }+ if (!row.clientSecret) {+ return { ok: false, secret: `dynamic_clients/${serverName}/client_secret` }+ }+ return { ok: true, cred: { clientId: row.clientId, clientSecret: row.clientSecret } }+ }+ // k8s-secret: pre-registered confidential — read both keys from the named Secret.+ const { clientIdRef, clientSecretRef } = source+ let idSecret: Record<string, string>+ try {+ idSecret = await deps.secretReader.read(clientIdRef.name, secretNamespace)+ } catch (err) {+ if (err instanceof SecretNotFoundError) return { ok: false, secret: clientIdRef.name }+ throw err+ }+ const clientId = idSecret[clientIdRef.key]+ if (!clientId) return { ok: false, secret: `${clientIdRef.name}/${clientIdRef.key}` }+ let secSecret: Record<string, string>+ try {+ secSecret = await deps.secretReader.read(clientSecretRef.name, secretNamespace)+ } catch (err) {+ if (err instanceof SecretNotFoundError) return { ok: false, secret: clientSecretRef.name }+ throw err+ }+ const clientSecret = secSecret[clientSecretRef.key]+ if (!clientSecret) return { ok: false, secret: `${clientSecretRef.name}/${clientSecretRef.key}` }+ return { ok: true, cred: { clientId, clientSecret } }+}++export type RemotePostResult =+ | { ok: true; bodyText: string }+ | { ok: false; status?: number; detail: string }++/**+ * POST a form-encoded token/refresh request to a discovery-derived endpoint+ * through the IP-pinned `pinnedFetch` (DEC-17). Adds `content-length` (the pinned+ * `node:https` transport needs an explicit length rather than chunked) on top of+ * the builder's `content-type: application/x-www-form-urlencoded`. Any pin-level+ * failure (kernel-rejected, transport, non-identity encoding) is a fail-closed+ * `ok:false` with a NAME-only detail — never secret material. Shared by exchange+ * + refresh (D4).+ */+export async function postRemoteTokenForm(+ url: string,+ field: string,+ tokenRequest: { headers: Record<string, string>; body: string },+ deps: { resolveDns?: DnsResolver; pinnedTransport?: PinnedTransport; timeoutMs?: number }+): Promise<RemotePostResult> {+ const headers = {+ ...tokenRequest.headers,+ 'content-length': String(Buffer.byteLength(tokenRequest.body)),+ }+ const result = await pinnedFetch(url, field, {+ method: 'POST',+ headers,+ body: tokenRequest.body,+ resolveDns: deps.resolveDns,+ transport: deps.pinnedTransport,+ timeoutMs: deps.timeoutMs ?? 15_000,+ })+ if (!result.ok) return { ok: false, detail: result.error.kind }+ const { status, bodyText } = result.response+ if (status < 200 || status >= 300) return { ok: false, status, detail: bodyText.slice(0, 2000) }+ return { ok: true, bodyText }+}+// ─── helpers ──────────────────────────────────────────────────────────────async function safeReadText(response: Response): Promise<string> {diff --git a/control-api/src/oauth/cimd.ts b/control-api/src/oauth/cimd.tsindex 5667ca33f..3116c22d2 100644--- a/control-api/src/oauth/cimd.ts+++ b/control-api/src/oauth/cimd.ts@@ -2,6 +2,7 @@ import { Router } from 'express'import { config } from '../config.js'import { type Logger, rootLogger } from '../observability/logger.js'import { normalizeConfiguredOrigin } from '../routes/external/oauthCallback.js'+import { REMOTE_CALLBACK_CLIENT_SEGMENT } from './callback.js'/*** Client ID Metadata Document (CIMD, SEP-991), served by control-api as the@@ -40,7 +41,7 @@ const CIMD_PUBLIC_PATH = `/api/v1${CIMD_ROUTE_PATH}`* C2 DCR (`dcr.ts`) derives its `redirect_uris` from the same constant so the CIMD* document and a dynamically-registered client advertise a byte-identical callback.*/-export const REMOTE_CALLBACK_PATH = '/api/v1/oauth-callback/remote'+export const REMOTE_CALLBACK_PATH = `/api/v1/oauth-callback/${REMOTE_CALLBACK_CLIENT_SEGMENT}`/*** Build the frozen CIMD document for a given public `origin` (scheme://host, nodiff --git a/control-api/src/oauth/dcrCleanup.ts b/control-api/src/oauth/dcrCleanup.tsnew file mode 100644index 000000000..b3a9cd3f1--- /dev/null+++ b/control-api/src/oauth/dcrCleanup.ts@@ -0,0 +1,80 @@+import type { DbClient } from '../db.js'+import { pinnedFetch } from '../http/pinnedFetch.js'+import type { DcrDeps } from './dcr.js'+import {+ type DynamicClientKey,+ deleteDynamicClient,+ getDynamicClient,+} from './dynamicClientStore.js'++/**+ * Shared DCR (RFC 7591/7592) client teardown (spec 02 C2/C4, DEC-18). Extracted+ * here once the compensation idiom reached a 4th call site (the mcp-server+ * uninstall) — the install saga's rollback paths (`remoteMcp.ts`) and the+ * uninstall now share ONE implementation (colateral DRY note of C2).+ */++const DCR_DELETE_TIMEOUT_MS = 15_000++/**+ * Best-effort RFC 7592 client-delete against the AS's management endpoint, so a+ * dynamic client we minted does not linger at the AS after a local abort/uninstall.+ * Single-hop pinned DELETE (never re-resolves) with the registration bearer; any+ * failure is swallowed — the local `deleteDynamicClient` is the reliable+ * revocation, this is courtesy cleanup. Never logs the bearer.+ */+export async function bestEffortRfc7592Delete(+ dcrDeps: DcrDeps,+ registrationClientUri: string,+ registrationAccessToken: string+): Promise<void> {+ try {+ await pinnedFetch(registrationClientUri, 'spec.oauth.registrationClientUri', {+ method: 'DELETE',+ headers: { authorization: `Bearer ${registrationAccessToken}` },+ resolveDns: dcrDeps.resolveDns,+ transport: dcrDeps.transport,+ timeoutMs: DCR_DELETE_TIMEOUT_MS,+ })+ } catch {+ // Best-effort; the local store delete is the reliable revocation.+ }+}++export interface DcrTeardownResult {+ /** Rows removed from `dynamic_clients` (0 ⇒ no DCR client for this server — already clean). */+ localRowsDeleted: number+ /** Whether a courtesy RFC 7592 DELETE was attempted (the row carried a management handle). */+ attemptedRemoteDelete: boolean+}++/**+ * Full DCR teardown for a server CR keyed per-server (`owner_kind/namespace/name`):+ * read the stored row, best-effort RFC 7592 DELETE at the AS (courtesy), then the+ * reliable local `deleteDynamicClient`. Idempotent — a server with no DCR client+ * (0 rows) is a clean no-op. Reads never mask the local delete: if the store read+ * throws (e.g. a decrypt error), the local delete still runs.+ */+export async function cleanupDynamicClientForServer(+ db: DbClient,+ encryptionKey: Buffer,+ dcrDeps: DcrDeps,+ key: DynamicClientKey+): Promise<DcrTeardownResult> {+ let registrationClientUri: string | undefined+ let registrationAccessToken: string | undefined+ try {+ const row = await getDynamicClient(db, encryptionKey, key)+ registrationClientUri = row?.registrationClientUri+ registrationAccessToken = row?.registrationAccessToken+ } catch {+ // Read failed — fall through to the reliable local delete below.+ }+ let attemptedRemoteDelete = false+ if (registrationClientUri && registrationAccessToken) {+ attemptedRemoteDelete = true+ await bestEffortRfc7592Delete(dcrDeps, registrationClientUri, registrationAccessToken)+ }+ const localRowsDeleted = await deleteDynamicClient(db, key)+ return { localRowsDeleted, attemptedRemoteDelete }+}diff --git a/control-api/src/oauth/mcpServerOAuthSpec.ts b/control-api/src/oauth/mcpServerOAuthSpec.tsindex 535804e9a..0ba9c0205 100644--- a/control-api/src/oauth/mcpServerOAuthSpec.ts+++ b/control-api/src/oauth/mcpServerOAuthSpec.ts@@ -11,6 +11,7 @@* All read the SAME fields the SAME way and derive the SAME `oauth_grants` key* (`buildMcpServerGrantKey`), so the rule lives here once.*/+import type { OAuthClientDecl, RemoteClientRouting, ServerOAuthSecretSource } from './callback.js'import type { OAuthGrantKey } from './store.js'export interface McpServerOAuthDecl {@@ -21,6 +22,16 @@ export interface McpServerOAuthDecl {scopes?: unknownbackgroundAccess?: unknowngrantScope?: unknown+ // Remote MCP-OAuth lane (`source:'remote'`, C1.5/C2/C3). Untrusted CR data →+ // every field is validated before use; a malformed remote block fails closed.+ source?: unknown+ clientMode?: unknown+ authorizationEndpoint?: unknown+ tokenEndpoint?: unknown+ resource?: unknown+ bearerInBody?: unknown+ supportsRefresh?: unknown+ issForCallback?: unknown}/** Minimal structural shape needed to resolve a server's OAuth grant coordinate. */@@ -123,19 +134,75 @@ export function buildMcpServerGrantKey(* 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- }+ /**+ * The `oauthClients[]`-compatible client decl. For BAKED (no `source`) it is+ * byte-identical to the confidential-K8s shape (id/provider + both refs). For+ * REMOTE (`source:'remote'`) it carries `remote` routing + a `secretSource`+ * discriminator and OMITS `clientSecretRef`/`clientIdRef` unless the mode is+ * pre-registered-confidential (`k8s-secret`).+ */+ decl: OAuthClientDeclgrantScope: GrantScope/** Authoritative Context (spec.contextRef); undefined if absent. */contextRef?: string}+/** Extract + type-validate the remote routing block from an untrusted `spec.oauth`. */+function extractRemoteRouting(oauth: McpServerOAuthDecl): RemoteClientRouting | null {+ const clientMode = oauth.clientMode+ if (clientMode !== 'public' && clientMode !== 'confidential') return null+ const authorizationEndpoint = oauth.authorizationEndpoint+ const tokenEndpoint = oauth.tokenEndpoint+ if (typeof authorizationEndpoint !== 'string' || authorizationEndpoint.length === 0) return null+ if (typeof tokenEndpoint !== 'string' || tokenEndpoint.length === 0) return null+ const resource =+ typeof oauth.resource === 'string' && oauth.resource.length > 0 ? oauth.resource : undefined+ const issForCallback =+ typeof oauth.issForCallback === 'string' && oauth.issForCallback.length > 0+ ? oauth.issForCallback+ : undefined+ return {+ authorizationEndpoint,+ tokenEndpoint,+ resource,+ clientMode,+ bearerInBody: oauth.bearerInBody === true,+ supportsRefresh: oauth.supportsRefresh === true,+ issForCallback,+ }+}++/** Read a nested `{name,key}` ref, returning null unless BOTH are non-empty strings. */+function readRef(+ ref: { name?: unknown; key?: unknown } | undefined+): { name: string; key: string } | null {+ if (!ref || typeof ref.name !== 'string' || typeof ref.key !== 'string') return null+ return { name: ref.name, key: ref.key }+}++/**+ * Classify a remote client's secret source (DEC-18): refs present ⇒ K8s Secret+ * (pre-registered confidential); no refs + confidential ⇒ encrypted DCR store;+ * no refs + public ⇒ no secret.+ */+function resolveRemoteSecretSource(+ oauth: McpServerOAuthDecl,+ clientMode: 'public' | 'confidential'+): ServerOAuthSecretSource {+ const clientIdRef = readRef(oauth.clientIdRef)+ const clientSecretRef = readRef(oauth.clientSecretRef)+ if (clientIdRef && clientSecretRef) {+ return { kind: 'k8s-secret', clientIdRef, clientSecretRef }+ }+ return clientMode === 'confidential' ? { kind: 'dcr-store' } : { kind: 'public' }+}++function normalizeScopes(scopes: unknown): string[] | undefined {+ return Array.isArray(scopes)+ ? scopes.filter((s): s is string => typeof s === 'string')+ : undefined+}+/*** Resolve a McpServer's full OAuth subject (decl + grant routing) for the U5* consent flow. Returns null when the server carries no usable OAuth@@ -143,48 +210,63 @@ export interface ResolvedServerOAuthSubject {* closed. Same field-reading rule as {@link resolveServerOAuth} — kept here so* the authorize-URL minter and the callback never drift (D4).*- * NOTE (E-19.2, deliberate deferral): the refresh-path reader- * `normalizeMcpServerOwnerDecl` (routes/mcpOauth.ts) already treats an absent- * `clientSecretRef` as a valid public client. This mint/callback resolver stays- * confidential-only ON PURPOSE for now: a public mcp-server is not representable- * in this phase (the CRD still lists `clientSecretRef` as required and there is- * no `'generic'` provider), so no reachable server diverges between the two- * readers today. Aligning this resolver (+ making- * `ResolvedServerOAuthSubject.decl.clientSecretRef` optional) lands together with- * the CRD/`'generic'` work, where the public-client path first becomes reachable.+ * Two lanes (C4/DEC-23), keyed uniformly by `oauth.id` (the install backfills it+ * for every remote mode, so the grant coordinate is uniform):+ * - BAKED (no `source`): behaves EXACTLY as before — confidential-K8s, both+ * refs required, `provider` required; returns the same decl shape. A public+ * baked mcp-server is still not representable, so nothing reachable changes.+ * - REMOTE (`source:'remote'`): `provider` is NOT required (no baked adapter);+ * the decl carries `remote` routing + a `secretSource` discriminator and+ * drops `clientSecretRef`/`clientIdRef` unless the mode is+ * pre-registered-confidential. Stays PURE/synchronous — the caller reads the+ * secret (K8s Secret or `getDynamicClient`) per `secretSource`.*/export function resolveServerOAuthSubject(server: McpServerOAuthSpecInput): ResolvedServerOAuthSubject | null {const oauth = server.spec?.oauthif (!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++ // ─── Remote lane (`source:'remote'`) ─────────────────────────────────────+ if (oauth.source === 'remote') {+ const remote = extractRemoteRouting(oauth)+ if (!remote) return null+ const secretSource = resolveRemoteSecretSource(oauth, remote.clientMode)+ const decl: OAuthClientDecl = {+ id: oauth.id,+ // No baked provider on the remote lane; exchange/refresh/authorize branch on+ // `remote` before any provider-adapter lookup. `'remote'` is the persisted /+ // displayed label.+ provider: 'remote',+ scopes: normalizeScopes(oauth.scopes),+ backgroundAccess: oauth.backgroundAccess === true,+ remote,+ secretSource,+ }+ if (secretSource.kind === 'k8s-secret') {+ decl.clientIdRef = secretSource.clientIdRef+ decl.clientSecretRef = secretSource.clientSecretRef+ }+ return { decl, grantScope, contextRef }+ }++ // ─── Baked lane (byte-identical to before) ───────────────────────────────+ if (typeof oauth.provider !== 'string' || oauth.provider.length === 0) return null+ const clientIdRef = readRef(oauth.clientIdRef)+ const clientSecretRef = readRef(oauth.clientSecretRef)+ if (!clientIdRef || !clientSecretRef) return nullreturn {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,+ clientIdRef,+ clientSecretRef,+ scopes: normalizeScopes(oauth.scopes),backgroundAccess: oauth.backgroundAccess === true,},grantScope,diff --git a/control-api/src/oauth/providers.ts b/control-api/src/oauth/providers.tsindex 07469939e..c873af98b 100644--- a/control-api/src/oauth/providers.ts+++ b/control-api/src/oauth/providers.ts@@ -617,6 +617,43 @@ function appendResource(request: TokenRequest, resource?: string): TokenRequestreturn { ...request, body: `${request.body}&resource=${encodeURIComponent(resource)}` }}+/** Input for a remote authorize URL — public client, always PKCE S256 (spec §6 #3). */+export interface RemoteAuthorizeUrlInput {+ clientId: string+ redirectUri: string+ state: string+ scopes: string[]+ /** S256 `code_challenge` — mandatory for the remote lane (fail-closed on no-S256, §6 #3). */+ codeChallenge: string+ /** RFC 8707 resource indicator, appended when present. */+ resource?: string+}++/**+ * Build the authorize URL for the remote MCP-OAuth lane against a discovery-pinned+ * `authorizationEndpoint`. Standard OAuth 2.1 auth-code + PKCE S256 + RFC 8707+ * `resource`. No secret material ever rides the authorize URL (public client:+ * only the public `client_id`). Wrapper over `urlEncode`, not a baked adapter — the+ * 8 baked authorize builders stay byte-identical.+ */+export function buildRemoteAuthorizeUrl(+ authorizationEndpoint: string,+ input: RemoteAuthorizeUrlInput+): string {+ const params: Record<string, string> = {+ response_type: 'code',+ client_id: input.clientId,+ redirect_uri: input.redirectUri,+ state: input.state,+ code_challenge: input.codeChallenge,+ code_challenge_method: 'S256',+ }+ if (input.scopes.length > 0) params.scope = input.scopes.join(' ')+ if (input.resource) params.resource = input.resource+ const sep = authorizationEndpoint.includes('?') ? '&' : '?'+ return `${authorizationEndpoint}${sep}${urlEncode(params)}`+}+/*** Build a remote token-exchange POST against a discovered `tokenEndpoint`, as a* public client (omits `client_secret` when `input.clientSecret` is absent — thediff --git a/control-api/src/oauth/tokenHelper.ts b/control-api/src/oauth/tokenHelper.tsindex 4011fb46b..e8732a9a4 100644--- a/control-api/src/oauth/tokenHelper.ts+++ b/control-api/src/oauth/tokenHelper.ts@@ -1,15 +1,22 @@import type { DbClient } from '../db.js'+import type { PinnedTransport } from '../http/pinnedFetch.js'+import type { DnsResolver } from '../http/validateMcpServerSpec.js'import {+ type OAuthClientDecl,RecipeNotFoundError,type RecipeReader,type RecipeWithOAuthClients,SecretNotFoundError,type SecretReader,+ postRemoteTokenForm,+ resolveRemoteClientCredential,} from './callback.js'import {type ParsedTokenResponse,+ buildRemoteRefreshRequest,getOAuthProviderAdapter,isKnownOAuthProvider,+ parseRemoteTokenResponse,} from './providers.js'import { type OAuthGrantKey, getOAuthGrant, refreshOAuthGrantTokens } from './store.js'@@ -43,6 +50,13 @@ export interface GetAccessTokenDeps {refreshBufferMs?: number/** Token-exchange timeout. Default 15s. */refreshTimeoutMs?: number+ /**+ * Remote lane only: injectable DNS resolver + pinned transport for the+ * IP-pinned refresh POST (DEC-17). Production leaves both undefined (real+ * resolve + `node:https`); the baked lane never touches them (keeps `fetchFn`).+ */+ resolveDns?: DnsResolver+ pinnedTransport?: PinnedTransport}export type GetAccessTokenResult =@@ -85,22 +99,41 @@ export async function getAccessToken(const decl = recipe.spec?.oauthClients?.find(c => c.id === input.oauthClientId)if (!decl) return { kind: 'unknown_oauth_client' }++ // Remote lane (`source:'remote'`): discovery-derived refresh over the IP-pinned+ // transport (DEC-17), public token client, credentials per `secretSource`. The+ // baked provider-adapter path is below (unchanged).+ if (decl.remote) {+ // no-refresh derived from pinned metadata (D-8, fail-closed): the AS never+ // advertised `refresh_token`, so treat as "needs reauth" rather than POST a+ // refresh — surfaces `connect_required` in mcp-host. Derived from the flag,+ // NOT heuristically from token presence.+ if (!decl.remote.supportsRefresh) return { kind: 'no_grant' }+ return refreshRemoteGrant(grant.refreshToken, decl, input, deps)+ }+if (!isKnownOAuthProvider(decl.provider)) {return { kind: 'unsupported_provider', provider: decl.provider }}+ // Baked/recipe lane: clientIdRef always present (only remote omits it).+ if (!decl.clientIdRef) {+ return { kind: 'secret_missing', secret: `${decl.id}/client_id` }+ }+ const clientIdRef = decl.clientIdRef+let clientIdSecret: Record<string, string>try {- clientIdSecret = await deps.secretReader.read(decl.clientIdRef.name, input.recipeNamespace)+ clientIdSecret = await deps.secretReader.read(clientIdRef.name, input.recipeNamespace)} catch (err) {if (err instanceof SecretNotFoundError) {- return { kind: 'secret_missing', secret: decl.clientIdRef.name }+ return { kind: 'secret_missing', secret: clientIdRef.name }}throw err}- const clientId = clientIdSecret[decl.clientIdRef.key]+ const clientId = clientIdSecret[clientIdRef.key]if (!clientId) {- return { kind: 'secret_missing', secret: `${decl.clientIdRef.name}/${decl.clientIdRef.key}` }+ return { kind: 'secret_missing', secret: `${clientIdRef.name}/${clientIdRef.key}` }}// Public client (E-19.2): no clientSecretRef ⇒ refresh without a client_secret.@@ -183,3 +216,74 @@ export async function getAccessToken(: undefinedreturn { kind: 'ok', accessToken: parsed.accessToken, expiresAt }}++/**+ * Remote-lane refresh (`source:'remote'`, `supportsRefresh:true`). Public token+ * client, credentials per `secretSource`, IP-pinned POST to the discovery-derived+ * token endpoint (DEC-17). Persists via the SAME `refreshOAuthGrantTokens` UPDATE+ * (never resurrects a concurrently-deleted grant). `refreshToken` is already+ * narrowed non-null by the caller.+ */+async function refreshRemoteGrant(+ refreshToken: string,+ decl: OAuthClientDecl,+ input: GetAccessTokenInput,+ deps: GetAccessTokenDeps+): Promise<GetAccessTokenResult> {+ const remote = decl.remote+ if (!remote) return { kind: 'no_grant' }+ const credResult = await resolveRemoteClientCredential(+ decl,+ input.recipeNamespace,+ input.recipeName,+ {+ db: deps.db,+ encryptionKey: deps.encryptionKey,+ secretReader: deps.secretReader,+ }+ )+ if (!credResult.ok) return { kind: 'secret_missing', secret: credResult.secret }++ const refreshRequest = buildRemoteRefreshRequest(+ remote.tokenEndpoint,+ {+ refreshToken,+ clientId: credResult.cred.clientId,+ clientSecret: credResult.cred.clientSecret,+ },+ remote.resource+ )+ const posted = await postRemoteTokenForm(+ remote.tokenEndpoint,+ 'spec.oauth.tokenEndpoint',+ refreshRequest,+ {+ resolveDns: deps.resolveDns,+ pinnedTransport: deps.pinnedTransport,+ timeoutMs: deps.refreshTimeoutMs,+ }+ )+ if (!posted.ok) return { kind: 'refresh_failed', status: posted.status, detail: posted.detail }++ let parsed: ParsedTokenResponse+ try {+ parsed = parseRemoteTokenResponse(JSON.parse(posted.bodyText))+ } catch (err) {+ return { kind: 'refresh_failed', detail: (err as Error).message }+ }++ const refreshed = await refreshOAuthGrantTokens(deps.db, deps.encryptionKey, {+ ...input,+ provider: 'remote',+ accessToken: parsed.accessToken,+ refreshToken: parsed.refreshToken ?? refreshToken,+ accessTokenExpiresInSec: parsed.expiresIn,+ })+ if (!refreshed.updated) return { kind: 'no_grant' }++ const expiresAt =+ typeof parsed.expiresIn === 'number'+ ? new Date(Date.now() + parsed.expiresIn * 1000)+ : undefined+ return { kind: 'ok', accessToken: parsed.accessToken, expiresAt }+}diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.tsindex 980db2b92..5bf3d6291 100644--- a/control-api/src/routes/admin/remoteMcp.ts+++ b/control-api/src/routes/admin/remoteMcp.ts@@ -5,18 +5,18 @@ import { type DbClient, pool } from '../../db.js'import { asyncHandler } from '../../http/asyncHandler.js'import { extractK8sError } from '../../http/k8sError.js'import { enforceNamespace } from '../../http/namespaceAudit.js'-import { pinnedFetch } from '../../http/pinnedFetch.js'import { RFC1123_RE } from '../../http/rfc1123.js'import { validateOAuthEndpointUrl } from '../../http/validateMcpServerSpec.js'import { K8sGateway } from '../../k8s.js'import { type UiAuthedRequest } from '../../middleware/controlUIAuth.js'-import { REMOTE_CALLBACK_PATH } from '../../oauth/cimd.js'+import { REMOTE_CALLBACK_PATH, buildCimdDocument } from '../../oauth/cimd.js'import {type DcrDeps,type DcrMintHandle,buildDcrRequest,registerDynamicClient,} from '../../oauth/dcr.js'+import { bestEffortRfc7592Delete } from '../../oauth/dcrCleanup.js'import { type DiscoveryResult, discoverRemoteOAuth } from '../../oauth/discovery.js'import {type DynamicClientKey,@@ -126,7 +126,7 @@ function derivedScopes(result: DiscoveryResult): string[] {return result.prm.scopes_supported ?? result.as.scopes_supported ?? []}-function buildRemoteOAuthSpec(+export function buildRemoteOAuthSpec(result: DiscoveryResult,opts: {clientMode: 'public' | 'confidential'@@ -135,6 +135,10 @@ function buildRemoteOAuthSpec(clientSecretName?: string/** Set for DCR (AS-assigned client_id); mirrored to `oauth.id`. Omits Secret refs. */dynamicClientId?: string+ /** CIMD public: the platform self-URL client_id (from `cimd.ts`) — DEC-23 backfill. */+ cimdClientId?: string+ /** Pre-registered confidential: operator-supplied plaintext client_id — DEC-23 backfill. */+ preRegisteredClientId?: string}): RemoteOAuthSpec {const oauth: RemoteOAuthSpec = {@@ -155,11 +159,18 @@ function buildRemoteOAuthSpec(// Secret (pre-registered). No refs + clientMode 'confidential' + `id` set ⇒ read// the secret from the encrypted `dynamic_clients` store (DCR). The two sources// are mutually exclusive per install mode, so we set at most one here.+ //+ // DEC-23 backfill: EVERY remote mode carries `oauth.id` (the public client_id) so+ // the resolver keys grants uniformly. DCR uses the AS assignment; CIMD-public the+ // platform self-URL; pre-registered the operator's plaintext client_id.if (opts.dynamicClientId) {oauth.id = opts.dynamicClientId} else if (opts.clientMode === 'confidential' && opts.clientSecretName) {oauth.clientIdRef = { name: opts.clientSecretName, key: 'client_id' }oauth.clientSecretRef = { name: opts.clientSecretName, key: 'client_secret' }+ if (opts.preRegisteredClientId) oauth.id = opts.preRegisteredClientId+ } else if (opts.cimdClientId) {+ oauth.id = opts.cimdClientId}return oauth}@@ -175,33 +186,6 @@ function deriveDcrClientMode(result: DiscoveryResult): 'public' | 'confidential'return Array.isArray(methods) && methods.includes('none') ? 'public' : 'confidential'}-const DCR_TIMEOUT_MS = 15_000--/**- * Best-effort RFC 7592 client-delete against the AS's management endpoint, so a- * dynamic client we minted but then failed to fully install does not linger at the- * AS. Single-hop pinned DELETE with the registration bearer; any failure is- * swallowed (the local `deleteDynamicClient` is the reliable revocation, this is- * courtesy cleanup). Never logs the bearer.- */-async function bestEffortRfc7592Delete(- dcrDeps: DcrDeps,- registrationClientUri: string,- registrationAccessToken: string-): Promise<void> {- try {- await pinnedFetch(registrationClientUri, 'spec.oauth.registrationClientUri', {- method: 'DELETE',- headers: { authorization: `Bearer ${registrationAccessToken}` },- resolveDns: dcrDeps.resolveDns,- transport: dcrDeps.transport,- timeoutMs: DCR_TIMEOUT_MS,- })- } catch {- // Best-effort; the local store delete is the reliable revocation.- }-}-const REMOTE_MCP_EGRESS_PROXY_IMAGE =process.env.CONTROL_API_REMOTE_MCP_EGRESS_PROXY_IMAGE || 'clerum/nginx-egress-proxy:0.1.0'const REMOTE_MCP_PROXY_PORT = 3000@@ -594,11 +578,34 @@ export function createAdminRemoteMcpRouter(const clientSecretName =body.mode === 'pre-registered' ? `${serverName}-oauth-client` : undefined+ // DEC-23 backfill of `oauth.id` for the non-DCR modes (DCR already carries it+ // via `dcrClientId`). CIMD reuses the platform self-URL client_id published by+ // `cimd.ts` (never re-derived); pre-registered mirrors the operator's+ // plaintext client_id (non-secret, already stored in the Secret in clear).+ let cimdClientId: string | undefined+ let preRegisteredClientId: string | undefined+ if (body.mode === 'cimd') {+ const cimdOrigin = normalizeConfiguredOrigin(config.oauthCallbackBaseUrl)+ if (cimdOrigin === null) {+ log.error(+ { event: 'remote_oauth_cimd_callback_unconfigured', serverName },+ 'cimd install requires a configured public callback base URL'+ )+ res.status(503).json({ error: 'callback_base_url_unconfigured' })+ return+ }+ cimdClientId = buildCimdDocument(cimdOrigin).client_id+ } else if (body.mode === 'pre-registered') {+ preRegisteredClientId = body.clientId as string+ }+const oauthSpec = buildRemoteOAuthSpec(discovery, {clientMode,grantScope,clientSecretName,...(dcrClientId ? { dynamicClientId: dcrClientId } : {}),+ ...(cimdClientId ? { cimdClientId } : {}),+ ...(preRegisteredClientId ? { preRegisteredClientId } : {}),})const mcpServerSpec: Record<string, unknown> = {diff --git a/control-api/src/routes/admin/resources.ts b/control-api/src/routes/admin/resources.tsindex a244c464c..a85918ead 100644--- a/control-api/src/routes/admin/resources.ts+++ b/control-api/src/routes/admin/resources.ts@@ -4,6 +4,7 @@ import {type DbClient,advisoryLockModelNames,boundCarrierTransactionIdleTimeout,+ pool,withTransaction,} from '../../db.js'import { asyncHandler } from '../../http/asyncHandler.js'@@ -11,6 +12,9 @@ import { enforceNamespace } from '../../http/namespaceAudit.js'import { validateCommunicationChannelSpec } from '../../http/validateCommunicationChannelSpec.js'import { validateMcpServerSpecPreflight } from '../../http/validateMcpServerSpec.js'import { K8sGateway } from '../../k8s.js'+import { cleanupDynamicClientForServer } from '../../oauth/dcrCleanup.js'+import { deriveOAuthEncryptionKey } from '../../oauth/encryption.js'+import { rootLogger } from '../../observability/logger.js'import { stripHookRefFromHosts } from '../../services/hostGuardrailRefs.js'import {K8sConflictError,@@ -470,6 +474,11 @@ function hostValidationDeps(db: DbClient) {export function createAdminResourcesRouter(gateway: K8sGateway): Router {const router = Router()+ const log = rootLogger.child({ module: 'admin-resources' })+ // Reliable local revocation of a remote server's DCR client on uninstall; the+ // AS-side RFC 7592 delete is courtesy (real pinned transport in production).+ const oauthEncryptionKey = deriveOAuthEncryptionKey(config.oauthEncryptionKey)+ const dcrDb: DbClient = { query: (text, values) => pool.query(text, values) }// Middleware: enforce namespace per resource type and audit any injection attempt.// Uses enforceNamespace() consistently with all other admin routers.@@ -1022,16 +1031,27 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {if (plural === 'communicationchannels' && ccSecretRefName) {try {await gateway.deleteSecret(ccSecretRefName, ns)- console.log(`[Admin] Deleted CC credentials Secret "${ccSecretRefName}" in ${ns}`)+ log.info(+ { event: 'cc_credentials_secret_deleted', secretName: ccSecretRefName, namespace: ns },+ 'deleted CC credentials secret'+ )} catch (err) {if (extractK8sStatusCode(err) === 404) {- console.log(`[Admin] CC credentials Secret "${ccSecretRefName}" already gone in ${ns}`)+ log.info(+ { event: 'cc_credentials_secret_absent', secretName: ccSecretRefName, namespace: ns },+ 'CC credentials secret already gone'+ )} else {// CC is already gone; log and swallow so the operator gets a 200// and can clean the orphan Secret manually if needed.- console.error(- `[Admin] CC delete succeeded but credentials Secret "${ccSecretRefName}" cleanup failed:`,- err+ log.error(+ {+ event: 'cc_credentials_secret_cleanup_failed',+ secretName: ccSecretRefName,+ namespace: ns,+ err,+ },+ 'CC delete succeeded but credentials secret cleanup failed')}}@@ -1041,10 +1061,47 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {const contextsNs = resourceNamespace('contexts')try {await gateway.deleteSecret(`${name}-credentials`, ns)- console.log(`[Admin] Deleted credentials secret "${name}-credentials" in ${ns}`)+ log.info(+ { event: 'mcpserver_credentials_secret_deleted', name, namespace: ns },+ 'deleted mcp-server credentials secret'+ )} catch (err) {- console.log(- `[Admin] No credentials secret to delete for "${name}": ${err instanceof Error ? err.message : String(err)}`+ log.info(+ { event: 'mcpserver_credentials_secret_absent', name, namespace: ns, err },+ 'no mcp-server credentials secret to delete'+ )+ }++ // Remote DCR client teardown (K, DEC-18): revoke the encrypted+ // `dynamic_clients` row (reliable) + best-effort RFC 7592 delete at the AS+ // (courtesy). Keyed per-server-CR; idempotent (0 rows ⇒ not a DCR server).+ // Never blocks or fails the uninstall — the CR is already deleted.+ try {+ const teardown = await cleanupDynamicClientForServer(+ dcrDb,+ oauthEncryptionKey,+ { logger: log },+ {+ ownerKind: 'mcpserver',+ serverNamespace: ns,+ serverName: name,+ }+ )+ if (teardown.localRowsDeleted > 0) {+ log.info(+ {+ event: 'mcpserver_dynamic_client_revoked',+ name,+ namespace: ns,+ attemptedRemoteDelete: teardown.attemptedRemoteDelete,+ },+ 'revoked remote oauth dynamic client on uninstall'+ )+ }+ } catch (err) {+ log.error(+ { event: 'mcpserver_dynamic_client_cleanup_failed', name, namespace: ns, err },+ 'dynamic client cleanup failed on uninstall (CR already deleted)')}@@ -1073,12 +1130,16 @@ export function createAdminResourcesRouter(gateway: K8sGateway): Router {},contextsNs)- console.log(`[Admin] Removed "${name}" from Context "${ctxName}" allowlist`)+ log.info(+ { event: 'mcpserver_removed_from_context', name, context: ctxName },+ 'removed mcp-server from Context allowlist'+ )}}} catch (err) {- console.error(- `[Admin] Failed to clean up Context allowlists for "${name}": ${err instanceof Error ? err.message : String(err)}`+ log.error(+ { event: 'mcpserver_context_allowlist_cleanup_failed', name, err },+ 'failed to clean up Context allowlists for mcp-server')}}diff --git a/control-api/src/routes/internal/oauth.ts b/control-api/src/routes/internal/oauth.tsindex 4b76c8013..4be4768ff 100644--- a/control-api/src/routes/internal/oauth.ts+++ b/control-api/src/routes/internal/oauth.ts@@ -8,6 +8,7 @@ import { buildAuthorizeUrl } from '../../oauth/authorizeUrlHelper.js'import {type McpServerOAuthReader,type McpServerOAuthSubject,+ REMOTE_CALLBACK_CLIENT_SEGMENT,RecipeNotFoundError,type RecipeReader,type RecipeWithOAuthClients,@@ -229,7 +230,18 @@ export function createInternalOAuthRouter(gateway: K8sGateway): Router {}const oauthClientId = resolved.decl.id- const redirectUri = buildPublicCallbackUrl(req, oauthClientId, config.oauthCallbackBaseUrl)+ // Remote lane registers ONE stable redirect_uri (`/oauth-callback/remote`),+ // so the callback URL segment is the reserved constant, NOT the client id —+ // the real binding rides the signed state. Baked keeps the per-client+ // segment. The exchange re-derives the same redirect_uri from this segment.+ const callbackSegment = resolved.decl.remote+ ? REMOTE_CALLBACK_CLIENT_SEGMENT+ : oauthClientId+ const redirectUri = buildPublicCallbackUrl(+ req,+ callbackSegment,+ config.oauthCallbackBaseUrl+ )const result = await buildAuthorizeUrl({diff --git a/control-api/src/routes/mcpOauth.ts b/control-api/src/routes/mcpOauth.tsindex 191e634e6..7d9917163 100644--- a/control-api/src/routes/mcpOauth.ts+++ b/control-api/src/routes/mcpOauth.ts@@ -17,6 +17,7 @@ import {type McpServerOAuthDecl,buildMcpServerGrantKey,resolveServerOAuth,+ resolveServerOAuthSubject,} from '../oauth/mcpServerOAuthSpec.js'import { type OAuthGrantKey, oauthGrantExists } from '../oauth/store.js'import { getAccessToken } from '../oauth/tokenHelper.js'@@ -80,7 +81,18 @@ export function normalizeMcpServerOwnerDecl(server: McpServerResource): RecipeWithOAuthClients | null {const oauth = server.spec?.oauth- if (!oauth || typeof oauth.id !== 'string' || typeof oauth.provider !== 'string') return null+ if (!oauth) return null+ // Remote lane (`source:'remote'`): delegate to the SHARED subject resolver so the+ // refresh reader reads the remote client (public / DCR / pre-registered)+ // IDENTICALLY to the mint + callback (D4 — no drift). The remote decl carries the+ // pinned routing + secretSource that `getAccessToken` branches on.+ if (oauth.source === 'remote') {+ const resolved = resolveServerOAuthSubject(server)+ if (!resolved) return null+ return { metadata: server.metadata, spec: { oauthClients: [resolved.decl] } }+ }+ // Baked lane (unchanged; a public baked client is tolerated per E-19.2).+ if (typeof oauth.id !== 'string' || typeof oauth.provider !== 'string') return nullconst clientIdRef = oauth.clientIdRefif (!clientIdRef || typeof clientIdRef.name !== 'string' || typeof clientIdRef.key !== 'string') {return nulldiff --git a/control-api/src/services/access/mcpInvocable.ts b/control-api/src/services/access/mcpInvocable.tsindex 14f8f3796..ec0e3d8df 100644--- a/control-api/src/services/access/mcpInvocable.ts+++ b/control-api/src/services/access/mcpInvocable.ts@@ -500,8 +500,9 @@ function classifyConnector(server: McpServerCR, grantPresent: ReadonlySet<string}// Provider is the non-secret panel label. Derive it directly from// `spec.oauth.provider`, consistent with the oauth-ness gate above — NOT via- // `resolveServerOAuthSubject`, which additionally requires clientIdRef/- // clientSecretRef and would drop the label for an oauth server missing them.+ // `resolveServerOAuthSubject`, whose baked lane still requires clientIdRef/+ // clientSecretRef (and whose remote lane sets `provider:'remote'`, not the panel+ // label). This gate only needs the grant coordinate (`resolveServerOAuth`).const providerRaw = server.spec?.oauth?.providerconst provider =typeof providerRaw === 'string' && providerRaw.length > 0 ? providerRaw : undefineddiff --git a/control-api/test/oauth.authorizeUrl.remote.test.ts b/control-api/test/oauth.authorizeUrl.remote.test.tsnew file mode 100644index 000000000..8cd9cfa15--- /dev/null+++ b/control-api/test/oauth.authorizeUrl.remote.test.ts@@ -0,0 +1,81 @@+import { describe, expect, it, vi } from 'vitest'+import { type BuildAuthorizeUrlDeps, buildAuthorizeUrl } from '../src/oauth/authorizeUrlHelper.js'+import type { McpServerOAuthReader, McpServerOAuthSubject } from '../src/oauth/callback.js'+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'++/**+ * C4/DEC-23 — the remote authorize-URL mint. The URL is built from the pinned+ * discovery-derived `authorizationEndpoint` with the PUBLIC client_id (`oauth.id`),+ * mandatory PKCE S256, and the RFC 8707 `resource`. No secret material rides the+ * URL and no K8s Secret is read. Subject decl comes from the REAL resolver.+ */++const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'+const MCP_NS = 'mcp-server'+const CLIENT_ID = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'+const REDIRECT_URI = 'https://control.example.com/api/v1/oauth-callback/remote'++function remoteSubject(): McpServerOAuthSubject {+ const resolved = resolveServerOAuthSubject({+ spec: {+ contextRef: 'ctx-A',+ oauth: {+ source: 'remote',+ id: CLIENT_ID,+ clientMode: 'public',+ authorizationEndpoint: 'https://mcp.notion.com/authorize',+ tokenEndpoint: 'https://mcp.notion.com/token',+ issuer: 'https://mcp.notion.com',+ resource: 'https://mcp.notion.com',+ grantScope: 'user',+ scopes: ['read', 'write'],+ bearerInBody: false,+ supportsRefresh: true,+ },+ },+ })+ if (!resolved) throw new Error('fixture: remote resolve returned null')+ return { namespace: MCP_NS, ...resolved }+}++describe('buildAuthorizeUrl — remote mcp subject (DEC-23)', () => {+ it('builds a pinned-endpoint authorize URL with PKCE S256 + resource, no secret read', async () => {+ const secretRead = vi.fn(async () => ({}))+ const mcpServerReader: McpServerOAuthReader = { read: vi.fn(async () => remoteSubject()) }+ const deps: BuildAuthorizeUrlDeps = {+ recipeReader: { read: vi.fn(async () => null) },+ mcpServerReader,+ secretReader: { read: secretRead } as unknown as BuildAuthorizeUrlDeps['secretReader'],+ stateSecret: STATE_SECRET,+ }++ const result = await buildAuthorizeUrl(+ {+ subjectKind: 'mcp',+ mcpServerName: 'notion-remote',+ oauthClientId: CLIENT_ID,+ userId: 'user-9',+ grantKind: 'user',+ background: false,+ redirectUri: REDIRECT_URI,+ },+ deps+ )++ expect(result.kind).toBe('ok')+ if (result.kind !== 'ok') return+ const url = new URL(result.authorizeUrl)+ expect(`${url.origin}${url.pathname}`).toBe('https://mcp.notion.com/authorize')+ expect(url.searchParams.get('response_type')).toBe('code')+ expect(url.searchParams.get('client_id')).toBe(CLIENT_ID)+ expect(url.searchParams.get('redirect_uri')).toBe(REDIRECT_URI)+ expect(url.searchParams.get('code_challenge_method')).toBe('S256')+ expect(url.searchParams.get('code_challenge')).toBeTruthy()+ expect(url.searchParams.get('resource')).toBe('https://mcp.notion.com')+ expect(url.searchParams.get('scope')).toBe('read write')+ expect(url.searchParams.get('state')).toBeTruthy()+ // No secret material, and the client-id Secret was never read (public client).+ expect(url.searchParams.get('client_secret')).toBeNull()+ expect(secretRead).not.toHaveBeenCalled()+ })+})diff --git a/control-api/test/oauth.callback.remote.test.ts b/control-api/test/oauth.callback.remote.test.tsnew file mode 100644index 000000000..58a3bdf0c--- /dev/null+++ b/control-api/test/oauth.callback.remote.test.ts@@ -0,0 +1,236 @@+import { describe, expect, it, vi } from 'vitest'+import type { PinnedRawResponse, PinnedTransportInput } from '../src/http/pinnedFetch.js'+import {+ type CallbackDeps,+ type CallbackInput,+ type McpServerOAuthReader,+ type McpServerOAuthSubject,+ 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'++/**+ * C4/DEC-17 — the REMOTE auth-code exchange goes through the IP-pinned+ * `pinnedFetch`, never `fetchFn`, closing the H2 DNS-rebinding TOCTOU on the+ * discovery-derived token endpoint. Baked stays on `fetchFn`, byte-identical.+ *+ * T3 (rebinding): the remote path resolves+validates the token host ONCE and pins+ * the socket to that IP. This test asserts the connected IP equals the validated+ * IP AND that `pinnedTransport` (not `fetchFn`) was used. Against `baf12e1fa` the+ * remote exchange DOES NOT EXIST (`resolveServerOAuthSubject` returns null for+ * `source:'remote'`, so the callback returns `server_not_found`), so the pinned+ * transport is never invoked and this assertion fails.+ *+ * The remote CR bytes are inline (not from `buildRemoteOAuthSpec`) ON PURPOSE:+ * this file must compile+run against the parent SHA where that producer export+ * does not exist. The producer-derived T1 coverage lives in+ * `oauth.mcpServerOAuthSpec.remote.test.ts`; here the REAL producers exercised are+ * `resolveServerOAuthSubject` (the decl) and `pinnedFetch` (the pin).+ */++const STATE_SECRET = 'test-state-hmac-secret-32-bytes-padding'+const ENCRYPTION_KEY = deriveOAuthEncryptionKey(+ '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'+)+const MCP_NS = 'mcp-server'+const VALIDATED_IP = '93.184.216.34'+const TOKEN_ENDPOINT = 'https://mcp.notion.com/token'++// Shape `buildRemoteOAuthSpec` emits for a CIMD-public remote server (kept inline+// so this file runs against the parent SHA — see file docstring).+function remoteServerCr() {+ return {+ metadata: { name: 'notion-remote', namespace: MCP_NS },+ spec: {+ contextRef: 'ctx-A',+ auth: { type: 'oauth' },+ oauth: {+ source: 'remote',+ id: 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client',+ clientMode: 'public',+ authorizationEndpoint: 'https://mcp.notion.com/authorize',+ tokenEndpoint: TOKEN_ENDPOINT,+ issuer: 'https://mcp.notion.com',+ resource: 'https://mcp.notion.com',+ grantScope: 'user',+ scopes: ['read'],+ bearerInBody: false,+ supportsRefresh: true,+ },+ },+ }+}++const REMOTE_CLIENT_ID = remoteServerCr().spec.oauth.id++/** Real reader → real `resolveServerOAuthSubject` (null at parent for remote). */+function remoteReader(): McpServerOAuthReader {+ return {+ read: vi.fn(async () => {+ const resolved = resolveServerOAuthSubject(remoteServerCr())+ if (!resolved) return null+ return { namespace: MCP_NS, ...resolved } as McpServerOAuthSubject+ }),+ }+}++/** A pinned transport that records the URL + the IP the socket would connect to. */+function recordingTransport(responseJson: string, status = 200) {+ const calls: {+ url: string+ connectedIP?: string+ body?: string+ headers: Record<string, string>+ }[] = []+ const transport = async (input: PinnedTransportInput): Promise<PinnedRawResponse> => {+ let connectedIP: string | undefined+ input.lookup(+ 'mcp.notion.com',+ { all: true } as never,+ ((err, addrs) => {+ if (!err && Array.isArray(addrs)) connectedIP = addrs[0]?.address+ }) as never+ )+ calls.push({ url: input.url, connectedIP, body: input.body, headers: input.headers })+ return { status, headers: { 'content-type': 'application/json' }, bodyText: responseJson }+ }+ return { transport, calls }+}++function remoteState() {+ // The signed state binds the REAL client id; the URL segment is the reserved+ // stable `remote` (CIMD/DCR register one fixed redirect_uri).+ return signOAuthState(STATE_SECRET, {+ subjectKind: 'mcp',+ mcpServerName: 'notion-remote',+ userId: 'user-9',+ oauthClientId: REMOTE_CLIENT_ID,+ grantKind: 'user',+ background: false,+ } as Parameters<typeof signOAuthState>[1])+}++function remoteInput(): CallbackInput {+ return {+ oauthClientId: 'remote', // stable segment, not the client id+ code: 'AUTH_CODE',+ state: remoteState(),+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/remote',+ }+}++describe('handleOAuthCallback — remote exchange is IP-pinned (DEC-17, T3)', () => {+ it('exchanges via pinnedTransport, connects to the validated IP, never touches fetchFn', async () => {+ const db = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 1 }) }+ const fetchFn = vi.fn(async () => {+ throw new Error('remote lane must NOT use fetchFn (DEC-17)')+ })+ const { transport, calls } = recordingTransport(+ JSON.stringify({ access_token: 'REMOTE-AT', refresh_token: 'REMOTE-RT', expires_in: 3600 })+ )++ const deps: CallbackDeps = {+ db: db as unknown as CallbackDeps['db'],+ recipeReader: { read: vi.fn(async () => null) },+ mcpServerReader: remoteReader(),+ userContextsReader: vi.fn(async () => ({ contextIds: ['ctx-A'] })),+ secretReader: { read: vi.fn(async () => ({})) } as unknown as CallbackDeps['secretReader'],+ fetchFn: fetchFn as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey: ENCRYPTION_KEY,+ resolveDns: async () => [VALIDATED_IP],+ pinnedTransport: transport,+ }++ const result = await handleOAuthCallback(remoteInput(), deps)++ // Observable outcome: a grant was persisted with provider 'remote'.+ expect(result.kind).toBe('ok')+ expect(fetchFn).not.toHaveBeenCalled()+ expect(calls).toHaveLength(1)+ // T3 core: the socket connected to the IP the kernel validated — no re-resolve.+ expect(calls[0].url).toBe(TOKEN_ENDPOINT)+ expect(calls[0].connectedIP).toBe(VALIDATED_IP)+ // Public client → form body carries client_id + PKCE verifier, no client_secret.+ expect(calls[0].headers['content-type']).toBe('application/x-www-form-urlencoded')+ expect(calls[0].headers['content-length']).toBe(String(Buffer.byteLength(calls[0].body ?? '')))+ expect(calls[0].body).toContain(`client_id=${encodeURIComponent(REMOTE_CLIENT_ID)}`)+ expect(calls[0].body).toContain('code_verifier=')+ expect(calls[0].body).not.toContain('client_secret=')++ const [sql, params] = db.query.mock.calls[0] as [string, unknown[]]+ expect(sql).toContain('INSERT INTO oauth_grants')+ expect(params[0]).toBe('mcpserver')+ expect(params[4]).toBe(REMOTE_CLIENT_ID)+ expect(params[5]).toBe('remote') // provider label+ })+})++describe('baked mcp exchange stays on fetchFn (byte-identical, T5c)', () => {+ it('uses fetchFn and never the pinned transport for a baked server', async () => {+ const bakedServer = {+ metadata: { name: 'gdrive', namespace: MCP_NS },+ spec: {+ contextRef: 'ctx-A',+ auth: { type: 'oauth' },+ oauth: {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'google-creds', key: 'client-id' },+ clientSecretRef: { name: 'google-creds', key: 'client-secret' },+ scopes: ['drive'],+ backgroundAccess: false,+ },+ },+ }+ const resolved = resolveServerOAuthSubject(bakedServer)+ if (!resolved) throw new Error('fixture: baked resolve returned null')+ const subject = { namespace: MCP_NS, ...resolved } as McpServerOAuthSubject++ const db = { query: vi.fn().mockResolvedValue({ rows: [], rowCount: 1 }) }+ const fetchFn = vi.fn(async () => ({+ ok: true,+ status: 200,+ json: async () => ({ access_token: 'AT', refresh_token: 'RT', expires_in: 3600 }),+ text: async () => '',+ }))+ const pinnedTransport = vi.fn(async () => {+ throw new Error('baked lane must NOT use pinnedTransport')+ })++ const deps: CallbackDeps = {+ db: db as unknown as CallbackDeps['db'],+ recipeReader: { read: vi.fn(async () => null) },+ mcpServerReader: { read: vi.fn(async () => subject) },+ userContextsReader: vi.fn(async () => ({ contextIds: ['ctx-A'] })),+ secretReader: {+ read: vi.fn(async () => ({ 'client-id': 'CID', 'client-secret': 'CSEC' })),+ } as unknown as CallbackDeps['secretReader'],+ fetchFn: fetchFn as unknown as typeof fetch,+ stateSecret: STATE_SECRET,+ encryptionKey: ENCRYPTION_KEY,+ pinnedTransport,+ }++ const input: CallbackInput = {+ oauthClientId: 'google-drive',+ code: 'AUTH_CODE',+ state: signOAuthState(STATE_SECRET, {+ subjectKind: 'mcp',+ mcpServerName: 'gdrive',+ userId: 'user-9',+ oauthClientId: 'google-drive',+ grantKind: 'user',+ background: false,+ } as Parameters<typeof signOAuthState>[1]),+ redirectUri: 'https://control.example.com/api/v1/oauth-callback/google-drive',+ }++ const result = await handleOAuthCallback(input, deps)+ expect(result.kind).toBe('ok')+ expect(fetchFn).toHaveBeenCalledTimes(1)+ expect(pinnedTransport).not.toHaveBeenCalled()+ })+})diff --git a/control-api/test/oauth.dcrCleanup.test.ts b/control-api/test/oauth.dcrCleanup.test.tsnew file mode 100644index 000000000..3dbf454f7--- /dev/null+++ b/control-api/test/oauth.dcrCleanup.test.ts@@ -0,0 +1,98 @@+import { describe, expect, it } from 'vitest'+import { bestEffortRfc7592Delete, cleanupDynamicClientForServer } from '../src/oauth/dcrCleanup.js'+import { getDynamicClient, upsertDynamicClient } from '../src/oauth/dynamicClientStore.js'+import { deriveOAuthEncryptionKey } from '../src/oauth/encryption.js'+import { makeDcrTransport, makeInMemoryDynamicClientsDb } from './fixtures/remoteOAuthDiscovery.js'++/**+ * C4/K (DEC-18) — uninstall teardown of a remote server's DCR client. The row is+ * written by the REAL store (`upsertDynamicClient`, T1 — encrypted envelope never+ * hand-built) and the RFC 7592 DELETE goes through the injected pinned transport.+ * Idempotent: a non-DCR server is a clean no-op.+ */++const ENC = deriveOAuthEncryptionKey(+ '00112233445566778899aabbccddeeff00112233445566778899aabbccddeeff'+)+const PUBLIC_IP = async () => ['93.184.216.34']+const KEY = {+ ownerKind: 'mcpserver' as const,+ serverNamespace: 'mcp-server',+ serverName: 'notion-remote',+}++describe('cleanupDynamicClientForServer (uninstall)', () => {+ it('revokes the local row AND attempts the best-effort RFC 7592 delete', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ await upsertDynamicClient(db, ENC, {+ ...KEY,+ issuer: 'https://mcp.notion.com',+ clientId: 'dcr-client-123',+ clientMode: 'confidential',+ clientSecret: 'shh',+ registrationAccessToken: 'reg-bearer-xyz',+ registrationClientUri: 'https://mcp.notion.com/register/dcr-client-123',+ })++ const { transport, calls } = makeDcrTransport({ responseJson: '' })+ const result = await cleanupDynamicClientForServer(+ db,+ ENC,+ { transport, resolveDns: PUBLIC_IP },+ KEY+ )++ expect(result).toEqual({ localRowsDeleted: 1, attemptedRemoteDelete: true })+ // Local row gone.+ expect(await getDynamicClient(db, ENC, KEY)).toBeNull()+ // RFC 7592 DELETE hit the registration_client_uri with the bearer.+ const del = calls.find(c => c.method === 'DELETE')+ expect(del?.url).toBe('https://mcp.notion.com/register/dcr-client-123')+ expect(del?.headers.authorization).toBe('Bearer reg-bearer-xyz')+ })++ it('is idempotent — a server with no DCR client is a clean no-op (0 rows, no remote delete)', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ const { transport, calls } = makeDcrTransport({ responseJson: '' })+ const result = await cleanupDynamicClientForServer(+ db,+ ENC,+ { transport, resolveDns: PUBLIC_IP },+ KEY+ )+ expect(result).toEqual({ localRowsDeleted: 0, attemptedRemoteDelete: false })+ expect(calls.some(c => c.method === 'DELETE')).toBe(false)+ })++ it('a DCR row without a management handle still deletes locally (no remote delete)', async () => {+ const { db } = makeInMemoryDynamicClientsDb()+ await upsertDynamicClient(db, ENC, {+ ...KEY,+ issuer: 'https://mcp.notion.com',+ clientId: 'dcr-client-nohandle',+ clientMode: 'public',+ })+ const { transport, calls } = makeDcrTransport({ responseJson: '' })+ const result = await cleanupDynamicClientForServer(+ db,+ ENC,+ { transport, resolveDns: PUBLIC_IP },+ KEY+ )+ expect(result).toEqual({ localRowsDeleted: 1, attemptedRemoteDelete: false })+ expect(calls.some(c => c.method === 'DELETE')).toBe(false)+ })++ it('bestEffortRfc7592Delete swallows transport failures (courtesy cleanup)', async () => {+ const transport = async () => {+ throw new Error('AS unreachable')+ }+ await expect(+ bestEffortRfc7592Delete(+ { transport, resolveDns: PUBLIC_IP },+ 'https://mcp.notion.com/register/x',+ 'tok'+ )+ ).resolves.toBeUndefined()+ })+})diff --git a/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.tsnew file mode 100644index 000000000..84ac69d5a--- /dev/null+++ b/control-api/test/oauth.mcpServerOAuthSpec.remote.test.ts@@ -0,0 +1,192 @@+import { describe, expect, it } from 'vitest'+import type { DiscoveryResult } from '../src/oauth/discovery.js'+import {+ type McpServerOAuthSpecInput,+ resolveServerOAuth,+ resolveServerOAuthSubject,+} from '../src/oauth/mcpServerOAuthSpec.js'+import { buildRemoteOAuthSpec } from '../src/routes/admin/remoteMcp.js'+import { normalizeMcpServerOwnerDecl } from '../src/routes/mcpOauth.js'++/**+ * C4/DEC-23: `resolveServerOAuthSubject` gains the remote lane. T1 — every remote+ * `spec.oauth` fixture is DERIVED FROM THE REAL PRODUCER (`buildRemoteOAuthSpec`),+ * never hand-written, so the resolver is tested against exactly what install+ * emits. The four remote modes must resolve to the right `secretSource`, baked+ * must stay byte-identical, and the refresh reader (`normalizeMcpServerOwnerDecl`)+ * must not diverge from the subject resolver (D4).+ */++const CIMD_SELF = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'++function discovery(): DiscoveryResult {+ return {+ prm: { resource: 'https://mcp.notion.com' },+ as: {+ issuer: 'https://mcp.notion.com',+ authorization_endpoint: 'https://mcp.notion.com/authorize',+ token_endpoint: 'https://mcp.notion.com/token',+ scopes_supported: ['read', 'write'],+ },+ resource: 'https://mcp.notion.com',+ issuer: 'https://mcp.notion.com',+ endpoints: {+ authorization: 'https://mcp.notion.com/authorize',+ token: 'https://mcp.notion.com/token',+ registration: 'https://mcp.notion.com/register',+ },+ registrationMode: 'cimd',+ quirks: { bearerInBody: false, supportsRefresh: true },+ }+}++/** Wrap a producer-emitted `spec.oauth` into a CR shape the resolver reads. */+function serverFrom(oauth: Record<string, unknown>, contextRef = 'ctx-a'): McpServerOAuthSpecInput {+ return { spec: { oauth, contextRef } }+}++describe('resolveServerOAuthSubject — remote lane (real-producer fixtures, T1)', () => {+ it('CIMD-public → secretSource:public, no refs, id = self-URL', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CIMD_SELF,+ })+ const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ expect(r).not.toBeNull()+ expect(r?.decl.id).toBe(CIMD_SELF)+ expect(r?.decl.provider).toBe('remote')+ expect(r?.decl.clientIdRef).toBeUndefined()+ expect(r?.decl.clientSecretRef).toBeUndefined()+ expect(r?.decl.secretSource).toEqual({ kind: 'public' })+ expect(r?.decl.remote).toMatchObject({+ authorizationEndpoint: 'https://mcp.notion.com/authorize',+ tokenEndpoint: 'https://mcp.notion.com/token',+ resource: 'https://mcp.notion.com',+ clientMode: 'public',+ supportsRefresh: true,+ bearerInBody: false,+ })+ })++ it('DCR-public → secretSource:public, id = AS assignment', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'public',+ grantScope: 'user',+ dynamicClientId: 'dcr-pub-123',+ })+ const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ expect(r?.decl.id).toBe('dcr-pub-123')+ expect(r?.decl.secretSource).toEqual({ kind: 'public' })+ })++ it('DCR-confidential (no refs) → secretSource:dcr-store', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'confidential',+ grantScope: 'user',+ dynamicClientId: 'dcr-conf-xyz',+ })+ const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ expect(r?.decl.id).toBe('dcr-conf-xyz')+ expect(r?.decl.clientIdRef).toBeUndefined()+ expect(r?.decl.secretSource).toEqual({ kind: 'dcr-store' })+ })++ it('pre-registered-confidential (refs) → secretSource:k8s-secret, id = operator client_id', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'confidential',+ grantScope: 'user',+ clientSecretName: 'srv-oauth-client',+ preRegisteredClientId: 'client-abc',+ })+ const r = resolveServerOAuthSubject(serverFrom(oauth as unknown as Record<string, unknown>))+ expect(r?.decl.id).toBe('client-abc')+ expect(r?.decl.clientIdRef).toEqual({ name: 'srv-oauth-client', key: 'client_id' })+ expect(r?.decl.clientSecretRef).toEqual({ name: 'srv-oauth-client', key: 'client_secret' })+ expect(r?.decl.secretSource).toEqual({+ kind: 'k8s-secret',+ clientIdRef: { name: 'srv-oauth-client', key: 'client_id' },+ clientSecretRef: { name: 'srv-oauth-client', key: 'client_secret' },+ })+ })++ it('malformed remote block (missing tokenEndpoint) → null (fail closed)', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CIMD_SELF,+ }) as unknown as Record<string, unknown>+ delete oauth.tokenEndpoint+ expect(resolveServerOAuthSubject(serverFrom(oauth))).toBeNull()+ })++ it('remote resolves the grant coordinate too (resolveServerOAuth keys by oauth.id)', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'public',+ grantScope: 'context',+ cimdClientId: CIMD_SELF,+ })+ const r = resolveServerOAuth(serverFrom(oauth as unknown as Record<string, unknown>))+ expect(r).toEqual({ oauthClientId: CIMD_SELF, grantScope: 'context', contextRef: 'ctx-a' })+ })+})++describe('baked lane stays byte-identical (no source)', () => {+ const BAKED = {+ id: 'google-drive',+ provider: 'google',+ clientIdRef: { name: 'creds', key: 'client-id' },+ clientSecretRef: { name: 'creds', key: 'client-secret' },+ scopes: ['a', 'b'],+ backgroundAccess: true,+ }++ it('returns exactly the confidential-K8s decl (no remote/secretSource keys)', () => {+ const r = resolveServerOAuthSubject(serverFrom(BAKED))+ 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('remote' in (r?.decl ?? {})).toBe(false)+ expect('secretSource' in (r?.decl ?? {})).toBe(false)+ })++ it('baked without clientSecretRef still fails closed (confidential-only)', () => {+ const { clientSecretRef: _drop, ...pub } = BAKED+ expect(resolveServerOAuthSubject(serverFrom(pub))).toBeNull()+ })+})++describe('normalizeMcpServerOwnerDecl (refresh reader) does not diverge from the subject resolver (D4)', () => {+ it('remote-public: accepts (no clientIdRef) and carries the remote routing', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'public',+ grantScope: 'user',+ cimdClientId: CIMD_SELF,+ })+ const normalized = normalizeMcpServerOwnerDecl({+ metadata: { name: 'notion-remote', namespace: 'mcp-server' },+ spec: { oauth: oauth as never },+ })+ const decl = normalized?.spec?.oauthClients?.[0]+ expect(decl?.id).toBe(CIMD_SELF)+ expect(decl?.remote?.tokenEndpoint).toBe('https://mcp.notion.com/token')+ expect(decl?.secretSource).toEqual({ kind: 'public' })+ })++ it('remote-dcr-confidential: accepts (no refs) with secretSource:dcr-store', () => {+ const oauth = buildRemoteOAuthSpec(discovery(), {+ clientMode: 'confidential',+ grantScope: 'user',+ dynamicClientId: 'dcr-conf-xyz',+ })+ const normalized = normalizeMcpServerOwnerDecl({+ spec: { oauth: oauth as never },+ })+ expect(normalized?.spec?.oauthClients?.[0]?.secretSource).toEqual({ kind: 'dcr-store' })+ })+})diff --git a/control-api/test/oauth.tokenHelper.remote.test.ts b/control-api/test/oauth.tokenHelper.remote.test.tsnew file mode 100644index 000000000..9f83edc78--- /dev/null+++ b/control-api/test/oauth.tokenHelper.remote.test.ts@@ -0,0 +1,134 @@+import { describe, expect, it, vi } from 'vitest'+import type { PinnedRawResponse, PinnedTransportInput } from '../src/http/pinnedFetch.js'+import { resolveServerOAuthSubject } from '../src/oauth/mcpServerOAuthSpec.js'+import * as store from '../src/oauth/store.js'+import { getAccessToken } from '../src/oauth/tokenHelper.js'++/**+ * C4/DEC-17 + D-8 — the REMOTE refresh goes through the IP-pinned transport (never+ * `fetchFn`), and a `supportsRefresh:false` server NEVER attempts a refresh+ * (derived from the pinned metadata flag, fail-closed → `no_grant` → the desktop+ * re-consents). The owner decl is produced by the REAL `resolveServerOAuthSubject`.+ */++const ENCRYPTION_KEY = Buffer.alloc(32)+const TOKEN_ENDPOINT = 'https://mcp.notion.com/token'+const VALIDATED_IP = '93.184.216.34'+const CLIENT_ID = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'++function remoteOwnerDecl(supportsRefresh: boolean) {+ const resolved = resolveServerOAuthSubject({+ spec: {+ contextRef: 'ctx-A',+ oauth: {+ source: 'remote',+ id: CLIENT_ID,+ clientMode: 'public',+ authorizationEndpoint: 'https://mcp.notion.com/authorize',+ tokenEndpoint: TOKEN_ENDPOINT,+ issuer: 'https://mcp.notion.com',+ resource: 'https://mcp.notion.com',+ grantScope: 'user',+ scopes: ['read'],+ bearerInBody: false,+ supportsRefresh,+ },+ },+ })+ if (!resolved) throw new Error('fixture: remote resolve returned null')+ return { spec: { oauthClients: [resolved.decl] } }+}++function staleGrant() {+ return {+ provider: 'remote',+ accessToken: 'OLD-AT',+ refreshToken: 'REMOTE-RT',+ accessTokenExpiresAt: new Date(Date.now() - 60_000), // already expired+ } as unknown as Awaited<ReturnType<typeof store.getOAuthGrant>>+}++function recordingTransport(responseJson: string) {+ const calls: { url: string; connectedIP?: string; body?: string }[] = []+ const transport = async (input: PinnedTransportInput): Promise<PinnedRawResponse> => {+ let connectedIP: string | undefined+ input.lookup(+ 'mcp.notion.com',+ { all: true } as never,+ ((err, addrs) => {+ if (!err && Array.isArray(addrs)) connectedIP = addrs[0]?.address+ }) as never+ )+ calls.push({ url: input.url, connectedIP, body: input.body })+ return { status: 200, headers: { 'content-type': 'application/json' }, bodyText: responseJson }+ }+ return { transport, calls }+}++const KEY = {+ grantKind: 'user' as const,+ recipeNamespace: 'mcp-server',+ recipeName: 'notion-remote',+ userId: 'user-9',+ oauthClientId: CLIENT_ID,+}++describe('getAccessToken — remote refresh is IP-pinned (DEC-17)', () => {+ it('refreshes a stale remote grant via pinnedTransport, connects to the validated IP, not fetchFn', async () => {+ vi.spyOn(store, 'getOAuthGrant').mockResolvedValue(staleGrant())+ const refreshSpy = vi+ .spyOn(store, 'refreshOAuthGrantTokens')+ .mockResolvedValue({ updated: true } as never)+ const { transport, calls } = recordingTransport(+ JSON.stringify({ access_token: 'NEW-AT', expires_in: 3600 })+ )+ const fetchFn = vi.fn(async () => {+ throw new Error('remote refresh must NOT use fetchFn')+ })++ const result = await getAccessToken(KEY, {+ db: { query: async () => ({ rows: [] }) } as never,+ recipeReader: { read: async () => remoteOwnerDecl(true) },+ secretReader: { read: async () => ({}) },+ fetchFn: fetchFn as unknown as typeof fetch,+ encryptionKey: ENCRYPTION_KEY,+ resolveDns: async () => [VALIDATED_IP],+ pinnedTransport: transport,+ })++ expect(result).toEqual({ kind: 'ok', accessToken: 'NEW-AT', expiresAt: expect.any(Date) })+ expect(fetchFn).not.toHaveBeenCalled()+ expect(calls).toHaveLength(1)+ expect(calls[0].url).toBe(TOKEN_ENDPOINT)+ expect(calls[0].connectedIP).toBe(VALIDATED_IP)+ expect(calls[0].body).toContain('grant_type=refresh_token')+ expect(refreshSpy).toHaveBeenCalledWith(+ expect.anything(),+ ENCRYPTION_KEY,+ expect.objectContaining({ provider: 'remote' })+ )+ vi.restoreAllMocks()+ })+})++describe('getAccessToken — no-refresh derived from metadata (D-8, fail-closed)', () => {+ it('never attempts a refresh when supportsRefresh=false (returns no_grant)', async () => {+ vi.spyOn(store, 'getOAuthGrant').mockResolvedValue(staleGrant())+ const { transport, calls } = recordingTransport('{}')++ const result = await getAccessToken(KEY, {+ db: { query: async () => ({ rows: [] }) } as never,+ recipeReader: { read: async () => remoteOwnerDecl(false) },+ secretReader: { read: async () => ({}) },+ fetchFn: (async () => {+ throw new Error('no refresh must be attempted')+ }) as unknown as typeof fetch,+ encryptionKey: ENCRYPTION_KEY,+ pinnedTransport: transport,+ })++ expect(result).toEqual({ kind: 'no_grant' })+ expect(calls).toHaveLength(0)+ vi.restoreAllMocks()+ })+})diff --git a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts b/control-api/test/routes.adminCommunicationChannelCredentials.test.tsindex 9c3a5c154..c9375fc65 100644--- a/control-api/test/routes.adminCommunicationChannelCredentials.test.ts+++ b/control-api/test/routes.adminCommunicationChannelCredentials.test.ts@@ -442,19 +442,19 @@ describe('admin communicationchannels — credentials cascade', () => {const e500 = Object.assign(new Error('boom'), { statusCode: 500 })gatewayMock.deleteSecret.mockRejectedValue(e500)gatewayMock.deleteResource.mockResolvedValue({ deleted: true })- const errorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})const res = await request(makeApp()).delete('/admin/communicationchannels/foo')- // CC delete already succeeded; Secret-cleanup failure shouldn't crash- // the request. Operator sees the warn in logs and can clean up manually.+ // CC delete already succeeded; the Secret-cleanup failure is logged (now via+ // the pino logger, not console) and MUST NOT crash the request — the observable+ // contract is a 200 with the Secret-delete attempted (T4: assert the outcome,+ // not the log transport).expect(res.status).toBe(200)expect(gatewayMock.deleteResource).toHaveBeenCalledWith('communicationchannels','foo','channels')- expect(errorSpy).toHaveBeenCalled()- errorSpy.mockRestore()+ expect(gatewayMock.deleteSecret).toHaveBeenCalledWith('cc-foo-credentials', 'channels')})})diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.tsindex e6d85aecd..92d7b1020 100644--- a/control-api/test/routes.adminRemoteMcp.test.ts+++ b/control-api/test/routes.adminRemoteMcp.test.ts@@ -147,6 +147,19 @@ describe('POST /admin/mcp-servers/remote/discover (dry-run)', () => {})describe('POST /admin/mcp-servers/remote (install saga)', () => {+ // CIMD now backfills `oauth.id` from the platform self-URL (DEC-23), which needs+ // a configured public callback base URL — same precondition DCR already has.+ let savedCallbackBaseUrl = ''+ beforeEach(() => {+ savedCallbackBaseUrl = config.oauthCallbackBaseUrl+ config.oauthCallbackBaseUrl = 'https://control.example.com'+ })+ afterEach(() => {+ config.oauthCallbackBaseUrl = savedCallbackBaseUrl+ })++ const CIMD_SELF_CLIENT_ID = 'https://control.example.com/api/v1/.well-known/evenfire-mcp-client'+it('CIMD (public): creates the CR with the pinned spec.oauth shape + attaches to Context', async () => {mockDiscovery(notionResult)const gw = gatewayWithContext('ctx-a')@@ -173,6 +186,8 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {expect(cr.spec.remote).toEqual({ baseUrl: 'https://mcp.notion.com/mcp' })expect(cr.spec.oauth).toEqual({source: 'remote',+ // DEC-23: CIMD-public backfills the platform self-URL client_id.+ id: CIMD_SELF_CLIENT_ID,clientMode: 'public',authorizationEndpoint: 'https://mcp.notion.com/authorize',tokenEndpoint: 'https://mcp.notion.com/token',@@ -215,6 +230,8 @@ describe('POST /admin/mcp-servers/remote (install saga)', () => {spec: { oauth: Record<string, unknown> }}expect(cr.spec.oauth.clientMode).toBe('confidential')+ // DEC-23: pre-registered backfills `oauth.id` from the operator's plaintext client_id.+ expect(cr.spec.oauth.id).toBe('client-abc')expect(cr.spec.oauth.clientIdRef).toEqual({name: 'slack-remote-oauth-client',key: 'client_id',diff --git a/host-context-controller/package.json b/host-context-controller/package.jsonindex 543c8b462..1c1e7faec 100644--- a/host-context-controller/package.json+++ b/host-context-controller/package.json@@ -1,6 +1,6 @@{"name": "clerum-host-context-controller",- "version": "0.1.341",+ "version": "0.1.342","description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API","main": "dist/main.js","engines": {diff --git a/host-context-controller/src/k8sClient.test.ts b/host-context-controller/src/k8sClient.test.tsindex 4f621bcac..698ca0d48 100644--- a/host-context-controller/src/k8sClient.test.ts+++ b/host-context-controller/src/k8sClient.test.ts@@ -629,6 +629,8 @@ describe('MCP authorization store Kubernetes 404 normalization', () => {auth: { type: 'bearer', secretRef: 'server-a-auth', secretKey: 'token' },// Non-remote fixture → remote-ness projects as false (mirrors reconciler isRemote).remote: false,+ // No spec.oauth → bearer-in-body quirk projects as false (mini-spec 19 §D-8).+ bearerInBody: false,enabled: true,status: { deployed: true, ready: true, authoritative: true },})@@ -662,7 +664,42 @@ describe('MCP authorization store Kubernetes 404 normalization', () => {const store = createMcpAuthorizationStore(provider)const server = await store.readMcpServer('server-remote')- expect(server.remote).toBe(true)+ expect(server).not.toBeNull()+ expect(server!.remote).toBe(true)+ })++ it('projects bearerInBody:true against the real producer when spec.oauth.bearerInBody is set', async () => {+ const objects: Record<string, unknown> = {+ 'mcpservers/server-body': {+ metadata: {+ name: 'server-body',+ namespace: 'mcp-server',+ uid: 'server-uid-body',+ resourceVersion: '21',+ },+ spec: {+ description: 'Body-bearer Server',+ transport: {+ type: 'streamableHttp',+ url: 'http://server-body.mcp-server.svc.cluster.local:8080/mcp',+ port: 8080,+ },+ auth: { type: 'oauth' },+ oauth: { source: 'remote', grantScope: 'user', bearerInBody: true },+ remote: { baseUrl: 'https://mcp.semrush.example/mcp' },+ enabled: true,+ },+ },+ }+ mocks.getNamespacedCustomObject.mockImplementation(+ async ({ plural, name }: { plural: string; name: string }) => objects[`${plural}/${name}`]+ )++ const store = createMcpAuthorizationStore(provider)+ const server = await store.readMcpServer('server-body')+ expect(server).not.toBeNull()+ expect(server!.bearerInBody).toBe(true)+ expect(server!.remote).toBe(true)})})diff --git a/host-context-controller/src/k8sClient.ts b/host-context-controller/src/k8sClient.tsindex b14fd448e..5847b95e8 100644--- a/host-context-controller/src/k8sClient.ts+++ b/host-context-controller/src/k8sClient.ts@@ -5346,6 +5346,10 @@ export function createMcpAuthorizationStore(provider: McpServerProvider): McpAutoauth: object.spec.oauth ? { ...object.spec.oauth } : undefined,// Single source of truth for remote-ness, mirrors the reconciler's isRemote.remote: !!object.spec.remote?.baseUrl,+ // Transport quirk derived alongside remote (mini-spec 19 §D-8): the+ // resource advertised bearer_methods_supported:["body"]. Non-secret;+ // projected omit-when-false to the inventory in listServers.+ bearerInBody: !!object.spec.oauth?.bearerInBody,enabled: object.spec.enabled !== false,status,}diff --git a/host-context-controller/src/mcpAuthorization.test.ts b/host-context-controller/src/mcpAuthorization.test.tsindex efb1189bd..2d1b50f58 100644--- a/host-context-controller/src/mcpAuthorization.test.ts+++ b/host-context-controller/src/mcpAuthorization.test.ts@@ -695,3 +695,35 @@ describe('listServers remote projection (C3, orthogonal transport axis)', () =>expect(inventory[0].authKind).toBe('static')})})++describe('listServers bearerInBody projection (mini-spec 19 §D-8, DEC-24)', () => {+ it('emits bearerInBody:true for a remote oauth server that carries the quirk', async () => {+ const store = new FakeStore()+ store.serverObject = {+ ...server,+ auth: { type: 'oauth' },+ oauth: fullOAuth('user'),+ remote: true,+ bearerInBody: true,+ }+ const service = new McpAuthorizationService(store)+ const inventory = await service.listServers(principal)+ expect(inventory[0].bearerInBody).toBe(true)+ // Orthogonal to authKind, and no authority leaks alongside the quirk.+ expect(inventory[0].authKind).toBe('oauth-user')+ expect(inventory[0]).not.toHaveProperty('oauth')+ })++ it('omits bearerInBody when the server does not carry the quirk (absent → header, fail-safe)', async () => {+ const store = new FakeStore()+ store.serverObject = {+ ...server,+ auth: { type: 'oauth' },+ oauth: fullOAuth('user'),+ remote: true,+ }+ const service = new McpAuthorizationService(store)+ const inventory = await service.listServers(principal)+ expect(inventory[0]).not.toHaveProperty('bearerInBody')+ })+})diff --git a/host-context-controller/src/mcpAuthorization.ts b/host-context-controller/src/mcpAuthorization.tsindex 863cc209c..a42760a69 100644--- a/host-context-controller/src/mcpAuthorization.ts+++ b/host-context-controller/src/mcpAuthorization.ts@@ -34,6 +34,8 @@ export interface AuthorityMcpServer {oauth?: McpServerOAuth/** True iff spec.remote.baseUrl is set (nginx egress-proxy server). Non-secret topology bit, orthogonal to authKind; C4 lifts the SHARED-without-token precondition on it. */remote?: boolean+ /** True iff spec.oauth.bearerInBody is set (bearer_methods_supported:["body"], mini-spec 19 §D-8). Non-secret transport quirk; derived alongside remote, projected omit-when-false. */+ bearerInBody?: booleanenabled: booleanstatus: McpServerStatus}@@ -74,6 +76,8 @@ export interface AuthorizedMcpServerInfo {authKind?: AuthorizedMcpAuthKind/** True iff a remote (egress-proxy) server. Absent → local (fail-safe). Orthogonal to authKind; carries no authority. */remote?: boolean+ /** True iff the resource wants the bearer in the request body (mini-spec 19 §D-8). Absent → header (fail-safe). Non-secret transport quirk; carries no authority. */+ bearerInBody?: boolean}export type AuthorizedMcpAuthKind = 'static' | 'oauth-user' | 'oauth-context'@@ -343,6 +347,7 @@ export class McpAuthorizationService {...(authRequired ? { credentialRevision: grant.credentialRevision } : {}),...(authKind ? { authKind } : {}),...(grant.server.remote ? { remote: true } : {}),+ ...(grant.server.bearerInBody ? { bearerInBody: true } : {}),})}const revalidated = await this.resolveHostContext(principal)diff --git a/host-context-controller/src/types.ts b/host-context-controller/src/types.tsindex 3a177dce1..f539d814f 100644--- a/host-context-controller/src/types.ts+++ b/host-context-controller/src/types.ts@@ -47,6 +47,11 @@ export interface McpServerOAuth {scopes?: string[]backgroundAccess?: booleangrantScope?: 'user' | 'context'+ // Remote transport quirk (mini-spec 19 §D-8, CRD IMM-6): true iff the resource+ // advertises `bearer_methods_supported:["body"]`, so mcp-host must present the+ // access token in the request body, not the Authorization header. Non-secret;+ // HCC only projects it to the inventory (as AuthorizedMcpServerInfo.bearerInBody).+ bearerInBody?: boolean}/**diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 83805f035..d78711ce7 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.356",+ "version": "0.1.357","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/contextMapperClient.test.ts b/mcp-host/src/contextMapperClient.test.tsindex e0e27a23f..df65caf98 100644--- a/mcp-host/src/contextMapperClient.test.ts+++ b/mcp-host/src/contextMapperClient.test.ts@@ -308,6 +308,126 @@ describe('ContextMapperClient Host-scoped v2 inventory', () => {)})+ it('projects a remote=true policy flag from the v2 inventory (mini-spec 19 §D-6)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockResolvedValue(+ new Response(+ JSON.stringify(inventory([authorizedServer({ authKind: 'oauth-user', remote: true })])),+ { status: 200 }+ )+ )+ )+ const client = new ContextMapperClient('http://context-mapper.test', {+ authentication: authentication(),+ })++ const result = await client.pollServers()+ expect(result.servers[0].remote).toBe(true)+ })++ it('fail-safes an absent remote flag to local (undefined, not false)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(inventory([authorizedServer({ authKind: 'oauth-user' })])), {+ status: 200,+ })+ )+ )+ const client = new ContextMapperClient('http://context-mapper.test', {+ authentication: authentication(),+ })++ const result = await client.pollServers()+ // HCC omits `remote` when false, so an absent flag must decode to undefined+ // (treated as local everywhere downstream), never a spurious `false` object key.+ expect(result.servers[0].remote).toBeUndefined()+ })++ it('rejects a present-but-non-boolean remote flag (decoder strictness)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockResolvedValue(+ new Response(JSON.stringify(inventory([authorizedServer({ remote: 'yes' })])), {+ status: 200,+ })+ )+ )+ const client = new ContextMapperClient('http://context-mapper.test', {+ authentication: authentication(),+ })++ await expect(client.pollServers()).rejects.toThrow(+ 'HCC inventory response contains an invalid remote flag'+ )+ })++ it('projects a bearerInBody=true transport quirk from the v2 inventory (mini-spec 19 §D-8)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi+ .fn()+ .mockResolvedValue(+ new Response(+ JSON.stringify(+ inventory([+ authorizedServer({ authKind: 'oauth-user', remote: true, bearerInBody: true }),+ ])+ ),+ { status: 200 }+ )+ )+ )+ const client = new ContextMapperClient('http://context-mapper.test', {+ authentication: authentication(),+ })++ const result = await client.pollServers()+ expect(result.servers[0].bearerInBody).toBe(true)+ })++ it('fail-safes an absent bearerInBody flag to header (undefined, not false)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(inventory([authorizedServer({ authKind: 'oauth-user' })])), {+ status: 200,+ })+ )+ )+ const client = new ContextMapperClient('http://context-mapper.test', {+ authentication: authentication(),+ })++ const result = await client.pollServers()+ // HCC omits `bearerInBody` when false, so an absent flag must decode to+ // undefined (treated as header everywhere downstream), never a spurious key.+ expect(result.servers[0].bearerInBody).toBeUndefined()+ })++ it('rejects a present-but-non-boolean bearerInBody flag (decoder strictness)', async () => {+ vi.stubGlobal(+ 'fetch',+ vi.fn().mockResolvedValue(+ new Response(JSON.stringify(inventory([authorizedServer({ bearerInBody: 1 })])), {+ status: 200,+ })+ )+ )+ const client = new ContextMapperClient('http://context-mapper.test', {+ authentication: authentication(),+ })++ await expect(client.pollServers()).rejects.toThrow(+ 'HCC inventory response contains an invalid bearerInBody flag'+ )+ })+it('still rejects forbidden metadata even when a valid authKind is present (guard intact, I1)', async () => {vi.stubGlobal('fetch',diff --git a/mcp-host/src/contextMapperClient.ts b/mcp-host/src/contextMapperClient.tsindex f8280ed36..12808e027 100644--- a/mcp-host/src/contextMapperClient.ts+++ b/mcp-host/src/contextMapperClient.ts@@ -131,6 +131,21 @@ function decodeMcpServer(value: unknown): McpServerInfo {) {throw new Error('HCC inventory response contains an invalid authKind')}+ // `remote` is non-secret policy (mini-spec 19 §D-6), the sibling of authKind:+ // absent degrades to local (fail-safe default); a present-but-non-boolean value+ // is rejected, consistent with the decoder's strictness. HCC emits it+ // omit-when-false, so a real inventory carries it only for remote servers. Like+ // authKind it is NOT on the forbidden-metadata denylist, so accepting it leaves+ // that guard intact.+ if (value.remote !== undefined && typeof value.remote !== 'boolean') {+ throw new Error('HCC inventory response contains an invalid remote flag')+ }+ // `bearerInBody` is non-secret transport policy (mini-spec 19 §D-8), the sibling+ // of `remote`: absent → header (fail-safe default); present-but-non-boolean is+ // rejected; NOT on the forbidden-metadata denylist, so the guard stays intact.+ if (value.bearerInBody !== undefined && typeof value.bearerInBody !== 'boolean') {+ throw new Error('HCC inventory response contains an invalid bearerInBody flag')+ }return {name: value.name,@@ -148,6 +163,8 @@ function decodeMcpServer(value: unknown): McpServerInfo {...(typeof value.authKind === 'string'? { authKind: value.authKind as McpServerInfo['authKind'] }: {}),+ ...(typeof value.remote === 'boolean' ? { remote: value.remote } : {}),+ ...(typeof value.bearerInBody === 'boolean' ? { bearerInBody: value.bearerInBody } : {}),status: {deployed: value.status.deployed,ready: value.status.ready,diff --git a/mcp-host/src/mcp/__tests__/clientRemoteTarget.test.ts b/mcp-host/src/mcp/__tests__/clientRemoteTarget.test.tsnew file mode 100644index 000000000..a4567874a--- /dev/null+++ b/mcp-host/src/mcp/__tests__/clientRemoteTarget.test.ts@@ -0,0 +1,130 @@+/**+ * Mini-spec 19 §D-6 / C4.1 — remote target handling in McpClient:+ * (d) the arbitrary remote `transport.url` is SSRF-guarded (https + public IP)+ * with the shared `core/net/ssrf` mold, BEFORE any transport is built.+ * (e) with MCP_PROXY_URL active, a remote server BYPASSES the in-cluster proxy+ * rail and targets its published `transport.url` (its egress goes through+ * the HCC's own proxy, D-2); a local server still uses the proxy rail.+ *+ * The SDK transports are mocked to capture the target URL that was actually+ * built. `core/net/ssrf` is the REAL mold, exercised with IP-literal hosts so no+ * DNS is touched: a literal is classified directly by `resolvePinnedPublicIp`.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import { SsrfBlockedError } from '../../core/net/ssrf'+import type { McpServerInfo } from '../../types'+import { McpClient, staticTokenProvider } from '../client'++const built: { streamable: string[]; sse: string[] } = { streamable: [], sse: [] }++vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({+ Client: class MockClient {+ connect = vi.fn(async () => undefined)+ close = vi.fn().mockResolvedValue(undefined)+ listTools = vi.fn(async () => ({ tools: [] }))+ request = vi.fn(async () => ({ tools: [] }))+ callTool = vi.fn(async () => ({ content: [] }))+ },+}))++vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({+ StreamableHTTPClientTransport: class MockStreamable {+ close = vi.fn().mockResolvedValue(undefined)+ constructor(url: URL) {+ built.streamable.push(url.toString())+ }+ },+}))++vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({+ SSEClientTransport: class MockSSE {+ close = vi.fn().mockResolvedValue(undefined)+ constructor(url: URL) {+ built.sse.push(url.toString())+ }+ },+}))++function remoteServer(url: string): McpServerInfo {+ return {+ name: 'remote-x',+ transport: { type: 'streamableHttp', url },+ authKind: 'oauth-user',+ remote: true,+ enabled: true,+ status: { deployed: true, ready: true },+ }+}++function localServer(): McpServerInfo {+ return {+ name: 'local-x',+ transport: {+ type: 'streamableHttp',+ url: 'http://local-x.mcp-server.svc.cluster.local:3000/mcp',+ },+ enabled: true,+ status: { deployed: true, ready: true },+ }+}++beforeEach(() => {+ built.streamable = []+ built.sse = []+})++// ─── (d) SSRF guard on the remote target ───────────────────────────────────────++describe('remote target is SSRF-guarded before any transport is built (d)', () => {+ it('rejects a target that resolves to a private/loopback IP, building no transport', async () => {+ const client = new McpClient(remoteServer('https://127.0.0.1/mcp'), staticTokenProvider('t'))+ await expect(client.connect()).rejects.toBeInstanceOf(SsrfBlockedError)+ expect(built.streamable).toEqual([])+ expect(built.sse).toEqual([])+ })++ it('rejects the cloud metadata IP (169.254.169.254)', async () => {+ const client = new McpClient(+ remoteServer('https://169.254.169.254/mcp'),+ staticTokenProvider('t')+ )+ await expect(client.connect()).rejects.toBeInstanceOf(SsrfBlockedError)+ expect(built.streamable).toEqual([])+ })++ it('rejects a non-https remote target', async () => {+ const client = new McpClient(remoteServer('http://8.8.8.8/mcp'), staticTokenProvider('t'))+ await expect(client.connect()).rejects.toBeInstanceOf(SsrfBlockedError)+ expect(built.streamable).toEqual([])+ })++ it('allows a public https target and builds the transport to it', async () => {+ const client = new McpClient(remoteServer('https://8.8.8.8/mcp'), staticTokenProvider('t'))+ await expect(client.connect()).resolves.toBeUndefined()+ expect(built.streamable).toEqual(['https://8.8.8.8/mcp'])+ })+})++// ─── (e) MCP_PROXY_URL bypass for a remote server ──────────────────────────────++describe('remote server bypasses the MCP_PROXY_URL rail (e)', () => {+ const PROXY = 'http://mcp-proxy.svc:8080'++ it('targets the published transport.url, not ${proxy}/servers/<name>/mcp', async () => {+ const client = new McpClient(+ remoteServer('https://8.8.8.8/mcp'),+ staticTokenProvider('t'),+ PROXY+ )+ await client.connect()+ // The remote egress went to its own URL, never the in-cluster proxy rail.+ expect(built.streamable).toEqual(['https://8.8.8.8/mcp'])+ expect(built.streamable[0]).not.toContain('mcp-proxy')+ })++ it('a LOCAL server with the same proxy still routes through the proxy rail (control)', async () => {+ const client = new McpClient(localServer(), staticTokenProvider('t'), PROXY)+ await client.connect()+ expect(built.streamable).toEqual([`${PROXY}/servers/local-x/mcp`])+ })+})diff --git a/mcp-host/src/mcp/__tests__/managerRemoteOauthCatalog.test.ts b/mcp-host/src/mcp/__tests__/managerRemoteOauthCatalog.test.tsnew file mode 100644index 000000000..30dfad79f--- /dev/null+++ b/mcp-host/src/mcp/__tests__/managerRemoteOauthCatalog.test.ts@@ -0,0 +1,225 @@+/**+ * Mini-spec 19 §D-6 / C4.1 — remote+oauth catalog is AUTHENTICATED, never+ * token-less; the platform heartbeat never probes a remote+oauth representative.+ *+ * A spec-compliant remote MCP server (Slack/Notion) 401s already at+ * `initialize`, so the token-less SHARED representative that seeds a LOCAL+ * catalog cannot seed a remote one. These tests pin the observable outcomes+ * (T4): which connection populated the catalog (its Authorization header),+ * whether any token-less connection was opened, and whether the heartbeat issued+ * a probe.+ *+ * Fixtures are derived from the real producers (McpManager + the real McpClient+ * over a mocked SDK, the same wiring managerProbeRepresentative.test.ts uses).+ * The pathological/authenticated states are reached with real manager APIs+ * (addServer / callTool / refreshAllServerStatus), never a hand-built map.+ *+ * The SDK Client mock models a spec-compliant remote: a token-less request to an+ * https target 401s at `initialize`. `core/net/ssrf` is mocked to a public no-op+ * here (its real behavior is covered by clientRemoteTarget.test.ts) so these+ * tests never touch DNS.+ */+import { beforeEach, describe, expect, it, vi } from 'vitest'+import type { McpServerInfo } from '../../types'+import type { McpTokenProvider } from '../client'+import { McpManager, type McpPrincipal, type McpTokenProviderFactory } from '../manager'++interface MockTransport {+ url: string+ requestHeaders: Record<string, string>+ close: ReturnType<typeof vi.fn>+}++const sdk: {+ transports: MockTransport[]+ /** Authorization header of every probe (`request` tools/list) call, in order. */+ probeAuth: Array<string | undefined>+} = { transports: [], probeAuth: [] }++const TOOLS_RESULT = {+ tools: [{ name: 'do', description: 'demo tool', inputSchema: { type: 'object' } }],+}++class RemoteAuthRequired extends Error {+ readonly code = 401+ constructor() {+ super('initialize returned 401')+ this.name = 'RemoteAuthRequired'+ }+}++vi.mock('@modelcontextprotocol/sdk/client/index.js', () => ({+ Client: class MockClient {+ private transport: MockTransport | null = null+ connect = vi.fn(async (t: MockTransport) => {+ // Spec-compliant remote: a token-less request to an https target 401s at+ // `initialize`. Local (http) targets serve initialize unauthenticated.+ if (t.url.startsWith('https:') && !t.requestHeaders['Authorization']) {+ throw new RemoteAuthRequired()+ }+ this.transport = t+ })+ close = vi.fn().mockResolvedValue(undefined)+ listTools = vi.fn(async () => TOOLS_RESULT)+ request = vi.fn(async () => {+ const headers = this.transport?.requestHeaders ?? {}+ sdk.probeAuth.push(headers['Authorization'])+ return TOOLS_RESULT+ })+ callTool = vi.fn(async () => ({ content: [{ type: 'text', text: 'ok' }] }))+ },+}))++vi.mock('@modelcontextprotocol/sdk/client/streamableHttp.js', () => ({+ StreamableHTTPClientTransport: class MockStreamable {+ url: string+ requestHeaders: Record<string, string>+ close = vi.fn().mockResolvedValue(undefined)+ constructor(url: URL, opts?: { requestInit?: { headers?: Record<string, string> } }) {+ this.url = url.toString()+ this.requestHeaders = opts?.requestInit?.headers ?? {}+ sdk.transports.push(this as unknown as MockTransport)+ }+ },+}))++vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({+ SSEClientTransport: class MockSSE {+ close = vi.fn().mockResolvedValue(undefined)+ },+}))++// Neutralize the SSRF guard for the catalog/heartbeat tests — the real guard is+// exercised in clientRemoteTarget.test.ts. Here it must never touch DNS.+vi.mock('../../core/net/ssrf', () => ({+ SsrfBlockedError: class SsrfBlockedError extends Error {},+ resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),+}))++// ─── Fixtures ────────────────────────────────────────────────────────────────++function remoteOauthUserServer(name = 'remote-gh'): McpServerInfo {+ return {+ name,+ transport: { type: 'streamableHttp', url: `https://${name}.example.com/mcp` },+ authKind: 'oauth-user',+ remote: true,+ enabled: true,+ status: { deployed: true, ready: true },+ }+}++function remoteOauthContextServer(name = 'remote-ctx'): McpServerInfo {+ return {+ name,+ transport: { type: 'streamableHttp', url: `https://${name}.example.com/mcp` },+ authKind: 'oauth-context',+ remote: true,+ enabled: true,+ status: { deployed: true, ready: true },+ }+}++function userFactory(): McpTokenProviderFactory {+ return (_server: McpServerInfo, principal: McpPrincipal): McpTokenProvider => {+ if (principal.kind === 'shared') {+ return { resolve: async () => undefined, refresh: async () => undefined }+ }+ const token = `token-for-${principal.userId}`+ return { resolve: async () => token, refresh: async () => token }+ }+}++function contextFactory(): McpTokenProviderFactory {+ return () => ({ resolve: async () => 'context-bearer', refresh: async () => 'context-bearer' })+}++beforeEach(() => {+ sdk.transports = []+ sdk.probeAuth = []+})++// ─── (a) T3 canonical (spec §7): 401-at-initialize resolved by authenticated catalog ──++describe('remote oauth-user catalog is authenticated per-user, never token-less (a)', () => {+ it('opens no token-less SHARED representative and populates the catalog with a user Bearer', async () => {+ const manager = new McpManager(undefined, undefined, userFactory())+ // Against the parent, addServer eagerly opens a token-less SHARED+ // representative that 401s at `initialize` and REJECTS — asserting it+ // resolves turns that defect into a clean assertion failure (T3).+ await expect(manager.addServer(remoteOauthUserServer())).resolves.toBe('applied')++ // No token-less SHARED representative was opened.+ expect(sdk.transports).toEqual([])+ expect(manager.status.get('remote-gh')?.state).toBe('connected')+ // Per-user catalog: empty until a user with a live grant connects.+ expect(manager.getAllTools()).toEqual([])++ // A user's tool call admits an AUTHENTICATED per-user partition whose+ // `initialize`/tools/list carry the Bearer → the catalog is populated.+ const res = await manager.callTool('remote-gh__do', {}, { userId: 'alice' })+ expect(res.isError).toBe(false)+ expect(sdk.transports).toHaveLength(1)+ expect(sdk.transports[0]!.requestHeaders['Authorization']).toBe('Bearer token-for-alice')+ expect(manager.getAllTools().map(t => t.name)).toEqual(['remote-gh__do'])+ })+})++// ─── (b) fail-closed dev: no factory ⇒ no token-less SHARED, no masking catalog ──++describe('remote oauth without a token-provider factory fails closed (b)', () => {+ it('opens no token-less SHARED representative and never populates a token-less catalog', async () => {+ const manager = new McpManager(undefined, undefined, undefined) // no factory (dev/tests)+ await expect(manager.addServer(remoteOauthUserServer())).resolves.toBe('applied')++ // The core invariant: NO token-less connection was ever attempted for a+ // remote oauth server (against the parent, a token-less SHARED representative+ // is opened here). Nothing can populate a token-less catalog.+ expect(sdk.transports).toEqual([])+ expect(manager.status.get('remote-gh')?.state).not.toBe('failed')+ expect(manager.getAllTools()).toEqual([])++ // A user call with no factory fails closed (the per-user provider resolves no+ // token → the remote 401s at initialize), never a silent token-less success.+ const res = await manager.callTool('remote-gh__do', {}, { userId: 'alice' })+ expect(res.isError).toBe(true)+ expect(manager.getAllTools()).toEqual([])+ })+})++// ─── (c) heartbeat never probes a remote+oauth representative ──────────────────++describe('refreshAllServerStatus never probes a remote+oauth server (c)', () => {+ it('does not probe a remote oauth-user server and derives its tool count from the catalog', async () => {+ const manager = new McpManager(undefined, undefined, userFactory())+ await expect(manager.addServer(remoteOauthUserServer())).resolves.toBe('applied')+ await manager.callTool('remote-gh__do', {}, { userId: 'alice' }) // per-user partition alive++ sdk.probeAuth = []+ const summary = await manager.refreshAllServerStatus()++ // No probe issued at all — alice's Bearer never left the host for a platform+ // probe — and the server contributes nothing to the round's tally.+ expect(sdk.probeAuth).toEqual([])+ expect(summary.serverCount).toBe(0)+ // Status is derived from the authenticated per-user catalog cache.+ expect(manager.status.get('remote-gh')?.state).toBe('connected')+ expect(manager.status.get('remote-gh')?.toolCount).toBe(1)+ })++ it('does not probe a remote oauth-context server even though its SHARED representative is alive', async () => {+ const manager = new McpManager(undefined, undefined, contextFactory())+ await manager.addServer(remoteOauthContextServer()) // authenticated SHARED representative++ // Sanity: the authenticated SHARED representative DID populate the catalog.+ expect(manager.getAllTools().map(t => t.name)).toEqual(['remote-ctx__do'])++ sdk.probeAuth = []+ const summary = await manager.refreshAllServerStatus()++ // The context Bearer is a real token; a platform probe must not spend it.+ // (Against the parent this server IS probed on 'Bearer context-bearer'.)+ expect(sdk.probeAuth).toEqual([])+ expect(summary.serverCount).toBe(0)+ })+})diff --git a/mcp-host/src/mcp/client.ts b/mcp-host/src/mcp/client.tsindex ec53d8616..d9e06f5cc 100644--- a/mcp-host/src/mcp/client.ts+++ b/mcp-host/src/mcp/client.ts@@ -6,6 +6,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js'import { SSEClientTransport } from '@modelcontextprotocol/sdk/client/sse.js'import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js'import { ListToolsResultSchema } from '@modelcontextprotocol/sdk/types.js'+import { SsrfBlockedError, resolvePinnedPublicIp } from '../core/net/ssrf'import { McpServerInfo, McpTool } from '../types'import {type McpToolCallOptions,@@ -166,12 +167,35 @@ export class McpClient {return cleanup}+ /**+ * A REMOTE server (mini-spec 19 §D-6) is an off-cluster, spec-compliant+ * upstream reached over its published `transport.url`. Two behaviors fork on+ * it: the target is SSRF-guarded (validateRemoteTarget) and the in-cluster+ * MCP_PROXY_URL rail is bypassed (see resolveUrl / usesProxyRail).+ */+ private isRemoteServer(): boolean {+ return this.serverConfig.remote === true+ }++ /**+ * Whether this connection routes through the in-cluster MCP_PROXY_URL rail. A+ * remote server bypasses it EXPLICITLY: its egress goes through the HCC's own+ * nginx proxy (per-user Bearer passthrough, D-2), not `${proxyUrl}/servers/…`,+ * and its transport type is driven by discovery — not forced to StreamableHTTP+ * by the presence of the (unused) proxy rail.+ */+ private usesProxyRail(): boolean {+ // Truthy check preserves the original `if (this.proxyUrl)` semantics (an+ // empty proxyUrl is "no proxy"); the remote bypass is the only new condition.+ return !!this.proxyUrl && !this.isRemoteServer()+ }+/*** Create the appropriate transport based on server configuration.*/private resolveUrl(): string {const { transport } = this.serverConfig- if (this.proxyUrl) {+ if (this.usesProxyRail()) {const url = `${this.proxyUrl}/servers/${this.serverConfig.name}/mcp`console.log(`[MCP:${this.name}] Using proxy URL: ${url}`)return url@@ -179,19 +203,50 @@ export class McpClient {return transport.url || `http://${this.serverConfig.name}.mcp-server.svc.cluster.local:3000/mcp`}+ /**+ * SSRF-guard a REMOTE server's target before any transport I/O. The target+ * (`transport.url`) is arbitrary operator/discovery input, so it is validated+ * with the shared mold (`core/net/ssrf`): https-only, and the host must resolve+ * exclusively to public addresses (private/loopback/link-local/metadata and+ * unresolvable hosts throw `SsrfBlockedError`). The in-cluster DNS fallback and+ * the MCP_PROXY_URL rail are internal and deliberately NOT guarded here.+ */+ private async validateRemoteTarget(options: McpToolCallOptions): Promise<void> {+ const url = new URL(this.resolveUrl())+ if (url.protocol !== 'https:') {+ throw new SsrfBlockedError(`remote MCP server URL must be https (got ${url.protocol})`)+ }+ // Throws SsrfBlockedError on a private/reserved/metadata or unresolvable host.+ await resolvePinnedPublicIp(url)+ ensureNotAborted(options.signal)+ }+private createTransport(): SupportedMcpTransport {const { transport } = this.serverConfigconst headers: Record<string, string> = {}// currentAuthToken is resolved per (re)connect in connect() below; a// representative (token-less) connection leaves it undefined → no header.+ //+ // Header vs body (mini-spec 19 §D-8, DEC-24): `serverConfig.bearerInBody`+ // flows end-to-end (HCC → decoder → here) but the token still goes in the+ // header for EVERY server. Body injection is deferred on purpose: a resource+ // advertising `bearer_methods_supported:["body"]` (SEMrush) has NO defined+ // wire shape for an MCP StreamableHTTP request — RFC 6750 §2.2 "body" is a+ // form-encoded `access_token`, incompatible with the JSON-RPC+ // `application/json` body the SDK sends. Committing to a field would invent+ // SEMrush's contract; it must be pinned by a real probe first. The SDK does+ // support the mechanism (a custom `fetch` in the transport opts could rewrite+ // the outgoing request), so this is a contract gap, not an SDK limitation. No+ // live pilot (Notion/Canva/Linear/Sentry) uses body-bearer, so the rail is+ // unaffected.if (this.currentAuthToken) {headers['Authorization'] = `Bearer ${this.currentAuthToken}`}const targetUrl = this.resolveUrl()- if (this.proxyUrl || transport.type === 'streamableHttp') {+ if (this.usesProxyRail() || transport.type === 'streamableHttp') {console.log(`[MCP:${this.name}] Using Streamable HTTP transport`)return new StreamableHTTPClientTransport(new URL(targetUrl), {requestInit: {@@ -232,6 +287,12 @@ export class McpClient {} else {this.currentAuthToken = undefined}+ // SSRF-guard a remote target BEFORE any transport is built (throws on a+ // private/metadata/unresolvable host or a non-https URL). Local servers (proxy+ // rail or in-cluster DNS) are internal and skip this.+ if (this.isRemoteServer()) {+ await this.validateRemoteTarget(options)+ }const connectionEpoch = ++this.connectionEpochconst nextTransport = this.createTransport()const nextClient = new Client(diff --git a/mcp-host/src/mcp/manager.ts b/mcp-host/src/mcp/manager.tsindex a62bda5f4..37e3af557 100644--- a/mcp-host/src/mcp/manager.ts+++ b/mcp-host/src/mcp/manager.ts@@ -207,25 +207,49 @@ export class McpManager {return this.clients.get(this.sharedKey(serverName))}+ /**+ * A remote oauth server's status is NEVER derived from a platform probe. A+ * probe (`probeTools`) is a real tools/list round-trip, and a spec-compliant+ * remote 401s on any token-less request while an authenticated probe would+ * spend a user's / context's OAuth token on a platform heartbeat (mini-spec 19+ * §D-6). Its status is derived from the authenticated per-user catalog cache+ * (a pure in-memory read) plus the `connect_required` marker set at call time.+ */+ private isRemoteOauthServer(serverName: string): boolean {+ const info = this.serverInfos.get(serverName)+ return info?.remote === true && this.isOauthServer(info)+ }++ private isOauthServer(serverConfig: McpServerInfo): boolean {+ return serverConfig.authKind === 'oauth-user' || serverConfig.authKind === 'oauth-context'+ }+private buildTokenProvider(serverConfig: McpServerInfo,principal: McpPrincipal,eagerToken: string | undefined): McpTokenProvider | undefined {- if (serverConfig.authKind === 'oauth-user' || serverConfig.authKind === 'oauth-context') {+ if (this.isOauthServer(serverConfig)) {// oauth: JIT resolution via the injected factory (broker per-user /- // per-context, or token-less representative). No factory (dev/tests) →- // token-less, which fails closed on a server that requires auth.- //- // PRECONDITION (v1 class-a, spec §10.1 VERIFIED / mini-spec 03 §5): catalog- // population relies on the SHARED representative connecting WITHOUT auth —- // i.e. the server must serve initialize/tools/list unauthenticated and only- // 401 on tools/call (own-image, static catalog). A class-b upstream that- // auth-gates discovery is OUT of v1 scope and needs the deferred- // CRD-declared-schema path (mini-spec 03 §5/§8 "fuente de schema declarado").- return this.tokenProviderFactory- ? this.tokenProviderFactory(serverConfig, principal)- : staticTokenProvider(undefined)+ // per-context, or token-less representative).+ if (this.tokenProviderFactory) {+ return this.tokenProviderFactory(serverConfig, principal)+ }+ // No factory (dev/tests). Behavior forks on remote vs local, because their+ // catalog preconditions are opposite:+ // - LOCAL (v1 class-a, mini-spec 03 §5): the server serves+ // initialize/tools/list WITHOUT auth and only 401s on tools/call, so a+ // token-less SHARED representative still populates the catalog. Preserve+ // that — `staticTokenProvider(undefined)`.+ // - REMOTE (mini-spec 19 §D-6): a spec-compliant upstream 401s already at+ // `initialize`. A token-less provider here would let a dev server that+ // does NOT enforce auth connect and populate a token-less catalog,+ // MASKING the authenticated rail (and, worse, hiding that the same+ // server 401s in prod). Fail closed: return no provider. `undefined`+ // resolves to a token-less connection, but the eager-admission path+ // (addServer) never treats a remote-oauth SHARED representative as a+ // "populated catalog" — see the remote-oauth branch there.+ return serverConfig.remote ? undefined : staticTokenProvider(undefined)}// static/none/bearer/basic/apiKey: preserve today's frozen-token behavior.return staticTokenProvider(eagerToken)@@ -304,8 +328,11 @@ export class McpManager {/*** Add and connect to an MCP server (SHARED partition — the eager coordinator- * path). oauth-user servers admit only the token-less representative here;- * per-user partitions are lazily admitted on demand via callTool.+ * path). LOCAL oauth-user servers admit only the token-less representative+ * here; per-user partitions are lazily admitted on demand via callTool. REMOTE+ * oauth servers open NO token-less SHARED representative (mini-spec 19 §D-6, see+ * the remote-oauth branch below): the catalog is authenticated per-user (or, for+ * oauth-context, over the authenticated SHARED grant).*/async addServer(serverConfig: McpServerInfo,@@ -355,6 +382,51 @@ export class McpManager {return 'applied'}+ // ── Remote oauth: no token-less SHARED representative (mini-spec 19 §D-6) ──+ // A LOCAL oauth server serves initialize/tools/list unauthenticated, so the+ // eager SHARED representative can populate the catalog token-less. A REMOTE+ // spec-compliant server 401s already at `initialize`, so that representative+ // CANNOT be token-less. Handle the eager SHARED admission by flavor; the sole+ // case that keeps the eager path is an oauth-context server WITH a factory,+ // whose SHARED representative connects AUTHENTICATED on its context grant and+ // IS the catalog. Everything else must NOT open a token-less SHARED+ // connection:+ // - oauth-user: no shared grant exists → the catalog is authenticated+ // PER-USER (each user's partition does the authenticated initialize/+ // tools/list, admitted lazily on first tool call, surfaced through the+ // per-user representative fallback in representativeClient/getAllTools).+ // - no factory (dev/tests): nothing can authenticate the representative →+ // fail closed rather than degrade to a masking token-less catalog.+ // In both, register the server (so per-user admission and status derive from+ // it) but open no SHARED connection.+ if (serverConfig.remote && this.isOauthServer(serverConfig)) {+ const sharedAuthenticates =+ serverConfig.authKind === 'oauth-context' && this.tokenProviderFactory !== undefined+ if (!sharedAuthenticates) {+ const installed = this.serverInfos.get(serverConfig.name)+ if (installed && JSON.stringify(installed) === JSON.stringify(serverConfig)) {+ control.onCommit?.()+ return 'applied'+ }+ // Config changed (or first registration): drop any live per-user+ // partitions so they rebuild lazily against the new revision — the remote+ // analogue of replaceServer's per-user eviction. There is no SHARED+ // representative to keep, so keepKey matches nothing.+ this.evictPartitionsExcept(serverConfig.name, this.sharedKey(serverConfig.name), control)+ this.serverInfos.set(serverConfig.name, serverConfig)+ // Reflect whatever the (per-user) representative catalog already holds —+ // 0 right after an eviction / until a user with a live grant connects. The+ // heartbeat refreshes this from the authenticated per-user catalog, never+ // a token-less probe.+ this.statusTracker.markConnected(+ serverConfig.name,+ this.representativeClient(serverConfig.name)?.availableTools.length ?? 0+ )+ control.onCommit?.()+ return 'applied'+ }+ }+const key = this.sharedKey(serverConfig.name)// Check if already connected (SHARED partition)@@ -1069,7 +1141,13 @@ export class McpManager {// oauth grantScope='user' server into per-user clients, but a status round// probes each server once via its representative; iterating raw clients would// double-count those partitions in the summary tally.- const entries = [...this.byServer.keys()]+ // Remote oauth servers are excluded from the probe set: their status is+ // derived from the per-user catalog cache below, never a token-less/platform+ // probe (see isRemoteOauthServer / mini-spec 19 §D-6).+ const allServers = [...this.byServer.keys()]+ const remoteOauthServers = allServers.filter(name => this.isRemoteOauthServer(name))+ const entries = allServers+ .filter(name => !this.isRemoteOauthServer(name)).map(name => [name, this.probeRepresentativeClient(name)] as const).filter((entry): entry is readonly [string, McpClient] => entry[1] !== undefined)if (options.signal?.aborted) {@@ -1136,6 +1214,16 @@ export class McpManager {this.statusTracker.updateToolCount(name, 0, { refreshError: result.error })}}+ // Remote oauth: refresh the tool count from the authenticated per-user catalog+ // cache (representativeClient, no network) instead of a probe — the token-safe+ // status derivation of mini-spec 19 §D-6. These servers are absent from the+ // summary tally on purpose (no probe was issued, no token spent).+ for (const name of remoteOauthServers) {+ const representative = this.representativeClient(name)+ if (representative) {+ this.statusTracker.updateToolCount(name, representative.availableTools.length)+ }+ }return summary}diff --git a/mcp-host/src/types.ts b/mcp-host/src/types.tsindex 23b792476..e4f4950e1 100644--- a/mcp-host/src/types.ts+++ b/mcp-host/src/types.ts@@ -223,6 +223,29 @@ export interface McpServerInfo {* keeping it on the policy side of the decoder's forbidden-metadata guard.*/authKind?: 'static' | 'oauth-user' | 'oauth-context'+ /**+ * Non-secret policy: `true` iff this is a REMOTE MCP server (an off-cluster,+ * spec-compliant upstream reached over its published `transport.url`, e.g.+ * Slack/Notion). It carries NO authority (like `authKind`, it stays on the+ * policy side of the decoder's forbidden-metadata guard). Absent → local+ * (in-cluster/own-image), the historical default. A remote oauth server is+ * spec-compliant and 401s already at `initialize`, so mcp-host must (a) populate+ * its catalog authenticated (never token-less), (b) SSRF-guard the arbitrary+ * `transport.url`, and (c) bypass the in-cluster MCP_PROXY_URL rail — its egress+ * goes through the HCC's own auth-passthrough proxy.+ */+ remote?: boolean+ /**+ * Non-secret transport quirk (mini-spec 19 §D-8, DEC-22/DEC-24): `true` iff the+ * remote OAuth resource advertises `bearer_methods_supported:["body"]` (e.g.+ * SEMrush) — the access token must ride the request BODY, not the+ * `Authorization: Bearer` header. Sibling of `remote`: policy only, no+ * authority, off the decoder's forbidden-metadata denylist, fail-safe to absent+ * (= header, the historical default). The flag is wired end-to-end here; the+ * actual body injection in client.ts is deferred pending a real wire contract+ * (see the note at McpClient.createTransport).+ */+ bearerInBody?: booleanenabled: booleanstatus: McpServerStatus}