Skip to content

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

TypeScript

fix(oauth): pin remote MCP connection against DNS rebinding (R1-H1)

Diego Zacarias66bd90473622
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 4862d18f2..1f9ab2509 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.356",
+ "version": "0.1.359",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.356",
+ "version": "0.1.359",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@anthropic-ai/sdk": "^0.32.0",
diff --git a/mcp-host/package.json b/mcp-host/package.json
index d78711ce7..dfc631db5 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.357",
+ "version": "0.1.359",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/core/net/__tests__/ssrf.test.ts b/mcp-host/src/core/net/__tests__/ssrf.test.ts
index d29d21a22..f6d3507ee 100644
--- a/mcp-host/src/core/net/__tests__/ssrf.test.ts
+++ b/mcp-host/src/core/net/__tests__/ssrf.test.ts
@@ -7,7 +7,7 @@
import { afterEach, describe, expect, it, vi } from 'vitest'
import * as dns from 'dns/promises'
import http from 'node:http'
-import { SsrfBlockedError, requestPinned, resolvePinnedPublicIp } from '../ssrf'
+import { SsrfBlockedError, pinnedFetch, requestPinned, resolvePinnedPublicIp } from '../ssrf'
vi.mock('dns/promises', () => ({
resolve4: vi.fn(),
@@ -132,3 +132,77 @@ describe('requestPinned — bounded in time and bytes', () => {
expect(Date.now() - started).toBeLessThan(2000) // settled promptly, not at 10s
})
})
+
+describe('pinnedFetch — connects to the pinned IP, never re-resolves the hostname', () => {
+ const servers: http.Server[] = []
+
+ async function startServer(handler: http.RequestListener): Promise<number> {
+ const s = http.createServer(handler)
+ servers.push(s)
+ await new Promise<void>(resolve => s.listen(0, '127.0.0.1', resolve))
+ return (s.address() as { port: number }).port
+ }
+
+ afterEach(async () => {
+ await Promise.all(servers.splice(0).map(s => new Promise<void>(r => s.close(() => r()))))
+ })
+
+ it('reaches the server at the pinned IP even when the URL hostname does not resolve', async () => {
+ // The observable (T4): the request ARRIVES at the local server bound to the
+ // pinned IP. The URL hostname `rebind.invalid` would fail DNS if re-resolved
+ // — so a request reaching the server proves the socket used the pinned IP, not
+ // a resolution of the hostname. The Host header still carries the hostname.
+ let seenHost: string | undefined
+ let seenBody = ''
+ let seenContentLength: string | undefined
+ let seenTransferEncoding: string | undefined
+ const port = await startServer((req, res) => {
+ seenHost = req.headers.host
+ seenContentLength = req.headers['content-length']
+ seenTransferEncoding = req.headers['transfer-encoding']
+ req.on('data', chunk => (seenBody += chunk))
+ req.on('end', () => {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end('{"ok":true}')
+ })
+ })
+
+ const requestBody = '{"jsonrpc":"2.0","method":"initialize"}'
+ const res = await pinnedFetch('127.0.0.1')(new URL(`http://rebind.invalid:${port}/mcp`), {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: requestBody,
+ })
+
+ expect(res.status).toBe(200)
+ await expect(res.json()).resolves.toEqual({ ok: true })
+ // Host preserved as the hostname (virtual-host routing / cert identity target).
+ expect(seenHost).toBe(`rebind.invalid:${port}`)
+ expect(seenBody).toBe(requestBody)
+ // The POST body carries a correct Content-Length, never chunked (strict WAFs
+ // reject Transfer-Encoding: chunked request bodies).
+ expect(seenContentLength).toBe(String(Buffer.byteLength(requestBody)))
+ expect(seenTransferEncoding).toBeUndefined()
+ })
+
+ it('streams the response body rather than buffering it (SSE-capable)', async () => {
+ const port = await startServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'text/event-stream' })
+ res.write('event: message\n')
+ res.end('data: hi\n\n')
+ })
+ const res = await pinnedFetch('127.0.0.1')(new URL(`http://stream.invalid:${port}/mcp`))
+ expect(res.body).toBeInstanceOf(ReadableStream)
+ await expect(res.text()).resolves.toBe('event: message\ndata: hi\n\n')
+ })
+
+ it('fails closed on a non-string request body (unsupported)', async () => {
+ const port = await startServer((_req, res) => res.end('unused'))
+ await expect(
+ pinnedFetch('127.0.0.1')(new URL(`http://x.invalid:${port}/`), {
+ method: 'POST',
+ body: new Uint8Array([1, 2, 3]),
+ })
+ ).rejects.toBeInstanceOf(SsrfBlockedError)
+ })
+})
diff --git a/mcp-host/src/core/net/ssrf.ts b/mcp-host/src/core/net/ssrf.ts
index f2312cdec..a9eff6a0c 100644
--- a/mcp-host/src/core/net/ssrf.ts
+++ b/mcp-host/src/core/net/ssrf.ts
@@ -19,6 +19,7 @@ import * as dns from 'dns/promises'
import * as http from 'http'
import * as https from 'https'
import * as net from 'net'
+import { Readable } from 'stream'
/** Thrown when a target host is (or resolves to) a non-public address, or can't be verified. */
export class SsrfBlockedError extends Error {
@@ -331,3 +332,122 @@ export function requestPinned(opts: {
req.end()
})
}
+
+/** Extract a plain header record from any `HeadersInit` shape. */
+function headerRecord(headers: HeadersInit | undefined): Record<string, string> {
+ const out: Record<string, string> = {}
+ if (!headers) return out
+ if (headers instanceof Headers) {
+ headers.forEach((value, key) => {
+ out[key] = value
+ })
+ } else if (Array.isArray(headers)) {
+ for (const [key, value] of headers) out[key] = value
+ } else {
+ for (const [key, value] of Object.entries(headers)) out[key] = String(value)
+ }
+ return out
+}
+
+/**
+ * Build a `fetch`-compatible function that connects to a caller-VALIDATED,
+ * DNS-pinned IP while keeping the original hostname in the Host header and TLS
+ * SNI/cert check — the streaming sibling of `requestPinned`, shaped for SDK
+ * transports that take a custom `fetch` (e.g. the MCP StreamableHTTP/SSE client).
+ *
+ * Why this and not `resolvePinnedPublicIp` alone: validating the host resolves to
+ * a public IP and then handing the raw hostname to a fetch that RE-RESOLVES it is
+ * a DNS-rebinding TOCTOU — a TTL≈0 record can answer public at validation and
+ * private/metadata at connect. This connects to the exact validated IP, so the
+ * socket can never be rebound. It deliberately does NOT follow redirects (Node's
+ * core client returns the 3xx as-is), so a redirect to an internal host is inert.
+ *
+ * `pinnedIp` MUST already be the public IP returned by `resolvePinnedPublicIp` —
+ * this primitive trusts it and does NOT re-validate (same contract as
+ * `requestPinned`; the caller owns the public-IP check). Only string/absent
+ * request bodies are supported (what the MCP SDK sends); any other body fails
+ * closed.
+ */
+export function pinnedFetch(
+ pinnedIp: string
+): (input: string | URL, init?: RequestInit) => Promise<Response> {
+ return (input, init) => {
+ const url = new URL(typeof input === 'string' ? input : input.toString())
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') {
+ return Promise.reject(new SsrfBlockedError(`unsupported protocol ${url.protocol}`))
+ }
+ const body = init?.body
+ if (body != null && typeof body !== 'string') {
+ // The MCP transports only ever send string bodies; anything else would need
+ // stream piping we do not support — fail closed rather than send a wrong body.
+ return Promise.reject(new SsrfBlockedError('pinnedFetch only supports string request bodies'))
+ }
+
+ const isHttps = url.protocol === 'https:'
+ const client = isHttps ? https : http
+ const defaultPort = isHttps ? 443 : 80
+ const headers = headerRecord(init?.headers)
+ // Preserve the hostname for the peer's virtual-host routing; suppress
+ // compression since Node's core client does not auto-decode (the SDK reads
+ // the body as SSE text / JSON).
+ headers['host'] = url.host
+ headers['accept-encoding'] = 'identity'
+ // The body is a complete string (never streamed), so send it with an explicit
+ // Content-Length rather than the chunked Transfer-Encoding Node's client would
+ // otherwise use — strict WAFs/gateways reject chunked request bodies.
+ if (typeof body === 'string') {
+ headers['content-length'] = String(Buffer.byteLength(body))
+ }
+
+ return new Promise<Response>((resolve, reject) => {
+ const req = client.request(
+ {
+ method: (init?.method ?? 'GET').toUpperCase(),
+ hostname: pinnedIp,
+ port: url.port ? Number(url.port) : defaultPort,
+ path: `${url.pathname}${url.search}`,
+ headers,
+ // SNI + certificate identity are checked against the real hostname even
+ // though the socket connects to the pinned IP literal.
+ servername: url.hostname,
+ },
+ res => {
+ const encoding = res.headers['content-encoding']
+ if (encoding && encoding !== 'identity') {
+ res.destroy()
+ reject(new SsrfBlockedError(`unexpected content-encoding "${encoding}"`))
+ return
+ }
+ const responseHeaders = new Headers()
+ for (const [key, value] of Object.entries(res.headers)) {
+ if (value === undefined) continue
+ if (Array.isArray(value)) value.forEach(item => responseHeaders.append(key, item))
+ else responseHeaders.set(key, value)
+ }
+ const status = res.statusCode ?? 502
+ // Per the fetch spec these statuses carry a null body.
+ const nullBody = status === 204 || status === 205 || status === 304
+ if (nullBody) res.resume()
+ resolve(
+ new Response(nullBody ? null : (Readable.toWeb(res) as ReadableStream<Uint8Array>), {
+ status,
+ statusText: res.statusMessage,
+ headers: responseHeaders,
+ })
+ )
+ }
+ )
+ req.on('error', reject)
+ const signal = init?.signal
+ if (signal) {
+ const onAbort = (): void => {
+ req.destroy(new Error('request aborted'))
+ }
+ if (signal.aborted) onAbort()
+ else signal.addEventListener('abort', onAbort, { once: true })
+ }
+ if (typeof body === 'string') req.write(body)
+ req.end()
+ })
+ }
+}
diff --git a/mcp-host/src/mcp/__tests__/clientRemoteTargetPin.test.ts b/mcp-host/src/mcp/__tests__/clientRemoteTargetPin.test.ts
new file mode 100644
index 000000000..222ad58b5
--- /dev/null
+++ b/mcp-host/src/mcp/__tests__/clientRemoteTargetPin.test.ts
@@ -0,0 +1,130 @@
+/**
+ * R1-H1 (T3) — DNS-rebinding TOCTOU on the remote MCP target.
+ *
+ * The guard validates the target resolves to a public IP, but the connection
+ * must also be PINNED to that exact IP, or the SDK's fetch re-resolves the
+ * hostname at connect time and a TTL≈0 record can rebind it to a
+ * private/metadata address (delivering the per-user Bearer + an SSRF read
+ * primitive to an internal host).
+ *
+ * This asserts the observable wiring (T4): the IP returned by
+ * `resolvePinnedPublicIp` is USED to build a pinned `fetch` that is handed to the
+ * SDK transport (`opts.fetch`). Against the anchor `7bfc2e9a9` — which validates
+ * the IP but DISCARDS it and injects no fetch — `opts.fetch` is undefined, so the
+ * assertions fail. `core/net/ssrf` is mocked so `pinnedFetch` is observable and
+ * no DNS is touched; the pin primitive itself is proven against a real server in
+ * core/net/__tests__/ssrf.test.ts.
+ */
+import { beforeEach, describe, expect, it, vi } from 'vitest'
+import { pinnedFetch, resolvePinnedPublicIp } from '../../core/net/ssrf'
+import type { McpServerInfo } from '../../types'
+import { McpClient, staticTokenProvider } from '../client'
+
+const captured: { streamableOpts?: { fetch?: unknown }; sseOpts?: { fetch?: unknown } } = {}
+
+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, opts?: { fetch?: unknown }) {
+ captured.streamableOpts = opts
+ }
+ },
+}))
+
+vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
+ SSEClientTransport: class MockSSE {
+ close = vi.fn().mockResolvedValue(undefined)
+ constructor(_url: URL, opts?: { fetch?: unknown }) {
+ captured.sseOpts = opts
+ }
+ },
+}))
+
+// Mock the SSRF mold so `pinnedFetch` is observable and no DNS/socket is touched.
+// resolvePinnedPublicIp returns a FIXED public IP (the "validation" result);
+// pinnedFetch tags the fetch it builds with the IP it was pinned to.
+vi.mock('../../core/net/ssrf', () => ({
+ SsrfBlockedError: class SsrfBlockedError extends Error {},
+ resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),
+ pinnedFetch: vi.fn((ip: string) =>
+ Object.assign(
+ vi.fn(async () => new Response('{}')),
+ { __pinnedIp: ip }
+ )
+ ),
+}))
+
+function remoteServer(url = 'https://rebind.example.com/mcp'): 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(() => {
+ captured.streamableOpts = undefined
+ captured.sseOpts = undefined
+ vi.mocked(resolvePinnedPublicIp).mockClear()
+ vi.mocked(pinnedFetch).mockClear()
+})
+
+describe('remote target connection is pinned to the validated IP (R1-H1, T3)', () => {
+ it('injects a fetch pinned to the resolvePinnedPublicIp IP into the SDK transport', async () => {
+ const client = new McpClient(remoteServer(), staticTokenProvider('t'))
+ await client.connect()
+
+ // The validated IP is actually USED to build the connection's fetch (against
+ // the anchor it is resolved then discarded, so pinnedFetch is never called).
+ expect(pinnedFetch).toHaveBeenCalledWith('203.0.113.10')
+ // ...and that pinned fetch is handed to the SDK transport, so the SDK cannot
+ // re-resolve the hostname at connect time. Anchor: opts.fetch is undefined.
+ const injected = captured.streamableOpts?.fetch as { __pinnedIp?: string } | undefined
+ expect(injected).toBeDefined()
+ expect(injected!.__pinnedIp).toBe('203.0.113.10')
+ })
+
+ it('does NOT pin a local (in-cluster) server — no fetch override, no resolve', async () => {
+ const client = new McpClient(localServer(), staticTokenProvider('t'))
+ await client.connect()
+ expect(resolvePinnedPublicIp).not.toHaveBeenCalled()
+ expect(pinnedFetch).not.toHaveBeenCalled()
+ expect(captured.streamableOpts?.fetch).toBeUndefined()
+ })
+
+ it('does NOT pin the MCP_PROXY_URL rail for a local server (internal egress)', async () => {
+ const client = new McpClient(
+ localServer(),
+ staticTokenProvider('t'),
+ 'http://mcp-proxy.svc:8080'
+ )
+ await client.connect()
+ expect(pinnedFetch).not.toHaveBeenCalled()
+ expect(captured.streamableOpts?.fetch).toBeUndefined()
+ })
+})
diff --git a/mcp-host/src/mcp/__tests__/managerRemoteOauthCatalog.test.ts b/mcp-host/src/mcp/__tests__/managerRemoteOauthCatalog.test.ts
index 30dfad79f..537ec5403 100644
--- a/mcp-host/src/mcp/__tests__/managerRemoteOauthCatalog.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerRemoteOauthCatalog.test.ts
@@ -94,6 +94,9 @@ vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
vi.mock('../../core/net/ssrf', () => ({
SsrfBlockedError: class SsrfBlockedError extends Error {},
resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),
+ // client.ts pins remote connections with a fetch from pinnedFetch(ip); the SDK
+ // Client is mocked here so the returned fetch is never invoked.
+ pinnedFetch: vi.fn(() => vi.fn(async () => new Response('{}'))),
}))
// ─── Fixtures ────────────────────────────────────────────────────────────────
diff --git a/mcp-host/src/mcp/client.ts b/mcp-host/src/mcp/client.ts
index d9e06f5cc..5c19a97df 100644
--- a/mcp-host/src/mcp/client.ts
+++ b/mcp-host/src/mcp/client.ts
@@ -6,7 +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 { SsrfBlockedError, pinnedFetch, resolvePinnedPublicIp } from '../core/net/ssrf'
import { McpServerInfo, McpTool } from '../types'
import {
type McpToolCallOptions,
@@ -204,24 +204,29 @@ export class McpClient {
}
/**
- * 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.
+ * SSRF-guard a REMOTE server's target before any transport I/O and return the
+ * single public IP to PIN the connection to. 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 returned IP is fed to `pinnedFetch` in
+ * `createTransport` so the SDK cannot re-resolve the hostname at connect time
+ * (DNS-rebinding TOCTOU). 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> {
+ private async validateRemoteTarget(options: McpToolCallOptions): Promise<string> {
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)
+ // Throws SsrfBlockedError on a private/reserved/metadata or unresolvable host;
+ // returns the exact IP the connection is then pinned to.
+ const pinnedIp = await resolvePinnedPublicIp(url)
ensureNotAborted(options.signal)
+ return pinnedIp
}
- private createTransport(): SupportedMcpTransport {
+ private createTransport(pinnedRemoteIp?: string): SupportedMcpTransport {
const { transport } = this.serverConfig
const headers: Record<string, string> = {}
@@ -246,12 +251,32 @@ export class McpClient {
const targetUrl = this.resolveUrl()
+ // Pin the SOCKET of a remote connection to the IP validated in
+ // validateRemoteTarget so the SDK's fetch cannot re-resolve the hostname to a
+ // private/metadata address at connect time (DNS-rebinding TOCTOU). Host header
+ // + TLS SNI still track the hostname. Only remote targets are pinned; the
+ // MCP_PROXY_URL rail and the in-cluster DNS fallback are internal and keep the
+ // default fetch. Fail closed if a remote transport is somehow built without a
+ // pinned IP — never connect a remote target unpinned.
+ let pinnedFetchImpl:
+ | ((input: string | URL, init?: RequestInit) => Promise<Response>)
+ | undefined
+ if (this.isRemoteServer()) {
+ if (!pinnedRemoteIp) {
+ throw new SsrfBlockedError(
+ `remote MCP server ${this.name} reached transport build without a pinned IP`
+ )
+ }
+ pinnedFetchImpl = pinnedFetch(pinnedRemoteIp)
+ }
+
if (this.usesProxyRail() || transport.type === 'streamableHttp') {
console.log(`[MCP:${this.name}] Using Streamable HTTP transport`)
return new StreamableHTTPClientTransport(new URL(targetUrl), {
requestInit: {
headers,
},
+ ...(pinnedFetchImpl ? { fetch: pinnedFetchImpl } : {}),
})
}
@@ -261,6 +286,7 @@ export class McpClient {
requestInit: {
headers,
},
+ ...(pinnedFetchImpl ? { fetch: pinnedFetchImpl } : {}),
})
}
@@ -288,13 +314,15 @@ export class McpClient {
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.
+ // private/metadata/unresolvable host or a non-https URL) and capture the IP to
+ // pin the connection to. Local servers (proxy rail or in-cluster DNS) are
+ // internal and skip this.
+ let pinnedRemoteIp: string | undefined
if (this.isRemoteServer()) {
- await this.validateRemoteTarget(options)
+ pinnedRemoteIp = await this.validateRemoteTarget(options)
}
const connectionEpoch = ++this.connectionEpoch
- const nextTransport = this.createTransport()
+ const nextTransport = this.createTransport(pinnedRemoteIp)
const nextClient = new Client(
{
name: 'clerum-mcp-host',