Skip to content

Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure

TypeScript

feat(control-api): remote MCP-OAuth C-install routes + discovery DNS-rebinding pin (C1.5)

Diego Zacarias9e46776524d6
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index 461945ecf..fbc5590fc 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.589",
+ "version": "0.1.590",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.589",
+ "version": "0.1.590",
"dependencies": {
"@clerum/display-field": "file:../packages/display-field",
"@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",
diff --git a/control-api/package.json b/control-api/package.json
index a518fab2a..c16ca492b 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.589",
+ "version": "0.1.590",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/http/pinnedFetch.ts b/control-api/src/http/pinnedFetch.ts
new file mode 100644
index 000000000..8075239bf
--- /dev/null
+++ b/control-api/src/http/pinnedFetch.ts
@@ -0,0 +1,231 @@
+import { request as httpsRequest } from 'node:https'
+import type { LookupFunction } from 'node:net'
+import {
+ type DnsResolver,
+ type ValidationError,
+ resolveValidatedOAuthEndpoint,
+} from './validateMcpServerSpec.js'
+
+/**
+ * IP-pinned guarded fetch over `node:https` (spec 02 §4, DEC-16; closes H2 —
+ * DNS-rebinding/TOCTOU SSRF).
+ *
+ * The problem it solves: `validateOAuthEndpointUrl` resolves a hostname to check
+ * its IPs, but a plain `fetch(url)` RE-RESOLVES the same hostname when it connects.
+ * An attacker with a low-TTL A record returns a public IP at validation and a
+ * private one (169.254.169.254 / RFC1918 / `.svc`) at connect. This module removes
+ * the second resolution: it resolves+validates ONCE via
+ * {@link resolveValidatedOAuthEndpoint}, then pins the socket to those exact IPs
+ * through the `lookup` option of `https.request`. `options.host` stays the HOSTNAME
+ * so SNI / the Host header / TLS cert verification all still run against the
+ * hostname — `servername` is NEVER set to the IP.
+ *
+ * It does ONE hop and NEVER follows redirects (a 3xx is returned verbatim, with its
+ * `location`, for the caller to re-validate AND re-pin — never reuse a prior hop's
+ * IP). It sends `Accept-Encoding: identity` and fails closed on any non-identity
+ * `content-encoding` (rather than mis-parsing compressed bytes as JSON), caps the
+ * response body, and preserves a request timeout/abort.
+ *
+ * The low-level transport is injectable so unit tests assert `connectedIP ===
+ * validatedIP` and that `resolveDns` runs exactly once per hop, with no real network.
+ */
+
+const DEFAULT_TIMEOUT_MS = 15_000
+/** 1 MiB cap — OAuth metadata documents are a few KiB; anything larger is hostile. */
+const DEFAULT_MAX_BODY_BYTES = 1024 * 1024
+
+/** What the transport receives: a single, already-validated hop with a pinned lookup. */
+export interface PinnedTransportInput {
+ url: string
+ method: 'GET' | 'POST'
+ headers: Record<string, string>
+ /**
+ * A `node:net` lookup that returns ONLY the pre-validated addresses and never
+ * re-resolves. The default transport hands it to `https.request`; a test
+ * transport invokes it to observe which IP the socket would connect to.
+ */
+ lookup: LookupFunction
+ signal: AbortSignal
+ maxBodyBytes: number
+ /** Present only for method === 'POST' (form body); C4 exchange adoption. */
+ body?: string
+}
+
+export interface PinnedRawResponse {
+ status: number
+ /** Lowercased header map, as `node:https` `res.headers` produces. */
+ headers: Record<string, string | string[] | undefined>
+ bodyText: string
+}
+
+export type PinnedTransport = (input: PinnedTransportInput) => Promise<PinnedRawResponse>
+
+export type PinnedFetchError =
+ | { kind: 'kernel_rejected'; field: string; errors: ValidationError[] }
+ | { kind: 'transport_failed'; detail: string }
+ | { kind: 'content_encoding_rejected'; encoding: string }
+
+export interface PinnedResponse {
+ status: number
+ headers: Record<string, string | string[] | undefined>
+ bodyText: string
+ /** The exact IPs the pin resolved and connected through — for tests/audit. */
+ pinnedAddresses: string[]
+}
+
+export type PinnedFetchResult =
+ | { ok: true; response: PinnedResponse }
+ | { ok: false; error: PinnedFetchError }
+
+export interface PinnedFetchOptions {
+ method?: 'GET' | 'POST'
+ headers?: Record<string, string>
+ body?: string
+ resolveDns?: DnsResolver
+ transport?: PinnedTransport
+ timeoutMs?: number
+ maxBodyBytes?: number
+}
+
+function errMessage(e: unknown): string {
+ return e instanceof Error ? e.message : String(e)
+}
+
+function firstHeaderValue(value: string | string[] | undefined): string | undefined {
+ if (Array.isArray(value)) return value[0]
+ return value
+}
+
+/**
+ * Build a `node:net` lookup that returns EXACTLY the validated addresses and never
+ * performs DNS itself. Feeding this to `https.request` pins the socket to the IPs the
+ * kernel already vetted, so no re-resolution can slip a private IP in at connect time.
+ */
+function pinnedLookup(addresses: string[]): LookupFunction {
+ const records = addresses.map(address => ({ address, family: 4 as const }))
+ const fn = (_hostname: string, options: unknown, callback: unknown): void => {
+ const cb = (typeof options === 'function' ? options : callback) as (
+ err: Error | null,
+ address: string | Array<{ address: string; family: number }>,
+ family?: number
+ ) => void
+ const wantsAll =
+ typeof options === 'object' && options !== null && (options as { all?: boolean }).all === true
+ if (wantsAll) {
+ cb(null, records)
+ } else {
+ cb(null, records[0].address, records[0].family)
+ }
+ }
+ return fn as unknown as LookupFunction
+}
+
+const defaultPinnedTransport: PinnedTransport = input =>
+ new Promise<PinnedRawResponse>((resolve, reject) => {
+ let u: URL
+ try {
+ u = new URL(input.url)
+ } catch (e) {
+ reject(e instanceof Error ? e : new Error(String(e)))
+ return
+ }
+ const req = httpsRequest(
+ {
+ protocol: u.protocol,
+ // hostname (NOT the IP) so SNI/Host/TLS cert verify against the hostname.
+ hostname: u.hostname,
+ port: u.port === '' ? 443 : Number(u.port),
+ path: `${u.pathname}${u.search}`,
+ method: input.method,
+ headers: input.headers,
+ // Pin: connect only to the pre-validated IPs.
+ lookup: input.lookup,
+ signal: input.signal,
+ },
+ res => {
+ const chunks: Buffer[] = []
+ let total = 0
+ let capped = false
+ res.on('data', (chunk: Buffer) => {
+ if (capped) return
+ total += chunk.length
+ if (total > input.maxBodyBytes) {
+ capped = true
+ req.destroy(new Error(`response body exceeded ${input.maxBodyBytes} bytes`))
+ return
+ }
+ chunks.push(chunk)
+ })
+ res.on('end', () => {
+ if (capped) return
+ resolve({
+ status: res.statusCode ?? 0,
+ headers: res.headers,
+ bodyText: Buffer.concat(chunks).toString('utf8'),
+ })
+ })
+ res.on('error', reject)
+ }
+ )
+ req.on('error', reject)
+ if (input.body !== undefined) req.write(input.body)
+ req.end()
+ })
+
+/**
+ * Validate + pin + fetch a SINGLE URL (no redirect following). On a 3xx the response
+ * is returned verbatim (status + `location` header) for the caller to re-validate and
+ * re-pin. Fail-closed: a URL the kernel rejects is never fetched, and a non-identity
+ * `content-encoding` is a typed error, not a silent mis-parse.
+ */
+export async function pinnedFetch(
+ url: string,
+ field: string,
+ options: PinnedFetchOptions = {}
+): Promise<PinnedFetchResult> {
+ const resolved = await resolveValidatedOAuthEndpoint(url, field, {
+ resolveDns: options.resolveDns,
+ })
+ if (!resolved.ok) {
+ return { ok: false, error: { kind: 'kernel_rejected', field, errors: resolved.errors } }
+ }
+
+ const transport = options.transport ?? defaultPinnedTransport
+ const headers: Record<string, string> = {
+ accept: 'application/json',
+ // Ask for no compression; we reject anything else rather than mis-parse it.
+ 'accept-encoding': 'identity',
+ ...options.headers,
+ }
+ const signal = AbortSignal.timeout(options.timeoutMs ?? DEFAULT_TIMEOUT_MS)
+
+ let raw: PinnedRawResponse
+ try {
+ raw = await transport({
+ url,
+ method: options.method ?? 'GET',
+ headers,
+ lookup: pinnedLookup(resolved.addresses),
+ signal,
+ maxBodyBytes: options.maxBodyBytes ?? DEFAULT_MAX_BODY_BYTES,
+ ...(options.body !== undefined ? { body: options.body } : {}),
+ })
+ } catch (e) {
+ return { ok: false, error: { kind: 'transport_failed', detail: errMessage(e) } }
+ }
+
+ const encoding = firstHeaderValue(raw.headers['content-encoding'])
+ if (encoding && encoding.trim().toLowerCase() !== 'identity') {
+ return { ok: false, error: { kind: 'content_encoding_rejected', encoding } }
+ }
+
+ return {
+ ok: true,
+ response: {
+ status: raw.status,
+ headers: raw.headers,
+ bodyText: raw.bodyText,
+ pinnedAddresses: resolved.addresses,
+ },
+ }
+}
diff --git a/control-api/src/http/validateMcpServerSpec.ts b/control-api/src/http/validateMcpServerSpec.ts
index ddbe8ef27..0d43de938 100644
--- a/control-api/src/http/validateMcpServerSpec.ts
+++ b/control-api/src/http/validateMcpServerSpec.ts
@@ -461,22 +461,30 @@ export async function validateMcpServerSpecPreflight(
}
/**
- * Kernel de política sobre una URL de endpoint OAuth (spec 19 §4): scheme https +
- * host público + resolve→IP no bloqueada. Reusa isPublicDnsHostname/validatePublicCidr.
- * `resolveDns` inyectable ⇒ testeable en Vitest sin cluster. Devuelve [] si válida.
- * Seam compartido para el carril self-hosted 'generic' (S3-B2) y el remoto (spec 02);
- * hoy sin call-sites de producción — es la base del seam.
+ * Kernel core: validate an OAuth endpoint URL (spec 19 §4) AND return the resolved
+ * IPv4 addresses. scheme https + public host + resolve→non-blocked IPs, reusing
+ * isPublicDnsHostname/filterBlockedIpv4. `resolveDns` is injectable ⇒ testable in
+ * Vitest without a cluster.
+ *
+ * This is the single source of truth for the rule: both {@link validateOAuthEndpointUrl}
+ * (thin wrapper discarding the addresses) and {@link resolveValidatedOAuthEndpoint}
+ * (the pin, which CONSUMES the addresses so the socket connects to the exact IPs the
+ * validator resolved — closing the TOCTOU/DNS-rebinding window, H2) call it. The two
+ * MUST never drift, so the resolve+filter logic lives here once.
+ *
+ * `addresses` is the deduplicated set of resolved IPv4 addresses. When `errors` is
+ * empty it is guaranteed non-empty and all non-blocked (public) — the pin candidates.
*/
-export async function validateOAuthEndpointUrl(
+async function validateAndResolveOAuthEndpoint(
rawUrl: string,
field: string,
options: { resolveDns?: DnsResolver } = {}
-): Promise<ValidationError[]> {
+): Promise<{ errors: ValidationError[]; addresses: string[] }> {
let url: URL
try {
url = new URL(rawUrl)
} catch {
- return [{ field, message: 'must be a valid absolute URL' }]
+ return { errors: [{ field, message: 'must be a valid absolute URL' }], addresses: [] }
}
const errors: ValidationError[] = []
@@ -490,12 +498,13 @@ export async function validateOAuthEndpointUrl(
// resolved. An internal/literal/malformed host is rejected without a DNS
// lookup (never resolve to probe internal names).
errors.push({ field, message: 'host must be a public DNS hostname' })
- return errors
+ return { errors, addresses: [] }
}
const resolveDns = options.resolveDns ?? defaultDnsResolver
+ let addresses: string[] = []
try {
- const addresses = Array.from(new Set(await resolveDns(host)))
+ addresses = Array.from(new Set(await resolveDns(host)))
if (addresses.length === 0) {
errors.push({ field, message: `host "${host}" did not resolve to an IPv4 A record` })
} else {
@@ -518,9 +527,44 @@ export async function validateOAuthEndpointUrl(
})
}
+ return { errors, addresses }
+}
+
+/**
+ * Kernel de política sobre una URL de endpoint OAuth (spec 19 §4): scheme https +
+ * host público + resolve→IP no bloqueada. `resolveDns` inyectable ⇒ testeable en
+ * Vitest sin cluster. Devuelve [] si válida. Seam compartido para el carril
+ * self-hosted 'generic' (S3-B2) y el remoto (spec 02).
+ */
+export async function validateOAuthEndpointUrl(
+ rawUrl: string,
+ field: string,
+ options: { resolveDns?: DnsResolver } = {}
+): Promise<ValidationError[]> {
+ const { errors } = await validateAndResolveOAuthEndpoint(rawUrl, field, options)
return errors
}
+/**
+ * Same rule as {@link validateOAuthEndpointUrl}, but on success RETURNS the resolved
+ * IPv4 addresses so a caller can PIN the socket to those exact IPs (spec 02 §4,
+ * H2 DNS-rebinding/TOCTOU). The addresses are the deduplicated, all-public set the
+ * validator resolved; a pinned fetch feeds them to its `lookup` so the connection
+ * cannot re-resolve to a private/metadata host between validation and connect.
+ *
+ * Fail-closed: any validation error (bad scheme, non-public host, blocked/empty
+ * resolution) yields `{ ok: false, errors }` and no addresses.
+ */
+export async function resolveValidatedOAuthEndpoint(
+ rawUrl: string,
+ field: string,
+ options: { resolveDns?: DnsResolver } = {}
+): Promise<{ ok: true; addresses: string[] } | { ok: false; errors: ValidationError[] }> {
+ const { errors, addresses } = await validateAndResolveOAuthEndpoint(rawUrl, field, options)
+ if (errors.length > 0) return { ok: false, errors }
+ return { ok: true, addresses }
+}
+
export async function validateEgressBindingsPreflight(
egressBindings: unknown,
fieldPrefix = 'spec.egressBindings',
diff --git a/control-api/src/oauth/discovery.ts b/control-api/src/oauth/discovery.ts
index 7118e0782..b79850821 100644
--- a/control-api/src/oauth/discovery.ts
+++ b/control-api/src/oauth/discovery.ts
@@ -1,3 +1,9 @@
+import {
+ type PinnedFetchError,
+ type PinnedResponse,
+ type PinnedTransport,
+ pinnedFetch,
+} from '../http/pinnedFetch.js'
import {
type DnsResolver,
type ValidationError,
@@ -122,7 +128,13 @@ export function deriveQuirks(
// ─── Discovery flow ─────────────────────────────────────────────────────────
export interface DiscoveryDeps {
- fetchFn: typeof fetch
+ /**
+ * Injectable low-level transport for the IP-pinned fetch (H2). Production leaves it
+ * undefined (the `node:https` default); tests inject one to assert the socket
+ * connects to the validated IP with no real network. Replaces the old `fetchFn`
+ * seam — discovery has no production caller before C1.5, so the swap is safe.
+ */
+ transport?: PinnedTransport
resolveDns?: DnsResolver
logger?: Logger
}
@@ -139,6 +151,8 @@ export type DiscoveryError =
| { kind: 'prm_resource_mismatch'; url: string; detail: string }
/** AS metadata `issuer` (RFC 8414 §3.3) does not match the AS base it was fetched from. */
| { kind: 'issuer_mismatch'; detail: string }
+ /** Response arrived with a non-identity `content-encoding` (fail-closed, never mis-parse). */
+ | { kind: 'content_encoding_rejected'; url: string; encoding: string }
export interface DiscoveryResult {
prm: ProtectedResourceMetadata
@@ -176,15 +190,30 @@ function isRedirectStatus(status: number): boolean {
return status === 301 || status === 302 || status === 303 || status === 307 || status === 308
}
+function firstHeader(value: string | string[] | undefined): string | undefined {
+ return Array.isArray(value) ? value[0] : value
+}
+
+/** Map a pinned-fetch error onto discovery's typed error union. */
+function mapPinnedError(error: PinnedFetchError, url: string): DiscoveryError {
+ switch (error.kind) {
+ case 'kernel_rejected':
+ return { kind: 'kernel_rejected', field: error.field, errors: error.errors }
+ case 'transport_failed':
+ return { kind: 'fetch_failed', url, detail: error.detail }
+ case 'content_encoding_rejected':
+ return { kind: 'content_encoding_rejected', url, encoding: error.encoding }
+ }
+}
+
/**
- * Kernel-guard a URL and fetch it, following redirects MANUALLY (`redirect:'manual'`).
+ * IP-pinned guarded fetch, following redirects MANUALLY and re-pinning EVERY hop.
*
- * The default `redirect:'follow'` only lets the kernel veto the FIRST hop — undici
- * then follows a `302 Location: http://169.254.169.254/…` from an untrusted AS/PRM
- * (§0) straight to IMDS/an internal host (SSRF). Here every hop — the initial URL
- * AND each `Location` (resolved against the current URL) — passes
- * `validateOAuthEndpointUrl` (§4, DNS-resolved) BEFORE it is fetched. A `Location`
- * the kernel rejects, a missing/invalid `Location`, or exceeding
+ * {@link pinnedFetch} resolves+validates+pins a single URL (spec §4, H2) and never
+ * follows a 3xx itself. Here the loop re-runs it for each hop — so the initial URL
+ * AND each `Location` (resolved against the current URL) is independently kernel-
+ * validated and pinned to a freshly-resolved IP; hop 0's IP is never reused. A
+ * `Location` the kernel rejects, a missing/invalid `Location`, or exceeding
* {@link MAX_DISCOVERY_REDIRECTS} is a typed fail-closed error, never followed.
*/
async function guardedFetch(
@@ -192,25 +221,19 @@ async function guardedFetch(
field: string,
deps: DiscoveryDeps
): Promise<
- { ok: true; response: Response; finalUrl: string } | { ok: false; error: DiscoveryError }
+ { ok: true; response: PinnedResponse; finalUrl: string } | { ok: false; error: DiscoveryError }
> {
let currentUrl = url
for (let hop = 0; ; hop++) {
- const errors = await validateOAuthEndpointUrl(currentUrl, field, {
+ const fetched = await pinnedFetch(currentUrl, field, {
resolveDns: deps.resolveDns,
+ transport: deps.transport,
+ timeoutMs: DISCOVERY_TIMEOUT_MS,
})
- if (errors.length > 0) {
- return { ok: false, error: { kind: 'kernel_rejected', field, errors } }
- }
- let response: Response
- try {
- response = await deps.fetchFn(currentUrl, {
- redirect: 'manual',
- signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
- })
- } catch (e) {
- return { ok: false, error: { kind: 'fetch_failed', url: currentUrl, detail: errMessage(e) } }
+ if (!fetched.ok) {
+ return { ok: false, error: mapPinnedError(fetched.error, currentUrl) }
}
+ const response = fetched.response
if (!isRedirectStatus(response.status)) {
return { ok: true, response, finalUrl: currentUrl }
}
@@ -224,7 +247,7 @@ async function guardedFetch(
},
}
}
- const location = response.headers.get('location')
+ const location = firstHeader(response.headers.location)
if (!location) {
return {
ok: false,
@@ -251,10 +274,10 @@ async function guardedFetch(
}
/**
- * Kernel-guard a URL and only then fetch it as JSON, following redirects through
- * the kernel (see {@link guardedFetch}). Structurally guarantees the spec §4
- * invariant: `validateOAuthEndpointUrl` runs BEFORE every `fetchFn`, and a URL the
- * kernel rejects is never fetched.
+ * Kernel-guard + pin a URL and only then parse it as JSON, following redirects
+ * through the pin (see {@link guardedFetch}). Structurally guarantees the spec §4
+ * invariant: validation runs BEFORE every fetch, and a URL the kernel rejects is
+ * never fetched.
*/
async function guardedFetchJson(
url: string,
@@ -264,7 +287,8 @@ async function guardedFetchJson(
const fetched = await guardedFetch(url, field, deps)
if (!fetched.ok) return fetched
const { response, finalUrl } = fetched
- if (!response.ok) {
+ const isOk = response.status >= 200 && response.status < 300
+ if (!isOk) {
return {
ok: false,
error: {
@@ -276,7 +300,7 @@ async function guardedFetchJson(
}
}
try {
- return { ok: true, json: await response.json() }
+ return { ok: true, json: JSON.parse(response.bodyText) }
} catch (e) {
return { ok: false, error: { kind: 'invalid_metadata', url: finalUrl, detail: errMessage(e) } }
}
@@ -408,30 +432,29 @@ async function resolvePrm(
const candidates: string[] = []
- // Best-effort probe for the challenge hint. The probe URL is kernel-guarded
- // first; a probe failure is non-fatal — the well-known candidates follow.
- const probeGuard = await validateOAuthEndpointUrl(mcpUrl, 'mcpUrl', {
+ // Best-effort probe for the challenge hint via the pinned fetch (kernel-guards +
+ // pins the mcpUrl before connecting). A kernel rejection is fatal (never probe an
+ // internal host); a transport/encoding failure is non-fatal — the well-known
+ // candidates follow. The pin never auto-follows a 3xx, so a redirecting MCP server
+ // simply yields no 401 hint here.
+ const probe = await pinnedFetch(mcpUrl, 'mcpUrl', {
resolveDns: deps.resolveDns,
+ transport: deps.transport,
+ timeoutMs: DISCOVERY_TIMEOUT_MS,
})
- if (probeGuard.length > 0) {
- return { ok: false, error: { kind: 'kernel_rejected', field: 'mcpUrl', errors: probeGuard } }
- }
- try {
- // `redirect:'manual'`: the probe URL is kernel-guarded above, but a 3xx from an
- // untrusted MCP server must NOT be auto-followed to an internal host. A redirect
- // simply yields no 401 hint here — the kernel-guarded well-known candidates below
- // are the fallback.
- const probe = await deps.fetchFn(mcpUrl, {
- method: 'GET',
- redirect: 'manual',
- signal: AbortSignal.timeout(DISCOVERY_TIMEOUT_MS),
- })
- if (probe.status === 401) {
- const hint = parseResourceMetadataChallenge(probe.headers.get('www-authenticate'))
- if (hint) candidates.push(hint)
+ if (!probe.ok) {
+ if (probe.error.kind === 'kernel_rejected') {
+ return {
+ ok: false,
+ error: { kind: 'kernel_rejected', field: 'mcpUrl', errors: probe.error.errors },
+ }
}
- } catch {
- // Probe failure is expected for some servers; fall back to well-known.
+ // transport / content-encoding failure of the probe is non-fatal — fall through.
+ } else if (probe.response.status === 401) {
+ const hint = parseResourceMetadataChallenge(
+ firstHeader(probe.response.headers['www-authenticate'])
+ )
+ if (hint) candidates.push(hint)
}
for (const wk of wellKnownPrmUrls(parsed)) {
diff --git a/control-api/src/routes/admin/index.ts b/control-api/src/routes/admin/index.ts
index 445e10caa..4a323b001 100644
--- a/control-api/src/routes/admin/index.ts
+++ b/control-api/src/routes/admin/index.ts
@@ -17,6 +17,7 @@ import { createAdminRecipeOauthRouter } from './recipeOauth.js'
import { createAdminRecipesRouter } from './recipes.js'
import { createAdminRegistryRouter } from './registry.js'
import { createRegistryConnectRouter } from './registryConnect.js'
+import { createAdminRemoteMcpRouter } from './remoteMcp.js'
import { createAdminResourcesRouter } from './resources.js'
import { createAdminSecretsRouter } from './secrets.js'
import { createAdminSharedFilesystemsRouter } from './sharedFilesystems.js'
@@ -36,6 +37,7 @@ export function createAdminRouter(gateway: K8sGateway): Router {
router.use(createAdminResourcesRouter(gateway))
router.use(createAdminRecipesRouter(gateway))
router.use(createAdminRecipeOauthRouter(gateway))
+ router.use(createAdminRemoteMcpRouter(gateway))
router.use(createAdminRegistryRouter(gateway))
router.use(createRegistryConnectRouter())
router.use(createAdminSharedFilesystemsRouter(gateway))
diff --git a/control-api/src/routes/admin/remoteMcp.ts b/control-api/src/routes/admin/remoteMcp.ts
new file mode 100644
index 000000000..cc878e29d
--- /dev/null
+++ b/control-api/src/routes/admin/remoteMcp.ts
@@ -0,0 +1,476 @@
+import { Router } from 'express'
+import { z } from 'zod'
+import { config } from '../../config.js'
+import { asyncHandler } from '../../http/asyncHandler.js'
+import { extractK8sError } from '../../http/k8sError.js'
+import { enforceNamespace } from '../../http/namespaceAudit.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 { type DiscoveryResult, discoverRemoteOAuth } from '../../oauth/discovery.js'
+import { rootLogger } from '../../observability/logger.js'
+import { K8sNotFoundError } from '../../services/resourceService.js'
+
+/**
+ * Admin "C-install" routes for the remote MCP-OAuth carril (spec 02 C1.5, DEC-12).
+ *
+ * Two routes, mounted under `/admin/*` (so `requireAuthForControlUI` already
+ * authenticated the caller as a control-ui admin):
+ *
+ * POST /admin/mcp-servers/remote/discover — dry-run: kernel-guard the URL, run
+ * RFC 9728→8414 discovery, return the "Detected" prefill for the C5 wizard. No
+ * writes.
+ * POST /admin/mcp-servers/remote — transactional install saga: re-run
+ * discovery server-side (D-4: discover only at install, then pin), create the
+ * Secret (confidential only) + McpServer CR + attach to the Context, with
+ * compensating rollback that preserves the original error.
+ *
+ * The written `spec.oauth` remote shape is the C3 CRD contract (see
+ * {@link buildRemoteOAuthSpec}). It is NOT admissible by the current CRD — C3
+ * legalizes `remote`×`oauth` — so this route's LIVE admission only works after C3.
+ * Until then the saga is unit-tested against a mocked K8sGateway.
+ *
+ * The engine (discovery, kernel §4) is C1; DCR (RFC 7591) lands in C2 — a DCR-mode
+ * install is rejected here with a clear message.
+ */
+
+const BASE = '/admin/mcp-servers/remote'
+
+const log = rootLogger.child({ module: 'admin-remote-mcp' })
+
+const discoverBodySchema = z.object({
+ baseUrl: z.string().min(1),
+})
+
+// Install body: serverName + contextRef + baseUrl + registration mode. A
+// pre-registered confidential client also carries clientId/clientSecret.
+const installBodySchema = z.object({
+ serverName: z.string().min(1),
+ contextRef: z.string().min(1),
+ baseUrl: z.string().min(1),
+ mode: z.enum(['cimd', 'pre-registered', 'dcr']),
+ clientId: z.string().min(1).optional(),
+ clientSecret: z.string().min(1).optional(),
+ grantScope: z.enum(['user', 'context']).optional(),
+})
+
+type InstallBody = z.infer<typeof installBodySchema>
+
+function isValidK8sName(name: string): boolean {
+ return RFC1123_RE.test(name) && name.length <= 253
+}
+
+/**
+ * The `spec.oauth` remote shape written to the CR — the C3 contract. Uses a distinct
+ * `source: 'remote'` discriminator instead of the closed 8-provider `provider` enum
+ * (D-10.3): a discovered remote client is NOT a baked provider. Endpoints are the
+ * pinned values discovery kernel-guarded; quirks (D-8) come from metadata. A
+ * confidential client references its Secret via `clientIdRef`/`clientSecretRef`
+ * (same nested ref shape as the baked carril); a public (CIMD) client carries no ref.
+ */
+export interface RemoteOAuthClientSecretRef {
+ name: string
+ key: string
+}
+
+export interface RemoteOAuthSpec {
+ /** Discriminator for the remote-discovered carril — never the baked `provider` enum. */
+ source: 'remote'
+ clientMode: 'public' | 'confidential'
+ authorizationEndpoint: string
+ tokenEndpoint: string
+ registrationEndpoint?: string
+ issuer: string
+ /** RFC 8707 value sent in authorize + token requests. */
+ resource: string
+ /** RFC 9207 issuer to validate the callback `iss` against (present only when advertised). */
+ issForCallback?: string
+ grantScope: 'user' | 'context'
+ scopes: string[]
+ /** D-8: token in the body, not the Authorization header. */
+ bearerInBody: boolean
+ /** D-8: fail-closed — false means never attempt a refresh. */
+ supportsRefresh: boolean
+ clientIdRef?: RemoteOAuthClientSecretRef
+ clientSecretRef?: RemoteOAuthClientSecretRef
+}
+
+function derivedScopes(result: DiscoveryResult): string[] {
+ return result.prm.scopes_supported ?? result.as.scopes_supported ?? []
+}
+
+function buildRemoteOAuthSpec(
+ result: DiscoveryResult,
+ opts: {
+ clientMode: 'public' | 'confidential'
+ grantScope: 'user' | 'context'
+ clientSecretName?: string
+ }
+): RemoteOAuthSpec {
+ const oauth: RemoteOAuthSpec = {
+ source: 'remote',
+ clientMode: opts.clientMode,
+ authorizationEndpoint: result.endpoints.authorization,
+ tokenEndpoint: result.endpoints.token,
+ issuer: result.issuer,
+ resource: result.resource,
+ grantScope: opts.grantScope,
+ scopes: derivedScopes(result),
+ bearerInBody: result.quirks.bearerInBody,
+ supportsRefresh: result.quirks.supportsRefresh,
+ }
+ if (result.endpoints.registration) oauth.registrationEndpoint = result.endpoints.registration
+ if (result.issForCallback) oauth.issForCallback = result.issForCallback
+ if (opts.clientMode === 'confidential' && opts.clientSecretName) {
+ oauth.clientIdRef = { name: opts.clientSecretName, key: 'client_id' }
+ oauth.clientSecretRef = { name: opts.clientSecretName, key: 'client_secret' }
+ }
+ return oauth
+}
+
+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
+const DELETE_SETTLE_TIMEOUT_MS = 10_000
+const DELETE_SETTLE_POLL_MS = 250
+
+const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
+
+/** Poll until a best-effort delete settles to a 404, so a re-install cannot 409. */
+async function waitForDeletion(readCurrent: () => Promise<unknown>, label: string): Promise<void> {
+ const deadline = Date.now() + DELETE_SETTLE_TIMEOUT_MS
+ while (Date.now() <= deadline) {
+ try {
+ await readCurrent()
+ } catch (err) {
+ if (extractK8sError(err)?.status === 404 || err instanceof K8sNotFoundError) return
+ throw err
+ }
+ await sleep(DELETE_SETTLE_POLL_MS)
+ }
+ throw new Error(`Timed out waiting for ${label} deletion`)
+}
+
+export function createAdminRemoteMcpRouter(gateway: K8sGateway): Router {
+ const router = Router()
+
+ // ── POST /admin/mcp-servers/remote/discover — dry-run, no writes ──────────
+ router.post(
+ `${BASE}/discover`,
+ asyncHandler(async (req: UiAuthedRequest, res) => {
+ const parsed = discoverBodySchema.safeParse(req.body)
+ if (!parsed.success) {
+ res.status(400).json({ error: 'baseUrl is required' })
+ return
+ }
+ const { baseUrl } = parsed.data
+
+ // Kernel §4: the admin-typed URL is untrusted input of origin — validate before
+ // any fetch (discovery also kernel-guards internally, but a clean 400 here gives
+ // the wizard immediate, field-level feedback).
+ const kernelErrors = await validateOAuthEndpointUrl(baseUrl, 'baseUrl')
+ if (kernelErrors.length > 0) {
+ res.status(400).json({ error: kernelErrors[0].message, errors: kernelErrors })
+ return
+ }
+
+ const outcome = await discoverRemoteOAuth(baseUrl, { logger: log })
+ if (!outcome.ok) {
+ log.warn({ discovery: outcome.error.kind }, 'remote discovery (dry-run) failed')
+ res.status(400).json({ error: 'discovery_failed', detail: outcome.error })
+ return
+ }
+
+ const r = outcome.result
+ res.status(200).json({
+ detected: {
+ registrationMode: r.registrationMode,
+ // DCR is not available until C2 — surfaced, not failed (spec C1.5).
+ ...(r.registrationMode === 'dcr'
+ ? {
+ dcr: {
+ available: false,
+ message: 'requires DCR (not available until C2)',
+ },
+ }
+ : {}),
+ endpoints: r.endpoints,
+ resource: r.resource,
+ issuer: r.issuer,
+ ...(r.issForCallback ? { issForCallback: r.issForCallback } : {}),
+ scopes: derivedScopes(r),
+ quirks: r.quirks,
+ },
+ })
+ })
+ )
+
+ // ── POST /admin/mcp-servers/remote — transactional install saga ───────────
+ router.post(
+ BASE,
+ // Namespace is server-determined; strip/audit any caller-supplied value.
+ enforceNamespace(config.mcpServersNamespace),
+ asyncHandler(async (req: UiAuthedRequest, res) => {
+ const parsed = installBodySchema.safeParse(req.body)
+ if (!parsed.success) {
+ res.status(400).json({ error: 'invalid_request', detail: parsed.error.issues })
+ return
+ }
+ const body: InstallBody = parsed.data
+
+ if (!isValidK8sName(body.serverName)) {
+ res.status(400).json({
+ error: 'invalid serverName: must be a valid K8s name (RFC 1123 label, max 253 chars)',
+ })
+ return
+ }
+ if (!isValidK8sName(body.contextRef)) {
+ res.status(400).json({ error: 'invalid contextRef' })
+ return
+ }
+
+ // DCR lands in C2 — reject clearly rather than half-install.
+ if (body.mode === 'dcr') {
+ res.status(400).json({
+ error: 'dcr_not_available',
+ message: 'dynamic client registration is not yet available (lands in C2)',
+ })
+ return
+ }
+
+ let clientMode: 'public' | 'confidential'
+ if (body.mode === 'pre-registered') {
+ if (!body.clientId || !body.clientSecret) {
+ res.status(400).json({
+ error: 'pre-registered confidential client requires clientId and clientSecret',
+ })
+ return
+ }
+ clientMode = 'confidential'
+ } else {
+ // CIMD → public client, no secret.
+ clientMode = 'public'
+ }
+
+ // Kernel §4 on the admin-typed baseUrl (explicit 400 before discovery).
+ const kernelErrors = await validateOAuthEndpointUrl(body.baseUrl, 'baseUrl')
+ if (kernelErrors.length > 0) {
+ res.status(400).json({ error: kernelErrors[0].message, errors: kernelErrors })
+ return
+ }
+
+ // D-4: re-run discovery SERVER-SIDE at install and pin the result — never trust
+ // the client-passed prefill as authoritative. Discovery kernel-guards baseUrl +
+ // every discovered endpoint internally before returning them.
+ const outcome = await discoverRemoteOAuth(
+ body.baseUrl,
+ { logger: log },
+ { hasPreRegisteredClient: clientMode === 'confidential' }
+ )
+ if (!outcome.ok) {
+ log.warn({ discovery: outcome.error.kind }, 'remote install discovery failed')
+ res.status(400).json({ error: 'discovery_failed', detail: outcome.error })
+ return
+ }
+ const discovery = outcome.result
+
+ // CIMD-mode install requires the AS to actually support the public CIMD carril.
+ if (clientMode === 'public' && discovery.registrationMode !== 'cimd') {
+ if (discovery.registrationMode === 'dcr') {
+ res.status(400).json({
+ error: 'dcr_not_available',
+ message:
+ 'this authorization server requires dynamic client registration, not yet available (C2)',
+ })
+ return
+ }
+ res.status(400).json({
+ error: 'mode_unsupported',
+ message: `authorization server does not support CIMD (detected mode: ${discovery.registrationMode})`,
+ })
+ return
+ }
+
+ const targetNs = config.mcpServersNamespace
+ const serverName = body.serverName
+ const contextRef = body.contextRef
+ const grantScope = body.grantScope ?? 'user'
+
+ const managedLabels: Record<string, string> = {
+ 'clerum.io/managed-by': 'control-api',
+ 'clerum.io/server-mode': 'remote',
+ }
+
+ // Build the McpServer spec. transport routes through the HCC nginx egress proxy
+ // (D-2); the pinned oauth block is the C3 CRD contract.
+ const upstreamPath = new URL(body.baseUrl).pathname || '/'
+ const clientSecretName =
+ clientMode === 'confidential' ? `${serverName}-oauth-client` : undefined
+
+ const oauthSpec = buildRemoteOAuthSpec(discovery, {
+ clientMode,
+ grantScope,
+ clientSecretName,
+ })
+
+ const mcpServerSpec: Record<string, unknown> = {
+ image: REMOTE_MCP_EGRESS_PROXY_IMAGE,
+ contextRef,
+ enabled: true,
+ managed: true,
+ transport: {
+ type: 'streamableHttp',
+ port: REMOTE_MCP_PROXY_PORT,
+ url: `http://${serverName}.${targetNs}.svc.cluster.local:${REMOTE_MCP_PROXY_PORT}${upstreamPath}`,
+ },
+ remote: { baseUrl: body.baseUrl },
+ // Bicondicional (D-10): remote+oauth MUST carry auth.type:'oauth'.
+ auth: { type: 'oauth' },
+ oauth: oauthSpec,
+ // The proxy egresses to the remote MCP host; NetworkPolicy is generated from this.
+ egressBindings: [
+ {
+ egressClass: 'exact-host',
+ dns: new URL(body.baseUrl).hostname,
+ port: 443,
+ protocol: 'TCP',
+ },
+ ],
+ }
+
+ // ── Saga step 1: create the client Secret (confidential only) ─────────
+ let secretCreated = false
+ if (clientMode === 'confidential' && clientSecretName) {
+ try {
+ await gateway.createSecret({
+ name: clientSecretName,
+ namespace: targetNs,
+ type: 'Opaque',
+ labels: managedLabels,
+ stringData: {
+ client_id: body.clientId as string,
+ client_secret: body.clientSecret as string,
+ },
+ })
+ } catch (err) {
+ const k8sErr = extractK8sError(err)
+ if (k8sErr) {
+ res.status(k8sErr.status).json({ error: `Secret creation failed: ${k8sErr.message}` })
+ return
+ }
+ throw err
+ }
+ secretCreated = true
+ // Names-only audit: never echo the secret material.
+ log.info(
+ {
+ event: 'remote_oauth_secret_created',
+ secretName: clientSecretName,
+ namespace: targetNs,
+ },
+ 'remote oauth client secret created'
+ )
+ }
+
+ // ── Saga step 2: create the McpServer CR (rollback Secret on failure) ──
+ try {
+ await gateway.createResource(
+ 'mcpservers',
+ { metadata: { name: serverName, labels: managedLabels }, spec: mcpServerSpec },
+ targetNs
+ )
+ } catch (err) {
+ if (secretCreated && clientSecretName) {
+ try {
+ await gateway.deleteSecret(clientSecretName, targetNs)
+ } catch {
+ // Best-effort rollback; preserve the original CR-create error.
+ }
+ }
+ const k8sErr = extractK8sError(err)
+ if (k8sErr) {
+ res.status(k8sErr.status).json({ error: k8sErr.message })
+ return
+ }
+ throw err
+ }
+
+ // ── Saga step 3: attach to the Context allowlist (rollback CR+Secret) ──
+ try {
+ const ctx = (await gateway.getResource('contexts', contextRef)) as {
+ spec?: Record<string, unknown> & { contextId?: string; mcpServers?: string[] }
+ }
+ const existing: string[] = ctx.spec?.mcpServers ?? []
+ if (!existing.includes(serverName)) {
+ await gateway.updateResource('contexts', contextRef, {
+ spec: {
+ ...ctx.spec,
+ contextId: ctx.spec?.contextId ?? contextRef,
+ mcpServers: [...existing, serverName],
+ } as Record<string, unknown>,
+ })
+ }
+ } catch (err) {
+ try {
+ await gateway.deleteResource('mcpservers', serverName, targetNs)
+ await waitForDeletion(
+ () => gateway.getResource('mcpservers', serverName, targetNs),
+ `McpServer/${serverName}`
+ )
+ } catch {
+ // Best-effort rollback; preserve the original attach error.
+ }
+ if (secretCreated && clientSecretName) {
+ try {
+ await gateway.deleteSecret(clientSecretName, targetNs)
+ await waitForDeletion(
+ () => gateway.getSecret(clientSecretName, targetNs),
+ `Secret/${clientSecretName}`
+ )
+ } catch {
+ // Best-effort rollback; preserve the original attach error.
+ }
+ }
+ const k8sErr = extractK8sError(err)
+ const notFound = err instanceof K8sNotFoundError
+ const message =
+ k8sErr?.message ||
+ (notFound
+ ? `context "${contextRef}" not found`
+ : err instanceof Error
+ ? err.message
+ : 'Failed to update Context allowlist')
+ res
+ .status(k8sErr?.status ?? (notFound ? 404 : 500))
+ .json({ error: `Context allowlist update failed: ${message}` })
+ return
+ }
+
+ log.info(
+ {
+ event: 'remote_oauth_server_installed',
+ serverName,
+ namespace: targetNs,
+ contextRef,
+ clientMode,
+ registrationMode: discovery.registrationMode,
+ },
+ 'remote oauth mcp server installed'
+ )
+
+ // Names-only summary — never echo the secret material or the pinned tokens.
+ res.status(201).json({
+ serverName,
+ namespace: targetNs,
+ contextRef,
+ contextUpdated: true,
+ clientMode,
+ registrationMode: discovery.registrationMode,
+ ...(clientSecretName ? { clientSecretName } : {}),
+ })
+ })
+ )
+
+ return router
+}
diff --git a/control-api/test/fixtures/remoteOAuthDiscovery.ts b/control-api/test/fixtures/remoteOAuthDiscovery.ts
index 513685305..085082738 100644
--- a/control-api/test/fixtures/remoteOAuthDiscovery.ts
+++ b/control-api/test/fixtures/remoteOAuthDiscovery.ts
@@ -21,6 +21,7 @@
* Provenance: scratchpad/c1-fixtures-provenance.md (sondeo en vivo 2026-09-20,
* sección "EVIDENCIA GET").
*/
+import type { PinnedTransport } from '../../src/http/pinnedFetch.js'
// ─── Notion (resource base sin path) ────────────────────────────────────────
// PRM: GET https://mcp.notion.com/.well-known/oauth-protected-resource → 200
@@ -129,36 +130,33 @@ export const PILOTS: Record<'notion' | 'linear' | 'sentry' | 'canva', PilotFixtu
}
/**
- * Build a `fetch`-shaped mock from a pilot fixture: a 401 (with WWW-Authenticate)
- * on the MCP probe when the fixture has a hint, 200+JSON on the served well-known
- * URLs, and 404 on the URLs the real server does not serve. Mirrors the real HTTP
- * responses so the discovery code path is exercised, not a hand-invented one.
+ * Build a {@link PinnedTransport}-shaped mock from a pilot fixture: a 401 (with
+ * WWW-Authenticate) on the MCP probe when the fixture has a hint, 200+JSON on the
+ * served well-known URLs, and 404 on the URLs the real server does not serve.
+ * Mirrors the real HTTP responses so the discovery code path is exercised, not a
+ * hand-invented one. Discovery now fetches through the IP-pinned `node:https`
+ * transport (H2), so the test double is a transport, not a `fetch`.
*/
-export function makeDiscoveryFetch(pilot: PilotFixture): typeof fetch {
+export function makeDiscoveryTransport(pilot: PilotFixture): PinnedTransport {
const jsonByUrl = new Map<string, string>([
[pilot.prm.url, pilot.prm.json],
[pilot.as.url, pilot.as.json],
])
const notFound = new Set(pilot.prmNotFound ?? [])
- const fn = async (input: string | URL | Request, init?: RequestInit): Promise<Response> => {
- const url = typeof input === 'string' ? input : input.toString()
- // MCP probe (GET) → 401 with the challenge header when the fixture has one.
- if (url === pilot.mcpUrl && (init?.method ?? 'GET') === 'GET') {
+ return async ({ url }) => {
+ // MCP probe → 401 with the challenge header when the fixture has one.
+ if (url === pilot.mcpUrl) {
if (pilot.wwwAuthenticate) {
- return new Response(null, {
- status: 401,
- headers: { 'www-authenticate': pilot.wwwAuthenticate },
- })
+ return { status: 401, headers: { 'www-authenticate': pilot.wwwAuthenticate }, bodyText: '' }
}
// No challenge advertised — probe returns a plain 401 with no hint.
- return new Response(null, { status: 401 })
+ return { status: 401, headers: {}, bodyText: '' }
}
const body = jsonByUrl.get(url)
if (body !== undefined) {
- return new Response(body, { status: 200, headers: { 'content-type': 'application/json' } })
+ return { status: 200, headers: { 'content-type': 'application/json' }, bodyText: body }
}
- if (notFound.has(url)) return new Response('not found', { status: 404 })
- return new Response('unexpected url', { status: 404 })
+ if (notFound.has(url)) return { status: 404, headers: {}, bodyText: 'not found' }
+ return { status: 404, headers: {}, bodyText: 'unexpected url' }
}
- return fn as unknown as typeof fetch
}
diff --git a/control-api/test/oauth.discovery.test.ts b/control-api/test/oauth.discovery.test.ts
index f7f93bb8a..cb1252df6 100644
--- a/control-api/test/oauth.discovery.test.ts
+++ b/control-api/test/oauth.discovery.test.ts
@@ -1,4 +1,5 @@
import { describe, expect, it, vi } from 'vitest'
+import type { PinnedRawResponse, PinnedTransport } from '../src/http/pinnedFetch.js'
import {
type DiscoveryDeps,
asMetadataUrls,
@@ -6,24 +7,33 @@ import {
parseResourceMetadataChallenge,
wellKnownPrmUrls,
} from '../src/oauth/discovery.js'
-import { PILOTS, makeDiscoveryFetch } from './fixtures/remoteOAuthDiscovery.js'
+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
/**
- * Discovery client (spec 19 §4/§5 C1). Fixtures are the real 2026-09-20 probe
- * bytes (T1). `resolveDns` is injected so the kernel runs without a cluster.
+ * Discovery client (spec 19 §4/§5 C1 + C1.5 H2 pin). Fixtures are the real
+ * 2026-09-20 probe bytes (T1). Discovery fetches through the IP-pinned `node:https`
+ * transport, injected here so the pin runs without a cluster; `resolveDns` is
+ * injected so the kernel runs without real DNS.
*/
const PUBLIC_IP = ['93.184.216.34']
const publicDns = () => vi.fn(async () => PUBLIC_IP)
-function deps(pilotFetch: typeof fetch, resolveDns = publicDns()): DiscoveryDeps {
- return { fetchFn: pilotFetch, resolveDns }
+/** A transport built from an inline `(url) => {status, headers, bodyText}` responder. */
+function transportOf(
+ respond: (url: string) => Promise<PinnedRawResponse> | PinnedRawResponse
+): PinnedTransport {
+ return async ({ url }) => respond(url)
+}
+
+function deps(transport: PinnedTransport, resolveDns = publicDns()): DiscoveryDeps {
+ return { transport, resolveDns }
}
describe('discoverRemoteOAuth — 4 CIMD pilots (T1 real fixtures)', () => {
for (const key of ['notion', 'linear', 'sentry', 'canva'] as const) {
const pilot = PILOTS[key]
it(`${key}: resolves PRM→AS, selects CIMD, pins endpoints`, async () => {
- const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(makeDiscoveryFetch(pilot)))
+ const outcome = await discoverRemoteOAuth(pilot.mcpUrl, deps(makeDiscoveryTransport(pilot)))
expect(outcome.ok).toBe(true)
if (!outcome.ok) return
const r = outcome.result
@@ -45,13 +55,13 @@ describe('discoverRemoteOAuth — 4 CIMD pilots (T1 real fixtures)', () => {
it('sentry: exposes issForCallback (RFC 9207); others do not', async () => {
const sentry = await discoverRemoteOAuth(
PILOTS.sentry.mcpUrl,
- deps(makeDiscoveryFetch(PILOTS.sentry))
+ deps(makeDiscoveryTransport(PILOTS.sentry))
)
expect(sentry.ok && sentry.result.issForCallback).toBe('https://mcp.sentry.dev')
const notion = await discoverRemoteOAuth(
PILOTS.notion.mcpUrl,
- deps(makeDiscoveryFetch(PILOTS.notion))
+ deps(makeDiscoveryTransport(PILOTS.notion))
)
expect(notion.ok && notion.result.issForCallback).toBeUndefined()
})
@@ -60,7 +70,7 @@ describe('discoverRemoteOAuth — 4 CIMD pilots (T1 real fixtures)', () => {
// Sentry root well-known 404s; discovery must follow the 401 hint.
const outcome = await discoverRemoteOAuth(
PILOTS.sentry.mcpUrl,
- deps(makeDiscoveryFetch(PILOTS.sentry))
+ deps(makeDiscoveryTransport(PILOTS.sentry))
)
expect(outcome.ok).toBe(true)
if (outcome.ok) expect(outcome.result.prm.resource).toBe('https://mcp.sentry.dev/mcp')
@@ -68,18 +78,18 @@ describe('discoverRemoteOAuth — 4 CIMD pilots (T1 real fixtures)', () => {
})
describe('discoverRemoteOAuth — kernel §4 before every fetch (invariant 2, T5)', () => {
- it('calls the kernel (resolveDns) before fetching each URL', async () => {
+ it('resolves DNS (kernel) before fetching each URL', async () => {
const order: string[] = []
const resolveDns = vi.fn(async (host: string) => {
order.push(`dns:${host}`)
return PUBLIC_IP
})
- const base = makeDiscoveryFetch(PILOTS.notion)
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- order.push(`fetch:${typeof input === 'string' ? input : input.toString()}`)
- return base(input, init)
- }) as unknown as typeof fetch
- const outcome = await discoverRemoteOAuth(PILOTS.notion.mcpUrl, { fetchFn, resolveDns })
+ const base = makeDiscoveryTransport(PILOTS.notion)
+ const transport: PinnedTransport = async input => {
+ order.push(`fetch:${input.url}`)
+ return base(input)
+ }
+ const outcome = await discoverRemoteOAuth(PILOTS.notion.mcpUrl, { transport, resolveDns })
expect(outcome.ok).toBe(true)
// Every fetch is immediately preceded by a DNS resolve of its host — no fetch
// ever appears before its guarding resolve.
@@ -96,13 +106,16 @@ describe('discoverRemoteOAuth — kernel §4 before every fetch (invariant 2, T5
it('rejects a PRM host resolving to a private IP WITHOUT fetching it', async () => {
const resolveDns = vi.fn(async () => ['10.0.0.5'])
- const fetchFn = vi.fn(
- async () => new Response('{}', { status: 200 })
- ) as unknown as typeof fetch
- const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })
+ const transport = vi.fn(
+ async () => ({ status: 200, headers: {}, bodyText: '{}' }) as PinnedRawResponse
+ )
+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
+ transport,
+ resolveDns,
+ })
expect(outcome.ok).toBe(false)
if (!outcome.ok) expect(outcome.error.kind).toBe('kernel_rejected')
- expect(fetchFn).not.toHaveBeenCalled()
+ expect(transport).not.toHaveBeenCalled()
})
it('skips a kernel-rejected WWW-Authenticate hint and never fetches it', async () => {
@@ -113,143 +126,244 @@ describe('discoverRemoteOAuth — kernel §4 before every fetch (invariant 2, T5
if (host === 'metadata.internal') return ['169.254.169.254']
return PUBLIC_IP
})
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- const url = typeof input === 'string' ? input : input.toString()
- if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {
- return new Response(null, { status: 401, headers: { 'www-authenticate': evilHint } })
+ const transport = vi.fn(async ({ url }: { url: string }): Promise<PinnedRawResponse> => {
+ if (url === 'https://mcp.notion.com/mcp') {
+ return { status: 401, headers: { 'www-authenticate': evilHint }, bodyText: '' }
}
if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {
- return new Response(PILOTS.notion.prm.json, { status: 200 })
+ return { status: 200, headers: {}, bodyText: PILOTS.notion.prm.json }
}
if (url === 'https://mcp.notion.com/.well-known/oauth-authorization-server') {
- return new Response(PILOTS.notion.as.json, { status: 200 })
+ return { status: 200, headers: {}, bodyText: PILOTS.notion.as.json }
}
- return new Response('nf', { status: 404 })
- }) as unknown as typeof fetch
- const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
+ transport,
+ resolveDns,
+ })
expect(outcome.ok).toBe(true)
// The internal host was never fetched.
- const fetchedUrls = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>
- String(c[0])
- )
+ const fetchedUrls = transport.mock.calls.map(c => c[0].url)
expect(fetchedUrls.some(u => u.includes('metadata.internal'))).toBe(false)
})
})
-describe('discoverRemoteOAuth — SSRF via redirects (H1: redirect:manual + re-validate)', () => {
- it('does NOT follow a 302 → IMDS from a well-known fetch (rejected by the kernel)', async () => {
+describe('discoverRemoteOAuth — IP pin (H2: DNS-rebinding/TOCTOU, T3)', () => {
+ it('connects the socket to the validated IP and never re-resolves (resolveDns once per hop)', async () => {
+ // resolveDns returns a PUBLIC ip; the pin must connect to THAT ip. The transport
+ // invokes the pinned lookup (as node:https would) and records the address it gets.
const resolveDns = vi.fn(async () => PUBLIC_IP)
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
+ const connectedIps: string[] = []
+ let extraResolvesDuringConnect = 0
+ const base = makeDiscoveryTransport(PILOTS.notion)
+ const transport: PinnedTransport = async input => {
+ // Simulate node:https connect: ask the (pinned) lookup for the address. The
+ // lookup MUST be a pure closure over the validated IPs — it must NOT trigger
+ // another resolveDns call (that second resolution is the rebinding window).
+ const before = resolveDns.mock.calls.length
+ await new Promise<void>(resolve => {
+ input.lookup(new URL(input.url).hostname, { all: true }, (_err, addrs) => {
+ const list = Array.isArray(addrs) ? addrs : [{ address: addrs as string }]
+ list.forEach(a => connectedIps.push(a.address))
+ resolve()
+ })
+ })
+ extraResolvesDuringConnect += resolveDns.mock.calls.length - before
+ return base(input)
+ }
+ const outcome = await discoverRemoteOAuth(PILOTS.notion.mcpUrl, { transport, resolveDns })
+ expect(outcome.ok).toBe(true)
+ // The socket connected to the validated public IP on every hop — no rebind.
+ expect(connectedIps.length).toBeGreaterThan(0)
+ connectedIps.forEach(ip => expect(ip).toBe(PUBLIC_IP[0]))
+ // The pin re-used the validated addresses; the connect never re-resolved DNS.
+ expect(extraResolvesDuringConnect).toBe(0)
+ })
+
+ it('T3: a rebinding decoy (public at validation, private at connect) cannot reach the private IP', async () => {
+ // The rebind: validation resolves PUBLIC; a naive re-resolving HTTP client would
+ // resolve PRIVATE at connect. The pin removes the second resolution, so the socket
+ // stays on the validated PUBLIC ip. This test also runs against the PRE-FIX head
+ // (which used a re-resolving `fetch`): there the vulnerable `fetchFn` seam records
+ // the PRIVATE connect ip and the assertion fails — proving the fix.
+ const PRIVATE_IP = '169.254.169.254'
+ const validationDns = vi.fn(async () => PUBLIC_IP)
+ const connectedIps: string[] = []
+ const base = makeDiscoveryTransport(PILOTS.notion)
+
+ // HEAD seam: pinned transport — invokes the pinned lookup, connects to the pin.
+ const transport: PinnedTransport = async input => {
+ await new Promise<void>(resolve => {
+ input.lookup(new URL(input.url).hostname, { all: true }, (_err, addrs) => {
+ const list = Array.isArray(addrs) ? addrs : [{ address: addrs as string }]
+ list.forEach(a => connectedIps.push(a.address))
+ resolve()
+ })
+ })
+ return base(input)
+ }
+
+ // PRE-FIX seam: the old `fetchFn` re-resolved at connect. Model that vulnerable
+ // client so the same test has teeth against the parent sha (see Repro-test note).
+ const fetchFn = (async (input: string | URL | Request, init?: RequestInit) => {
const url = typeof input === 'string' ? input : input.toString()
- if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {
- return new Response(null, { status: 401 })
+ // Re-resolution at connect returns the rebind PRIVATE ip.
+ connectedIps.push(PRIVATE_IP)
+ const r = await base({
+ url,
+ method: (init?.method as 'GET') ?? 'GET',
+ headers: {},
+ lookup: (() => {}) as never,
+ signal: AbortSignal.timeout(1000),
+ maxBodyBytes: 1,
+ })
+ return new Response(r.bodyText || null, {
+ status: r.status,
+ headers: r.headers as Record<string, string>,
+ })
+ }) as unknown as typeof fetch
+
+ // Spread avoids excess-property checking so the pre-fix `fetchFn` key rides along;
+ // HEAD reads `transport`, the parent reads `fetchFn` — same file, both seams.
+ const depsBoth = { transport, resolveDns: validationDns, fetchFn } as unknown as DiscoveryDeps
+ await discoverRemoteOAuth(PILOTS.notion.mcpUrl, depsBoth)
+
+ expect(connectedIps.length).toBeGreaterThan(0)
+ // The connection never touched the private rebind ip.
+ expect(connectedIps).not.toContain(PRIVATE_IP)
+ connectedIps.forEach(ip => expect(ip).toBe(PUBLIC_IP[0]))
+ })
+
+ it('fails closed on a non-identity content-encoding (never mis-parses, T5)', async () => {
+ // A hostile server returns gzip bytes despite Accept-Encoding: identity; discovery
+ // must reject rather than JSON.parse compressed bytes.
+ const resolveDns = vi.fn(async () => PUBLIC_IP)
+ const transport = transportOf(url => {
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
+ if (url.startsWith('https://mcp.notion.com/.well-known/oauth-protected-resource')) {
+ return {
+ status: 200,
+ headers: { 'content-encoding': 'gzip', 'content-type': 'application/json' },
+ bodyText: '\u001f\u008b garbage',
+ }
}
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
+ transport,
+ resolveDns,
+ })
+ expect(outcome.ok).toBe(false)
+ if (!outcome.ok) expect(outcome.error.kind).toBe('content_encoding_rejected')
+ })
+})
+
+describe('discoverRemoteOAuth — SSRF via redirects (H1: manual redirect + re-validate + re-pin)', () => {
+ it('does NOT follow a 302 → IMDS from a well-known fetch (rejected by the kernel)', async () => {
+ const resolveDns = vi.fn(async () => PUBLIC_IP)
+ const transport = vi.fn(async ({ url }: { url: string }): Promise<PinnedRawResponse> => {
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
// Every PRM well-known candidate 302s at the link-local IMDS address.
if (url.startsWith('https://mcp.notion.com/.well-known/oauth-protected-resource')) {
- return new Response(null, {
+ return {
status: 302,
headers: { location: 'http://169.254.169.254/latest/meta-data/' },
- })
+ bodyText: '',
+ }
}
- return new Response('nf', { status: 404 })
- }) as unknown as typeof fetch
- const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
+ transport,
+ resolveDns,
+ })
expect(outcome.ok).toBe(false)
if (!outcome.ok) expect(outcome.error.kind).toBe('kernel_rejected')
- const fetched = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>
- String(c[0])
- )
+ const fetched = transport.mock.calls.map(c => c[0].url)
expect(fetched.some(u => u.includes('169.254.169.254'))).toBe(false)
})
it('does NOT follow a 302 → internal .svc host (rejected by the kernel)', async () => {
const resolveDns = vi.fn(async () => PUBLIC_IP)
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- const url = typeof input === 'string' ? input : input.toString()
- if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {
- return new Response(null, { status: 401 })
- }
+ const transport = vi.fn(async ({ url }: { url: string }): Promise<PinnedRawResponse> => {
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
if (url.startsWith('https://mcp.notion.com/.well-known/oauth-protected-resource')) {
- return new Response(null, {
+ return {
status: 302,
headers: { location: 'http://control-api.mcp-host.svc/.well-known/x' },
- })
+ bodyText: '',
+ }
}
- return new Response('nf', { status: 404 })
- }) as unknown as typeof fetch
- const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
+ transport,
+ resolveDns,
+ })
expect(outcome.ok).toBe(false)
if (!outcome.ok) expect(outcome.error.kind).toBe('kernel_rejected')
- const fetched = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>
- String(c[0])
- )
+ const fetched = transport.mock.calls.map(c => c[0].url)
expect(fetched.some(u => u.includes('.svc'))).toBe(false)
})
it('fails closed (redirect_blocked) when the hop count is exceeded', async () => {
const resolveDns = vi.fn(async () => PUBLIC_IP)
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- const url = typeof input === 'string' ? input : input.toString()
- if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {
- return new Response(null, { status: 401 })
- }
+ const transport = transportOf(url => {
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
// A public host that keeps redirecting to itself — never terminates.
- return new Response(null, {
- status: 302,
- headers: { location: 'https://loop.example.com/next' },
- })
- }) as unknown as typeof fetch
- const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })
+ return { status: 302, headers: { location: 'https://loop.example.com/next' }, bodyText: '' }
+ })
+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
+ transport,
+ resolveDns,
+ })
expect(outcome.ok).toBe(false)
if (!outcome.ok) expect(outcome.error.kind).toBe('redirect_blocked')
})
- it('DOES follow a kernel-approved redirect to a public host', async () => {
+ it('DOES follow a kernel-approved redirect to a public host (re-pinned per hop)', async () => {
const resolveDns = vi.fn(async () => PUBLIC_IP)
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- const url = typeof input === 'string' ? input : input.toString()
- if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {
- return new Response(null, { status: 401 })
- }
+ const transport = transportOf(url => {
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {
- return new Response(null, {
+ return {
status: 302,
headers: { location: 'https://mcp.notion.com/prm-moved' },
- })
+ bodyText: '',
+ }
}
if (url === 'https://mcp.notion.com/prm-moved') {
- return new Response(PILOTS.notion.prm.json, { status: 200 })
+ return { status: 200, headers: {}, bodyText: PILOTS.notion.prm.json }
}
if (url === 'https://mcp.notion.com/.well-known/oauth-authorization-server') {
- return new Response(PILOTS.notion.as.json, { status: 200 })
+ return { status: 200, headers: {}, bodyText: PILOTS.notion.as.json }
}
- return new Response('nf', { status: 404 })
- }) as unknown as typeof fetch
- const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', { fetchFn, resolveDns })
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
+ const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
+ transport,
+ resolveDns,
+ })
expect(outcome.ok).toBe(true)
if (outcome.ok) expect(outcome.result.resource).toBe('https://mcp.notion.com')
- const fetched = (fetchFn as unknown as ReturnType<typeof vi.fn>).mock.calls.map(c =>
- String(c[0])
- )
- expect(fetched).toContain('https://mcp.notion.com/prm-moved')
+ // The redirect target's host was re-resolved (re-pinned) before the follow-up fetch.
+ expect(resolveDns.mock.calls.length).toBeGreaterThan(0)
})
})
describe('discoverRemoteOAuth — third-party metadata self-consistency (C2/C3)', () => {
it('C2: rejects a PRM whose resource is cross-origin (RFC 9728 §3.3)', async () => {
const evilPrm = { ...JSON.parse(PILOTS.notion.prm.json), resource: 'https://evil.example.com' }
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- const url = typeof input === 'string' ? input : input.toString()
- if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {
- return new Response(null, { status: 401 })
- }
+ const transport = transportOf(url => {
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
if (url.startsWith('https://mcp.notion.com/.well-known/oauth-protected-resource')) {
- return new Response(JSON.stringify(evilPrm), { status: 200 })
+ return { status: 200, headers: {}, bodyText: JSON.stringify(evilPrm) }
}
- return new Response('nf', { status: 404 })
- }) as unknown as typeof fetch
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
- fetchFn,
+ transport,
resolveDns: publicDns(),
})
expect(outcome.ok).toBe(false)
@@ -260,7 +374,7 @@ describe('discoverRemoteOAuth — third-party metadata self-consistency (C2/C3)'
for (const key of ['notion', 'linear'] as const) {
const outcome = await discoverRemoteOAuth(
PILOTS[key].mcpUrl,
- deps(makeDiscoveryFetch(PILOTS[key]))
+ deps(makeDiscoveryTransport(PILOTS[key]))
)
expect(outcome.ok).toBe(true)
if (outcome.ok)
@@ -270,13 +384,10 @@ describe('discoverRemoteOAuth — third-party metadata self-consistency (C2/C3)'
it('C3: rejects AS metadata whose issuer != authorization server base (RFC 8414 §3.3)', async () => {
const evilAs = { ...JSON.parse(PILOTS.notion.as.json), issuer: 'https://evil.example.com' }
- const fetchFn = vi.fn(async (input: string | URL | Request, init?: RequestInit) => {
- const url = typeof input === 'string' ? input : input.toString()
- if (url === 'https://mcp.notion.com/mcp' && (init?.method ?? 'GET') === 'GET') {
- return new Response(null, { status: 401 })
- }
+ const transport = transportOf(url => {
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {
- return new Response(PILOTS.notion.prm.json, { status: 200 })
+ return { status: 200, headers: {}, bodyText: PILOTS.notion.prm.json }
}
// The evil issuer is served on BOTH AS-metadata candidates (oauth + OIDC),
// so neither clears the RFC 8414 §3.3 check.
@@ -284,12 +395,12 @@ describe('discoverRemoteOAuth — third-party metadata self-consistency (C2/C3)'
url === 'https://mcp.notion.com/.well-known/oauth-authorization-server' ||
url === 'https://mcp.notion.com/.well-known/openid-configuration'
) {
- return new Response(JSON.stringify(evilAs), { status: 200 })
+ return { status: 200, headers: {}, bodyText: JSON.stringify(evilAs) }
}
- return new Response('nf', { status: 404 })
- }) as unknown as typeof fetch
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
- fetchFn,
+ transport,
resolveDns: publicDns(),
})
expect(outcome.ok).toBe(false)
@@ -300,7 +411,7 @@ describe('discoverRemoteOAuth — third-party metadata self-consistency (C2/C3)'
for (const key of ['notion', 'sentry'] as const) {
const outcome = await discoverRemoteOAuth(
PILOTS[key].mcpUrl,
- deps(makeDiscoveryFetch(PILOTS[key]))
+ deps(makeDiscoveryTransport(PILOTS[key]))
)
expect(outcome.ok).toBe(true)
if (outcome.ok) expect(outcome.result.issuer).toBe(JSON.parse(PILOTS[key].as.json).issuer)
@@ -312,19 +423,18 @@ describe('discoverRemoteOAuth — fail-closed without S256 (invariant 3, T5)', (
it('refuses when code_challenge_methods_supported lacks S256', async () => {
const noS256As = JSON.parse(PILOTS.notion.as.json)
noS256As.code_challenge_methods_supported = ['plain']
- const fetchFn = vi.fn(async (input: string | URL | Request) => {
- const url = String(input)
+ const transport = transportOf(url => {
if (url === 'https://mcp.notion.com/.well-known/oauth-protected-resource') {
- return new Response(PILOTS.notion.prm.json, { status: 200 })
+ return { status: 200, headers: {}, bodyText: PILOTS.notion.prm.json }
}
if (url === 'https://mcp.notion.com/.well-known/oauth-authorization-server') {
- return new Response(JSON.stringify(noS256As), { status: 200 })
+ return { status: 200, headers: {}, bodyText: JSON.stringify(noS256As) }
}
- if (url === 'https://mcp.notion.com/mcp') return new Response(null, { status: 401 })
- return new Response('nf', { status: 404 })
- }) as unknown as typeof fetch
+ if (url === 'https://mcp.notion.com/mcp') return { status: 401, headers: {}, bodyText: '' }
+ return { status: 404, headers: {}, bodyText: 'nf' }
+ })
const outcome = await discoverRemoteOAuth('https://mcp.notion.com/mcp', {
- fetchFn,
+ transport,
resolveDns: vi.fn(async () => PUBLIC_IP),
})
expect(outcome.ok).toBe(false)
diff --git a/control-api/test/routes.adminRemoteMcp.test.ts b/control-api/test/routes.adminRemoteMcp.test.ts
new file mode 100644
index 000000000..311d35b28
--- /dev/null
+++ b/control-api/test/routes.adminRemoteMcp.test.ts
@@ -0,0 +1,318 @@
+import { beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
+import express from 'express'
+import request from 'supertest'
+import { config } from '../src/config.js'
+import type { K8sGateway } from '../src/k8s.js'
+import {
+ type DiscoveryOutcome,
+ type DiscoveryResult,
+ discoverRemoteOAuth,
+} from '../src/oauth/discovery.js'
+import { createAdminRemoteMcpRouter } from '../src/routes/admin/remoteMcp.js'
+import { PILOTS, makeDiscoveryTransport } from './fixtures/remoteOAuthDiscovery.js'
+import { MockGateway } from './mockGateway.js'
+
+/**
+ * C1.5 "C-install" admin routes (spec 02, DEC-12). The saga is tested against a
+ * MOCKED K8sGateway — the `remote`×`oauth` CR shape is not admissible until C3 lands
+ * the CRD (batch model, §8), so live admission is out of scope here.
+ *
+ * Discovery is module-mocked, but the DiscoveryResult it returns is DERIVED FROM THE
+ * REAL PRODUCER (T1): the actual `discoverRemoteOAuth` is run once against the real
+ * 2026-09-20 probe fixtures to produce it — never hand-authored.
+ */
+
+// The kernel resolves the admin-typed baseUrl via node:dns; keep it public + offline.
+vi.mock('node:dns/promises', () => ({
+ lookup: vi.fn(async () => [{ address: '93.184.216.34', family: 4 }]),
+}))
+
+vi.mock('../src/oauth/discovery.js', async importActual => {
+ const actual = await importActual<typeof import('../src/oauth/discovery.js')>()
+ return { ...actual, discoverRemoteOAuth: vi.fn() }
+})
+
+const NS = config.mcpServersNamespace // 'mcp-server'
+
+function makeApp(gateway: MockGateway) {
+ const app = express()
+ app.use(express.json())
+ app.use(createAdminRemoteMcpRouter(gateway as unknown as K8sGateway))
+ app.use(
+ (err: unknown, _req: express.Request, res: express.Response, _next: express.NextFunction) => {
+ res.status(500).json({ error: err instanceof Error ? err.message : 'unknown' })
+ }
+ )
+ return app
+}
+
+/** Seed a Context in the gateway's default namespace (where the route reads it). */
+function gatewayWithContext(contextName = 'ctx-a'): MockGateway {
+ const gw = new MockGateway(NS)
+ void gw.createResource(
+ 'contexts',
+ { metadata: { name: contextName }, spec: { contextId: contextName } },
+ NS
+ )
+ return gw
+}
+
+// Real DiscoveryResult, derived from the real Notion probe fixtures (T1).
+let notionResult: DiscoveryResult
+
+beforeAll(async () => {
+ const actual = await vi.importActual<typeof import('../src/oauth/discovery.js')>(
+ '../src/oauth/discovery.js'
+ )
+ const outcome = await actual.discoverRemoteOAuth(PILOTS.notion.mcpUrl, {
+ transport: makeDiscoveryTransport(PILOTS.notion),
+ resolveDns: async () => ['93.184.216.34'],
+ })
+ if (!outcome.ok) throw new Error(`fixture discovery failed: ${outcome.error.kind}`)
+ notionResult = outcome.result
+})
+
+beforeEach(() => {
+ vi.mocked(discoverRemoteOAuth).mockReset()
+})
+
+function mockDiscovery(result: DiscoveryResult): void {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({ ok: true, result } as DiscoveryOutcome)
+}
+
+describe('POST /admin/mcp-servers/remote/discover (dry-run)', () => {
+ it('kernel-rejects a non-https baseUrl → 400, no discovery', async () => {
+ const gw = gatewayWithContext()
+ const res = await request(makeApp(gw))
+ .post('/admin/mcp-servers/remote/discover')
+ .send({ baseUrl: 'http://mcp.notion.com/mcp' })
+ expect(res.status).toBe(400)
+ expect(discoverRemoteOAuth).not.toHaveBeenCalled()
+ })
+
+ it('returns the "Detected" prefill for a CIMD server → 200', async () => {
+ mockDiscovery(notionResult)
+ const res = await request(makeApp(gatewayWithContext()))
+ .post('/admin/mcp-servers/remote/discover')
+ .send({ baseUrl: 'https://mcp.notion.com/mcp' })
+ expect(res.status).toBe(200)
+ expect(res.body.detected.registrationMode).toBe('cimd')
+ expect(res.body.detected.endpoints.token).toBe('https://mcp.notion.com/token')
+ expect(res.body.detected.resource).toBe('https://mcp.notion.com')
+ expect(res.body.detected.quirks).toEqual({ bearerInBody: false, supportsRefresh: true })
+ // No DCR marker for a CIMD server.
+ expect(res.body.detected.dcr).toBeUndefined()
+ })
+
+ it('marks DCR mode unavailable (not failed) → 200 with dcr.available=false', async () => {
+ mockDiscovery({ ...notionResult, registrationMode: 'dcr' })
+ const res = await request(makeApp(gatewayWithContext()))
+ .post('/admin/mcp-servers/remote/discover')
+ .send({ baseUrl: 'https://mcp.example.com/mcp' })
+ expect(res.status).toBe(200)
+ expect(res.body.detected.registrationMode).toBe('dcr')
+ expect(res.body.detected.dcr).toEqual({
+ available: false,
+ message: 'requires DCR (not available until C2)',
+ })
+ })
+
+ it('maps a discovery failure → 400', async () => {
+ vi.mocked(discoverRemoteOAuth).mockResolvedValue({
+ ok: false,
+ error: { kind: 'no_s256', detail: 'no S256' },
+ } as DiscoveryOutcome)
+ const res = await request(makeApp(gatewayWithContext()))
+ .post('/admin/mcp-servers/remote/discover')
+ .send({ baseUrl: 'https://mcp.example.com/mcp' })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('discovery_failed')
+ })
+})
+
+describe('POST /admin/mcp-servers/remote (install saga)', () => {
+ it('CIMD (public): creates the CR with the pinned spec.oauth shape + attaches to Context', async () => {
+ mockDiscovery(notionResult)
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'notion-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'cimd',
+ })
+ expect(res.status).toBe(201)
+ expect(res.body).toMatchObject({
+ serverName: 'notion-remote',
+ namespace: NS,
+ clientMode: 'public',
+ registrationMode: 'cimd',
+ })
+ // No secret material echoed.
+ expect(res.body.clientSecret).toBeUndefined()
+
+ const cr = (await gw.getResource('mcpservers', 'notion-remote', NS)) as {
+ spec: Record<string, unknown>
+ }
+ expect(cr.spec.auth).toEqual({ type: 'oauth' })
+ expect(cr.spec.remote).toEqual({ baseUrl: 'https://mcp.notion.com/mcp' })
+ expect(cr.spec.oauth).toEqual({
+ source: 'remote',
+ clientMode: 'public',
+ authorizationEndpoint: 'https://mcp.notion.com/authorize',
+ tokenEndpoint: 'https://mcp.notion.com/token',
+ registrationEndpoint: 'https://mcp.notion.com/register',
+ issuer: 'https://mcp.notion.com',
+ resource: 'https://mcp.notion.com',
+ grantScope: 'user',
+ scopes: ['default'],
+ bearerInBody: false,
+ supportsRefresh: true,
+ })
+
+ // Context now allowlists the server.
+ const ctx = (await gw.getResource('contexts', 'ctx-a', NS)) as {
+ spec: { mcpServers?: string[] }
+ }
+ expect(ctx.spec.mcpServers).toContain('notion-remote')
+ })
+
+ it('pre-registered confidential: creates the client Secret + references it in spec.oauth', async () => {
+ mockDiscovery(notionResult)
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'slack-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'pre-registered',
+ clientId: 'client-abc',
+ clientSecret: 'shhh-secret',
+ })
+ expect(res.status).toBe(201)
+ expect(res.body.clientMode).toBe('confidential')
+
+ const secret = (await gw.getSecret('slack-remote-oauth-client', NS)) as {
+ stringData?: Record<string, string>
+ }
+ expect(secret.stringData).toEqual({ client_id: 'client-abc', client_secret: 'shhh-secret' })
+
+ const cr = (await gw.getResource('mcpservers', 'slack-remote', NS)) as {
+ spec: { oauth: Record<string, unknown> }
+ }
+ expect(cr.spec.oauth.clientMode).toBe('confidential')
+ expect(cr.spec.oauth.clientIdRef).toEqual({
+ name: 'slack-remote-oauth-client',
+ key: 'client_id',
+ })
+ expect(cr.spec.oauth.clientSecretRef).toEqual({
+ name: 'slack-remote-oauth-client',
+ key: 'client_secret',
+ })
+ })
+
+ it('rejects DCR mode → 400 dcr_not_available', async () => {
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'stripe-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.example.com/mcp',
+ mode: 'dcr',
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('dcr_not_available')
+ // No CR written.
+ await expect(gw.getResource('mcpservers', 'stripe-remote', NS)).rejects.toThrow()
+ })
+
+ it('pre-registered without clientSecret → 400', async () => {
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'x-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'pre-registered',
+ clientId: 'only-id',
+ })
+ expect(res.status).toBe(400)
+ })
+
+ it('CIMD requested but AS is DCR-only → 400 (server-side discovery is authoritative)', async () => {
+ mockDiscovery({ ...notionResult, registrationMode: 'dcr' })
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'y-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.example.com/mcp',
+ mode: 'cimd',
+ })
+ expect(res.status).toBe(400)
+ expect(res.body.error).toBe('dcr_not_available')
+ })
+
+ it('rolls back the Secret when the CR create fails', async () => {
+ mockDiscovery(notionResult)
+ const gw = gatewayWithContext('ctx-a')
+ const k8sErr = Object.assign(new Error('already exists'), { code: 409 })
+ vi.spyOn(gw, 'createResource').mockRejectedValueOnce(k8sErr)
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'roll-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'pre-registered',
+ clientId: 'cid',
+ clientSecret: 'csecret',
+ })
+ expect(res.status).toBe(409)
+ // The client Secret created before the CR must be rolled back.
+ await expect(gw.getSecret('roll-remote-oauth-client', NS)).rejects.toThrow()
+ })
+
+ it('rolls back the CR AND Secret when the Context attach fails', async () => {
+ mockDiscovery(notionResult)
+ // Context does NOT exist → getResource('contexts', …) throws K8sNotFoundError.
+ const gw = new MockGateway(NS)
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'attach-remote',
+ contextRef: 'missing-ctx',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'pre-registered',
+ clientId: 'cid',
+ clientSecret: 'csecret',
+ })
+ expect(res.status).toBeGreaterThanOrEqual(400)
+ // Both the CR and the Secret are rolled back.
+ await expect(gw.getResource('mcpservers', 'attach-remote', NS)).rejects.toThrow()
+ await expect(gw.getSecret('attach-remote-oauth-client', NS)).rejects.toThrow()
+ })
+
+ it('forces the namespace server-side (caller-supplied namespace is ignored)', async () => {
+ mockDiscovery(notionResult)
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(makeApp(gw)).post('/admin/mcp-servers/remote').send({
+ serverName: 'ns-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'cimd',
+ namespace: 'attacker-ns',
+ })
+ expect(res.status).toBe(201)
+ expect(res.body.namespace).toBe(NS)
+ // Created in the config namespace, nothing in the attacker-supplied one.
+ await expect(gw.getResource('mcpservers', 'ns-remote', NS)).resolves.toBeTruthy()
+ await expect(gw.getResource('mcpservers', 'ns-remote', 'attacker-ns')).rejects.toThrow()
+ })
+
+ it('rejects a metadata.namespace that disagrees with the server namespace → 400', async () => {
+ mockDiscovery(notionResult)
+ const gw = gatewayWithContext('ctx-a')
+ const res = await request(makeApp(gw))
+ .post('/admin/mcp-servers/remote')
+ .send({
+ serverName: 'md-remote',
+ contextRef: 'ctx-a',
+ baseUrl: 'https://mcp.notion.com/mcp',
+ mode: 'cimd',
+ metadata: { namespace: 'evil' },
+ })
+ expect(res.status).toBe(400)
+ })
+})