Skip to content

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

TypeScript

fix(guardrails): bound hook transport in time and bytes (§8.1/§8.6)

Andy Paviae764b5600a23
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 0196acbe4..fa326f009 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.256",
+ "version": "0.1.257",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.256",
+ "version": "0.1.257",
"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 58aeb4c96..114a97755 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.256",
+ "version": "0.1.257",
"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/guardrails/hooks/__tests__/remoteLlmHook.test.ts b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
index 6a31d8e82..1cf40e8f0 100644
--- a/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
+++ b/mcp-host/src/core/guardrails/hooks/__tests__/remoteLlmHook.test.ts
@@ -309,6 +309,34 @@ describe('quarantine (§8.2 digest mismatch → fail-closed, N11)', () => {
})
})
+describe('hard deadline (§8.6 belt-and-braces)', () => {
+ const neverSettles: HookFetcher = () => new Promise<HookHttpResult>(() => {})
+
+ it('a transport that never settles → unavailable → fail-mode (deny for may_deny)', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_deny'], failMode: 'closed', lifecyclePoints: ['moderate'] }),
+ neverSettles,
+ new HookBreakerRegistry(),
+ () => 0,
+ 5 // hardDeadlineMs = 5ms so the deadline wins deterministically
+ )
+ const c = await h.moderate(req())
+ expect(c?.decision).toBe('deny')
+ expect(c?.reasonCode).toBe('hook_unavailable')
+ })
+
+ it('a never-settling advisory hook → no contribution (skip), not a hang', async () => {
+ const h = new RemoteLlmHook(
+ desc({ capabilities: ['may_add_context'], failMode: 'open', lifecyclePoints: ['pre_call'] }),
+ neverSettles,
+ new HookBreakerRegistry(),
+ () => 0,
+ 5
+ )
+ expect(await h.preCall(req())).toBeNull()
+ })
+})
+
describe('circuit breaker (§8.6)', () => {
// Advisory hook (may_add_context, not may_deny) that opts into breaker mode.
const advisory = (over: Partial<HookDescriptor> = {}): HookDescriptor =>
diff --git a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
index 3f86b9e7d..0f1bc0801 100644
--- a/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
+++ b/mcp-host/src/core/guardrails/hooks/hookFetcher.ts
@@ -57,7 +57,7 @@ export function buildHookUrl(endpoint: string, path: string, point: LifecyclePoi
* the `FetchLike` shape so the outcome classification is shared with the
* in-cluster path. Throws `SsrfBlockedError` on a blocked/unverifiable host.
*/
-function makeSsrfGuardedFetch(timeoutMs: number): FetchLike {
+function makeSsrfGuardedFetch(timeoutMs: number, maxBytes: number): FetchLike {
return async (urlStr, init) => {
const url = new URL(urlStr)
if (url.protocol !== 'https:') {
@@ -71,16 +71,58 @@ function makeSsrfGuardedFetch(timeoutMs: number): FetchLike {
body: init.body,
pinnedIp,
timeoutMs,
+ // Absolute deadline (idle-independent) + streaming byte cap: a trickling or
+ // flooding remote hook can no longer hang or OOM the pod (settles → §8.6).
+ signal: init.signal,
+ maxBytes,
})
return { status: statusCode, text: async () => body }
}
}
+/**
+ * In-cluster transport (default): the global `fetch` honors the abort `signal`
+ * (absolute deadline) and the body is read WITH a streaming byte cap, so an
+ * oversized in-cluster response is never fully buffered either.
+ */
+function makeInClusterFetch(maxBytes: number): FetchLike {
+ return async (urlStr, init) => {
+ const res = await (globalThis.fetch as unknown as (u: string, i: unknown) => Promise<Response>)(
+ urlStr,
+ init
+ )
+ return {
+ status: res.status,
+ text: async () => {
+ const stream = res.body as ReadableStream<Uint8Array> | null
+ if (!stream) return res.text()
+ const reader = stream.getReader()
+ const chunks: Buffer[] = []
+ let total = 0
+ for (;;) {
+ const { done, value } = await reader.read()
+ if (done) break
+ if (value) {
+ total += value.length
+ if (total > maxBytes) {
+ await reader.cancel()
+ throw new Error('response exceeded maxBytes') // → caught → unavailable
+ }
+ chunks.push(Buffer.from(value))
+ }
+ }
+ return Buffer.concat(chunks).toString('utf-8')
+ },
+ }
+ }
+}
+
export function createHookFetcher(deps: HookFetcherDeps): HookFetcher {
const timeoutMs = deps.timeoutMs ?? 5000
const maxOutputBytes = deps.maxOutputBytes ?? 65536
- const inClusterFetch: FetchLike = deps.fetchImpl ?? (globalThis.fetch as unknown as FetchLike)
- const externalFetch: FetchLike = deps.externalFetchImpl ?? makeSsrfGuardedFetch(timeoutMs)
+ const inClusterFetch: FetchLike = deps.fetchImpl ?? makeInClusterFetch(maxOutputBytes)
+ const externalFetch: FetchLike =
+ deps.externalFetchImpl ?? makeSsrfGuardedFetch(timeoutMs, maxOutputBytes)
return async ({ point, descriptor, body }) => {
const url = buildHookUrl(descriptor.endpoint, descriptor.path, point)
diff --git a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
index b6e1e0da9..0b43c0987 100644
--- a/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
+++ b/mcp-host/src/core/guardrails/hooks/remoteLlmHook.ts
@@ -75,7 +75,16 @@ export class RemoteLlmHook {
/** Shared so a trip survives the per-task rebuild of this instance (§8.6). */
private readonly breakers: HookBreakerRegistry = defaultBreakerRegistry,
/** Injectable clock for deterministic breaker tests. */
- private readonly now: () => number = () => Date.now()
+ private readonly now: () => number = () => Date.now(),
+ /**
+ * Belt-and-braces hard deadline (§8.6): an ABSOLUTE ceiling on every hook
+ * dial, independent of the transport's own timeout. If the transport ever
+ * fails to settle (a signal that wasn't honored, a socket idle-timer reset by
+ * a trickling peer), the dial still resolves to `unavailable` after this,
+ * so the §8.6 fail-posture always applies and the await can never hang. Set
+ * well above the transport timeout so normal timeouts settle there first.
+ */
+ private readonly hardDeadlineMs: number = 15000
) {}
private has(cap: Capability): boolean {
@@ -119,7 +128,7 @@ export class RemoteLlmHook {
// Breaker open: skip the dial (and its timeout); report unavailable.
return { status: 0, body: undefined, unavailable: true }
}
- const res = await this.fetch(args)
+ const res = await this.fetchWithDeadline(args)
if (engaged) {
const policy = this.descriptor.onUnavailable!
if (res.unavailable) {
@@ -142,6 +151,31 @@ export class RemoteLlmHook {
return res
}
+ /**
+ * Race the transport against an absolute deadline so a dial that never settles
+ * (buggy/unhonored transport timeout) still yields `unavailable` rather than
+ * hanging the awaiting turn. Promise.race attaches a handler to the loser, so a
+ * late transport rejection is not an unhandled rejection.
+ */
+ private fetchWithDeadline(args: {
+ point: LifecyclePoint
+ descriptor: HookDescriptor
+ body: unknown
+ }): Promise<HookHttpResult> {
+ let timer: ReturnType<typeof setTimeout> | undefined
+ const deadline = new Promise<HookHttpResult>(resolve => {
+ timer = setTimeout(
+ () => resolve({ status: 0, body: undefined, unavailable: true }),
+ this.hardDeadlineMs
+ )
+ // Don't let the backstop timer keep the event loop alive.
+ ;(timer as { unref?: () => void }).unref?.()
+ })
+ return Promise.race([this.fetch(args), deadline]).finally(() => {
+ if (timer) clearTimeout(timer)
+ })
+ }
+
private handles(point: LifecyclePoint): boolean {
return this.descriptor.lifecyclePoints.includes(point)
}
diff --git a/mcp-host/src/core/net/__tests__/ssrf.test.ts b/mcp-host/src/core/net/__tests__/ssrf.test.ts
index 032913618..b1fd0354d 100644
--- a/mcp-host/src/core/net/__tests__/ssrf.test.ts
+++ b/mcp-host/src/core/net/__tests__/ssrf.test.ts
@@ -6,7 +6,8 @@
*/
import { afterEach, describe, expect, it, vi } from 'vitest'
import * as dns from 'dns/promises'
-import { SsrfBlockedError, resolvePinnedPublicIp } from '../ssrf'
+import http from 'node:http'
+import { SsrfBlockedError, requestPinned, resolvePinnedPublicIp } from '../ssrf'
vi.mock('dns/promises', () => ({
resolve4: vi.fn(),
@@ -60,3 +61,75 @@ describe('resolvePinnedPublicIp', () => {
)
})
})
+
+describe('requestPinned — bounded in time and bytes', () => {
+ let server: http.Server
+ let port: number
+ 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('resolves a normal response (happy path preserved)', async () => {
+ port = await startServer((_req, res) => {
+ res.writeHead(200, { 'content-type': 'application/json' })
+ res.end('{"ok":true}')
+ })
+ const out = await requestPinned({
+ url: new URL(`http://localhost:${port}/`),
+ method: 'GET',
+ headers: {},
+ pinnedIp: '127.0.0.1',
+ timeoutMs: 5000,
+ })
+ expect(out.statusCode).toBe(200)
+ expect(out.body).toBe('{"ok":true}')
+ })
+
+ it('rejects (does not buffer) once the body exceeds maxBytes', async () => {
+ port = await startServer((_req, res) => {
+ res.writeHead(200)
+ res.end('x'.repeat(200_000)) // 200 KB, well over the cap below
+ })
+ await expect(
+ requestPinned({
+ url: new URL(`http://localhost:${port}/`),
+ method: 'GET',
+ headers: {},
+ pinnedIp: '127.0.0.1',
+ timeoutMs: 5000,
+ maxBytes: 1024,
+ })
+ ).rejects.toThrow(/maxBytes/)
+ })
+
+ it('honors the abort signal even while the socket is active (absolute deadline)', async () => {
+ // Server sends headers + a byte every 20ms and NEVER ends — a Node socket
+ // idle timeout would keep resetting, but the abort must still settle it.
+ port = await startServer((_req, res) => {
+ res.writeHead(200)
+ const t = setInterval(() => res.write('.'), 20)
+ res.on('close', () => clearInterval(t))
+ })
+ const started = Date.now()
+ await expect(
+ requestPinned({
+ url: new URL(`http://localhost:${port}/`),
+ method: 'GET',
+ headers: {},
+ pinnedIp: '127.0.0.1',
+ timeoutMs: 10_000, // idle timer would only fire at 10s
+ signal: AbortSignal.timeout(80), // absolute deadline wins first
+ })
+ ).rejects.toThrow(/aborted/)
+ expect(Date.now() - started).toBeLessThan(2000) // settled promptly, not at 10s
+ })
+})
diff --git a/mcp-host/src/core/net/ssrf.ts b/mcp-host/src/core/net/ssrf.ts
index 4c6cac4e2..f2312cdec 100644
--- a/mcp-host/src/core/net/ssrf.ts
+++ b/mcp-host/src/core/net/ssrf.ts
@@ -247,8 +247,17 @@ export async function resolvePinnedPublicIp(url: URL): Promise<string> {
/**
* Make an HTTP(S) request to a caller-validated, DNS-pinned IP while keeping the
- * original hostname in the Host header and TLS SNI. Reads the full body (callers
- * apply their own size/parse policy) and rejects on error/timeout.
+ * original hostname in the Host header and TLS SNI. Rejects on error/timeout.
+ *
+ * The response is bounded in BOTH dimensions so an active-but-unbounded peer
+ * cannot hang or OOM the process:
+ * - `signal` — an ABSOLUTE deadline (e.g. `AbortSignal.timeout`). Node's socket
+ * `timeout` (below) is an IDLE timer that a trickling peer resets on every
+ * byte; the abort settles the request regardless of activity.
+ * - `maxBytes` — the body is capped WHILE streaming: once exceeded the request
+ * is destroyed, so an oversized body is never fully buffered (no memory spike,
+ * no `ERR_STRING_TOO_LONG` from `Buffer.concat().toString()`).
+ * Both are optional; omitting them preserves the prior behavior for other callers.
*/
export function requestPinned(opts: {
url: URL
@@ -257,9 +266,19 @@ export function requestPinned(opts: {
body?: string
pinnedIp: string
timeoutMs: number
+ /** Absolute-deadline abort (idle-independent). Destroys the request on abort. */
+ signal?: AbortSignal
+ /** Hard response-body cap; destroy + reject once exceeded (bytes). */
+ maxBytes?: number
}): Promise<{ statusCode: number; body: string }> {
- const { url, method, headers, body, pinnedIp, timeoutMs } = opts
+ const { url, method, headers, body, pinnedIp, timeoutMs, signal, maxBytes } = opts
return new Promise((resolve, reject) => {
+ let settled = false
+ const settle = (fn: () => void): void => {
+ if (settled) return
+ settled = true
+ fn()
+ }
const isHttps = url.protocol === 'https:'
const client = isHttps ? https : http
const defaultPort = isHttps ? 443 : 80
@@ -280,16 +299,34 @@ export function requestPinned(opts: {
}
const req = client.request(requestOptions, res => {
const chunks: Buffer[] = []
- res.on('data', chunk => chunks.push(chunk))
- res.on('end', () => {
- resolve({ statusCode: res.statusCode!, body: Buffer.concat(chunks).toString('utf-8') })
+ let total = 0
+ res.on('data', chunk => {
+ total += chunk.length
+ if (maxBytes !== undefined && total > maxBytes) {
+ // Destroy before buffering the over-limit chunk — 'error' → reject.
+ req.destroy(new Error('response exceeded maxBytes'))
+ return
+ }
+ chunks.push(chunk)
})
+ res.on('end', () =>
+ settle(() =>
+ resolve({ statusCode: res.statusCode!, body: Buffer.concat(chunks).toString('utf-8') })
+ )
+ )
})
- req.on('error', reject)
+ req.on('error', err => settle(() => reject(err)))
req.on('timeout', () => {
req.destroy()
- reject(new Error('Request timeout'))
+ settle(() => reject(new Error('Request timeout')))
})
+ if (signal) {
+ const onAbort = (): void => {
+ req.destroy(new Error('request aborted (deadline)'))
+ }
+ if (signal.aborted) onAbort()
+ else signal.addEventListener('abort', onAbort, { once: true })
+ }
if (body) req.write(body)
req.end()
})
diff --git a/mcp-host/src/main.ts b/mcp-host/src/main.ts
index c3c3f872d..b301574c5 100644
--- a/mcp-host/src/main.ts
+++ b/mcp-host/src/main.ts
@@ -3070,6 +3070,18 @@ async function main(): Promise<void> {
// side-effect free allows the authoritative initialization contract to be
// regression-tested without starting the service.
if (require.main === module) {
+ // Global crash guards (defense-in-depth): a throw that escapes a stray event
+ // listener (e.g. a transport listener) must be LOGGED, not a silent process
+ // exit. uncaughtException leaves the process in an undefined state, so we log
+ // and exit non-zero for a clean k8s restart; an unhandledRejection is logged
+ // for triage but is not treated as fatal on its own.
+ process.on('uncaughtException', (err, origin) => {
+ console.error(`[Main] FATAL uncaughtException (${origin}):`, err)
+ process.exit(1)
+ })
+ process.on('unhandledRejection', reason => {
+ console.error('[Main] unhandledRejection:', reason)
+ })
main().catch(error => {
console.error('[Main] Fatal error:', error)
process.exit(1)