Skip to content

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

TypeScript

fix(mcp-host): remove dead pinnedFetch/headerRecord SSRF export (R1-M2)

Diego Zacarias4e0694d2cd3b
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 5223dec4b..dc5c90bb7 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.465",
+ "version": "0.1.466",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.465",
+ "version": "0.1.466",
"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 3ba364fb1..120460319 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.465",
+ "version": "0.1.466",
"description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude",
"main": "dist/main.js",
"engines": {
diff --git a/mcp-host/src/agent/__tests__/taskExecutorCatalogBootstrap.integration.test.ts b/mcp-host/src/agent/__tests__/taskExecutorCatalogBootstrap.integration.test.ts
index 8a711c7b4..339017b65 100644
--- a/mcp-host/src/agent/__tests__/taskExecutorCatalogBootstrap.integration.test.ts
+++ b/mcp-host/src/agent/__tests__/taskExecutorCatalogBootstrap.integration.test.ts
@@ -54,7 +54,6 @@ vi.mock('@modelcontextprotocol/sdk/client/sse.js', async () => {
vi.mock('../../core/net/ssrf', () => ({
SsrfBlockedError: class SsrfBlockedError extends Error {},
resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),
- pinnedFetch: vi.fn(() => vi.fn(async () => new Response('{}'))),
}))
function remoteOauthUserServer(name = 'calendar'): McpServerInfo {
diff --git a/mcp-host/src/core/net/__tests__/ssrf.test.ts b/mcp-host/src/core/net/__tests__/ssrf.test.ts
index f6d3507ee..d29d21a22 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, pinnedFetch, requestPinned, resolvePinnedPublicIp } from '../ssrf'
+import { SsrfBlockedError, requestPinned, resolvePinnedPublicIp } from '../ssrf'
vi.mock('dns/promises', () => ({
resolve4: vi.fn(),
@@ -132,77 +132,3 @@ 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 a9eff6a0c..f2312cdec 100644
--- a/mcp-host/src/core/net/ssrf.ts
+++ b/mcp-host/src/core/net/ssrf.ts
@@ -19,7 +19,6 @@ 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 {
@@ -332,122 +331,3 @@ 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__/managerCatalogBootstrap.test.ts b/mcp-host/src/mcp/__tests__/managerCatalogBootstrap.test.ts
index 3c225a19e..4da6dd89e 100644
--- a/mcp-host/src/mcp/__tests__/managerCatalogBootstrap.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerCatalogBootstrap.test.ts
@@ -45,12 +45,11 @@ vi.mock('@modelcontextprotocol/sdk/client/sse.js', async () => {
return remoteUpstream({ strict: true }, sdk).sseModule
})
-// The real SSRF guard is exercised in clientRemoteTarget.test.ts; here it must
-// never touch DNS (the SDK is mocked, so its returned fetch is never invoked).
+// The real SSRF guard is exercised in clientRemoteTarget.test.ts; here its DNS
+// resolver is stubbed so these tests never touch DNS.
vi.mock('../../core/net/ssrf', () => ({
SsrfBlockedError: class SsrfBlockedError extends Error {},
resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),
- pinnedFetch: vi.fn(() => vi.fn(async () => new Response('{}'))),
}))
function remoteOauthUserServer(name = 'gh'): McpServerInfo {
diff --git a/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts b/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts
index 7f3aabe2e..ff3bade1f 100644
--- a/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerConnectRequired.test.ts
@@ -83,12 +83,13 @@ vi.mock('@modelcontextprotocol/sdk/client/sse.js', () => ({
},
}))
-// Remote (https) admissions pin a public IP via the SSRF guard; neutralize it so
-// these tests never touch DNS (its real behavior lives in clientRemoteTarget.test.ts).
+// Stub the SSRF guard's DNS resolver so these tests never touch DNS; the real
+// guard is exercised in clientRemoteTarget.test.ts. Remote MCP egress goes through
+// the internal HCC http hop, which is NOT pinned (see client.ts) — the guard here
+// only keeps import-time resolution offline.
vi.mock('../../core/net/ssrf', () => ({
SsrfBlockedError: class SsrfBlockedError extends Error {},
resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),
- pinnedFetch: vi.fn(() => vi.fn(async () => new Response('{}'))),
}))
function httpError(status: number): () => Promise<never> {
diff --git a/mcp-host/src/mcp/__tests__/managerSharedGrantGate.test.ts b/mcp-host/src/mcp/__tests__/managerSharedGrantGate.test.ts
index 989d4a4ed..369ffd3b1 100644
--- a/mcp-host/src/mcp/__tests__/managerSharedGrantGate.test.ts
+++ b/mcp-host/src/mcp/__tests__/managerSharedGrantGate.test.ts
@@ -49,7 +49,6 @@ vi.mock('@modelcontextprotocol/sdk/client/sse.js', async () => {
vi.mock('../../core/net/ssrf', () => ({
SsrfBlockedError: class SsrfBlockedError extends Error {},
resolvePinnedPublicIp: vi.fn(async () => '203.0.113.10'),
- pinnedFetch: vi.fn(() => vi.fn(async () => new Response('{}'))),
}))
function remoteOauthContextServer(name = 'remote-ctx'): McpServerInfo {