Skip to content

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

TypeScript

feat: deliver Host execution bytes through private Pod channels

Alfredo Lopez5d5944087591
diff --git a/deploy/base/control-plane/networkpolicies.yaml b/deploy/base/control-plane/networkpolicies.yaml
index b51a1dc6c..7e2c499a6 100644
--- a/deploy/base/control-plane/networkpolicies.yaml
+++ b/deploy/base/control-plane/networkpolicies.yaml
@@ -999,3 +999,34 @@ spec:
- ipBlock:
cidr: 0.0.0.0/0
except: []
+
+---
+# Private execution results are retrieved directly from the validated Pod,
+# never from container logs or a caller-selected URL.
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+ name: hcc-to-private-execution-results
+ namespace: control-plane
+ labels:
+ clerum.io/policy-type: execution
+spec:
+ podSelector:
+ matchLabels:
+ app: host-context-controller
+ policyTypes:
+ - Egress
+ egress:
+ - to:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: mcp-host
+ podSelector:
+ matchLabels:
+ clerum.io/managed-by: host-context-controller
+ clerum.io/role: host-execution
+ ports:
+ - port: 9300
+ protocol: TCP
+ - port: 9301
+ protocol: TCP
diff --git a/deploy/base/mcp-host/networkpolicies.yaml b/deploy/base/mcp-host/networkpolicies.yaml
index c3bf4c687..9d561e0ce 100644
--- a/deploy/base/mcp-host/networkpolicies.yaml
+++ b/deploy/base/mcp-host/networkpolicies.yaml
@@ -27,6 +27,10 @@ spec:
podSelector:
matchLabels:
clerum.io/managed-by: host-context-controller
+ matchExpressions:
+ - key: clerum.io/role
+ operator: NotIn
+ values: [host-execution]
policyTypes:
- Egress
egress:
@@ -50,6 +54,10 @@ spec:
podSelector:
matchLabels:
clerum.io/managed-by: host-context-controller
+ matchExpressions:
+ - key: clerum.io/role
+ operator: NotIn
+ values: [host-execution]
policyTypes:
- Ingress
- Egress
@@ -142,6 +150,10 @@ spec:
podSelector:
matchLabels:
clerum.io/managed-by: host-context-controller
+ matchExpressions:
+ - key: clerum.io/role
+ operator: NotIn
+ values: [host-execution]
policyTypes:
- Egress
egress:
@@ -153,3 +165,36 @@ spec:
protocol: TCP
- port: 8443
protocol: TCP
+
+---
+# Execution Pods get no inherited Host API, DNS or public-network lane. Only
+# HCC can fetch/clear the private result portal; Pod UID is not user authority.
+apiVersion: networking.k8s.io/v1
+kind: NetworkPolicy
+metadata:
+ name: host-execution-private
+ namespace: mcp-host
+ labels:
+ clerum.io/policy-type: execution
+spec:
+ podSelector:
+ matchLabels:
+ clerum.io/managed-by: host-context-controller
+ clerum.io/role: host-execution
+ policyTypes:
+ - Ingress
+ - Egress
+ ingress:
+ - from:
+ - namespaceSelector:
+ matchLabels:
+ kubernetes.io/metadata.name: control-plane
+ podSelector:
+ matchLabels:
+ app: host-context-controller
+ ports:
+ - port: 9300
+ protocol: TCP
+ - port: 9301
+ protocol: TCP
+ egress: []
diff --git a/host-context-controller/package-lock.json b/host-context-controller/package-lock.json
index db02055f0..938e400a2 100644
--- a/host-context-controller/package-lock.json
+++ b/host-context-controller/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.376",
+ "version": "0.1.377",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-host-context-controller",
- "version": "0.1.376",
+ "version": "0.1.377",
"license": "SEE LICENSE IN LICENSE",
"dependencies": {
"@clerum/codex-catalog-projection": "file:../packages/codex-catalog-projection",
diff --git a/host-context-controller/package.json b/host-context-controller/package.json
index eb45e90ac..ef4a910fe 100644
--- a/host-context-controller/package.json
+++ b/host-context-controller/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-host-context-controller",
- "version": "0.1.376",
+ "version": "0.1.377",
"description": "Host Context Controller - provides McpServer CRDs to mcp-host via REST API",
"main": "dist/main.js",
"engines": {
diff --git a/host-context-controller/src/existenceReadMetrics.test.ts b/host-context-controller/src/existenceReadMetrics.test.ts
index 65ccd6a63..8cd58be85 100644
--- a/host-context-controller/src/existenceReadMetrics.test.ts
+++ b/host-context-controller/src/existenceReadMetrics.test.ts
@@ -28,13 +28,9 @@ it('initializes the real read registry before any test seeding', async () => {
// Review each exclusion when its enclosing operation changes. Counts describe
// expressions, not executions; a newly added direct read must be classified.
const readExclusions: Record<string, readonly [number, string]> = {
- 'hostExecution/operations.ts::inspect::readNamespacedPod': [
+ 'hostExecution/operations.ts::revalidatePod::readNamespacedPod': [
1,
- 'Exact Pod UID revalidation after private output retrieval',
- ],
- 'hostExecution/operations.ts::inspect::readNamespacedPodLog': [
- 1,
- 'Bounded execution result retrieval, not a resource existence decision',
+ 'Exact Pod UID revalidation across private input/output transport awaits',
],
'hostReconciler.ts::readHostDeploymentOrNull::readNamespacedDeployment': [
1,
@@ -264,7 +260,7 @@ function assertReadInventory(sources: Record<string, string>): void {
expect(excluded[id], `Stale or changed read exclusion: ${id}`).toBe(count)
}
expect(Object.values(wrapped).reduce((sum, count) => sum + count, 0)).toBe(27)
- expect(Object.values(excluded).reduce((sum, count) => sum + count, 0)).toBe(46)
+ expect(Object.values(excluded).reduce((sum, count) => sum + count, 0)).toBe(45)
}
it('classifies every direct dot-property production SDK read as observed or explicitly excluded', () => {
diff --git a/host-context-controller/src/hostExecution/inputTransport.test.ts b/host-context-controller/src/hostExecution/inputTransport.test.ts
new file mode 100644
index 000000000..b0cf100a7
--- /dev/null
+++ b/host-context-controller/src/hostExecution/inputTransport.test.ts
@@ -0,0 +1,91 @@
+import { describe, expect, it, vi } from 'vitest'
+import { Readable } from 'node:stream'
+import { ExecutionInputTransport } from './inputTransport'
+import { EXECUTION_POD_UID_HEADER } from './resultTransport'
+
+const target = { podUid: '00000000-1111-4111-8111-000000000004', podIp: '10.244.0.7' }
+const headers = { [EXECUTION_POD_UID_HEADER]: target.podUid }
+
+describe('private execution input transport', () => {
+ it('probes the fixed input listener without reading the original', async () => {
+ const probe = vi.fn<typeof fetch>(async () => new Response(null, { status: 204, headers }))
+ await expect(new ExecutionInputTransport(5_000, probe).ready(target)).resolves.toBe(true)
+ expect(probe).toHaveBeenCalledWith(
+ 'http://10.244.0.7:9301/ready',
+ expect.objectContaining({
+ method: 'GET',
+ headers,
+ redirect: 'error',
+ signal: expect.any(AbortSignal),
+ })
+ )
+ })
+
+ it('distinguishes initial listener refusal from every other failure', async () => {
+ const probe = vi
+ .fn<typeof fetch>()
+ .mockRejectedValueOnce(
+ Object.assign(new Error('fetch failed'), { cause: { code: 'ECONNREFUSED' } })
+ )
+ .mockRejectedValueOnce(
+ Object.assign(new Error('fetch failed'), { cause: { code: 'ENETUNREACH' } })
+ )
+ const transport = new ExecutionInputTransport(5_000, probe)
+ await expect(transport.ready(target)).resolves.toBe(false)
+ await expect(transport.ready(target)).rejects.toThrow('fetch failed')
+ })
+
+ it('streams a single opaque POST with a bound length, UID and real abort signal', async () => {
+ const input = Readable.from([Buffer.from([0, 255, 17])])
+ const send = vi.fn<typeof fetch>(async (_url, init) => {
+ const chunks: Buffer[] = []
+ for await (const chunk of init!.body as Readable) chunks.push(chunk)
+ expect(Buffer.concat(chunks)).toEqual(Buffer.from([0, 255, 17]))
+ return new Response(null, { status: 204, headers })
+ })
+ await new ExecutionInputTransport(5_000, send).send(target, input, 3)
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(send).toHaveBeenCalledWith(
+ 'http://10.244.0.7:9301/input',
+ expect.objectContaining({
+ method: 'POST',
+ duplex: 'half',
+ body: input,
+ redirect: 'error',
+ headers: { ...headers, 'content-type': 'application/octet-stream', 'content-length': '3' },
+ signal: expect.any(AbortSignal),
+ })
+ )
+ expect(input.destroyed).toBe(true)
+ })
+
+ it('never resends an ambiguous or rejected delivery and closes its stream', async () => {
+ for (const failure of ['network', 'foreign', 'rejected']) {
+ const input = Readable.from([Buffer.from('private')])
+ const send = vi.fn<typeof fetch>(async () => {
+ if (failure === 'network') throw new Error('delivery unknown')
+ return new Response(null, {
+ status: failure === 'rejected' ? 400 : 204,
+ headers: failure === 'foreign' ? { [EXECUTION_POD_UID_HEADER]: 'other' } : headers,
+ })
+ })
+ await expect(
+ new ExecutionInputTransport(5_000, send).send(target, input, 7)
+ ).rejects.toThrow()
+ expect(send).toHaveBeenCalledTimes(1)
+ expect(input.destroyed).toBe(true)
+ }
+ })
+
+ it('rejects a bad target or size before I/O', async () => {
+ const send = vi.fn<typeof fetch>()
+ const transport = new ExecutionInputTransport(5_000, send)
+ await expect(
+ transport.send({ ...target, podIp: '127.0.0.1' }, Readable.from([]), 0)
+ ).rejects.toThrow('execution_result_target_invalid')
+ await expect(transport.send(target, Readable.from([]), 11_534_337)).rejects.toThrow(
+ 'execution_input_contract_invalid'
+ )
+ expect(send).not.toHaveBeenCalled()
+ })
+})
diff --git a/host-context-controller/src/hostExecution/inputTransport.ts b/host-context-controller/src/hostExecution/inputTransport.ts
new file mode 100644
index 000000000..589282513
--- /dev/null
+++ b/host-context-controller/src/hostExecution/inputTransport.ts
@@ -0,0 +1,87 @@
+import type { Readable } from 'node:stream'
+import { EXECUTION_INPUT_MAX_BYTES } from './jobFactory'
+import {
+ EXECUTION_POD_UID_HEADER,
+ type ExecutionPodTarget,
+ executionPodAddress,
+} from './resultTransport'
+
+export const EXECUTION_INPUT_PORT = 9301
+
+/** One-shot opaque input delivery; failed/ambiguous POSTs are never retried. */
+export class ExecutionInputTransport {
+ constructor(
+ private readonly timeoutMs: number,
+ private readonly fetchResponse: typeof fetch = fetch
+ ) {
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 60_000) {
+ throw new Error('execution_input_timeout_invalid')
+ }
+ }
+
+ async ready(target: ExecutionPodTarget): Promise<boolean> {
+ let response: Response
+ try {
+ response = await this.fetchResponse(
+ `http://${executionPodAddress(target)}:${EXECUTION_INPUT_PORT}/ready`,
+ {
+ method: 'GET',
+ headers: { [EXECUTION_POD_UID_HEADER]: target.podUid },
+ redirect: 'error',
+ signal: AbortSignal.timeout(this.timeoutMs),
+ }
+ )
+ } catch (error) {
+ // Running is visible before the init process has bound its listener.
+ // Only that concrete connection refusal is a not-ready observation.
+ if ((error as { cause?: { code?: string } })?.cause?.code === 'ECONNREFUSED') return false
+ throw error
+ }
+ await response.body?.cancel()
+ if (response.headers.get(EXECUTION_POD_UID_HEADER) !== target.podUid) {
+ throw new Error('execution_input_binding_mismatch')
+ }
+ if (response.status !== 204) throw new Error('execution_input_unavailable')
+ return true
+ }
+
+ async send(
+ target: ExecutionPodTarget,
+ input: Readable,
+ byteLength: number,
+ signal?: AbortSignal
+ ): Promise<void> {
+ const address = executionPodAddress(target)
+ if (
+ !Number.isSafeInteger(byteLength) ||
+ byteLength < 0 ||
+ byteLength > EXECUTION_INPUT_MAX_BYTES
+ ) {
+ throw new Error('execution_input_contract_invalid')
+ }
+ const deadline = AbortSignal.timeout(this.timeoutMs)
+ try {
+ const response = await this.fetchResponse(`http://${address}:${EXECUTION_INPUT_PORT}/input`, {
+ method: 'POST',
+ headers: {
+ [EXECUTION_POD_UID_HEADER]: target.podUid,
+ 'content-type': 'application/octet-stream',
+ 'content-length': String(byteLength),
+ },
+ body: input,
+ duplex: 'half',
+ redirect: 'error',
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
+ })
+ await response.body?.cancel()
+ if (response.headers.get(EXECUTION_POD_UID_HEADER) !== target.podUid) {
+ throw new Error('execution_input_binding_mismatch')
+ }
+ if (response.status !== 204) throw new Error('execution_input_rejected')
+ } finally {
+ // The input is an operation-owned stream from the protected file store.
+ // Closing it does not delete the original or acknowledge physical purge.
+ input.destroy()
+ }
+ }
+}
diff --git a/host-context-controller/src/hostExecution/jobFactory.test.ts b/host-context-controller/src/hostExecution/jobFactory.test.ts
index 465fbefbb..9e7e3322e 100644
--- a/host-context-controller/src/hostExecution/jobFactory.test.ts
+++ b/host-context-controller/src/hostExecution/jobFactory.test.ts
@@ -168,7 +168,7 @@ describe('bounded Host execution job factory', () => {
])
expect(job.spec!.backoffLimit).toBe(0)
- expect(job.spec!.activeDeadlineSeconds).toBe(60)
+ expect(job.spec!.activeDeadlineSeconds).toBe(120)
expect(podSpec(job).restartPolicy).toBe('Never')
expect(podSpec(job).initContainers).toBeUndefined()
expect(volume(job, 'workspace').persistentVolumeClaim).toEqual({
@@ -188,6 +188,7 @@ describe('bounded Host execution job factory', () => {
expect(executor.env).toEqual([
{ name: 'HOME', value: EXECUTION_WORKSPACE_MOUNT_PATH },
{ name: 'TMPDIR', value: EXECUTION_TMP_MOUNT_PATH },
+ { name: 'EXECUTION_POD_UID', valueFrom: { fieldRef: { fieldPath: 'metadata.uid' } } },
])
})
@@ -247,6 +248,7 @@ describe('bounded Host execution job factory', () => {
expect(executor.env).toEqual([
{ name: 'HOME', value: EXECUTION_SCRATCH_MOUNT_PATH },
{ name: 'TMPDIR', value: EXECUTION_TMP_MOUNT_PATH },
+ { name: 'EXECUTION_POD_UID', valueFrom: { fieldRef: { fieldPath: 'metadata.uid' } } },
])
expect(collectNamespaces(job)).toEqual([identity.namespace])
})
@@ -264,10 +266,12 @@ describe('bounded Host execution job factory', () => {
String(attachmentRequest.timeoutMs),
])
expect(receiver.args).toBeUndefined()
- expect(receiver.stdin).toBe(true)
- expect(receiver.stdinOnce).toBe(true)
- expect(receiver.tty).toBe(false)
- expect(receiver.env).toBeUndefined()
+ expect(receiver.stdin).toBeUndefined()
+ expect(receiver.stdinOnce).toBeUndefined()
+ expect(receiver.tty).toBeUndefined()
+ expect(receiver.env).toEqual([
+ { name: 'EXECUTION_POD_UID', valueFrom: { fieldRef: { fieldPath: 'metadata.uid' } } },
+ ])
expect(receiver.envFrom).toBeUndefined()
expect(receiver.volumeMounts).toEqual([
{ name: 'input', mountPath: EXECUTION_INPUT_MOUNT_PATH, readOnly: false },
@@ -345,9 +349,9 @@ describe('bounded Host execution job factory', () => {
buildHostExecutionJob(identity, { ...workspaceRequest, timeoutMs }).spec!
.activeDeadlineSeconds
- expect(at(1_000)).toBe(1)
- expect(at(90_001)).toBe(91)
- expect(at(EXECUTION_TIMEOUT_MAX_MS)).toBe(1_500)
+ expect(at(1_000)).toBe(61)
+ expect(at(90_001)).toBe(151)
+ expect(at(EXECUTION_TIMEOUT_MAX_MS)).toBe(1_560)
for (const timeoutMs of [999, 0, -1, 1.5, EXECUTION_TIMEOUT_MAX_MS + 1, Number.NaN]) {
expect(
rejection(() => buildHostExecutionJob(identity, { ...workspaceRequest, timeoutMs })).field
diff --git a/host-context-controller/src/hostExecution/jobFactory.ts b/host-context-controller/src/hostExecution/jobFactory.ts
index 251a1d317..1086c2259 100644
--- a/host-context-controller/src/hostExecution/jobFactory.ts
+++ b/host-context-controller/src/hostExecution/jobFactory.ts
@@ -28,9 +28,12 @@ export const EXECUTION_EXECUTOR_CONTAINER_NAME = 'executor'
export const EXECUTION_INPUT_RECEIVER_CONTAINER_NAME = 'input-receiver'
/** Fixed receiver entrypoint inside the server-resolved Host image. */
export const EXECUTION_RECEIVE_INPUT_ENTRYPOINT =
- '/app/mcp-host/dist/core/execution/receiveInput.js'
-/** PID 1 captures aggregate output before it reaches the node's container log. */
-export const EXECUTION_RUN_ENTRYPOINT = '/app/mcp-host/dist/core/execution/runExecution.js'
+ '/app/mcp-host/dist/core/execution/receiveSession.js'
+export const EXECUTION_INPUT_PORT = 9301
+/** PID 1 retains captured results privately and serves only the scoped portal. */
+export const EXECUTION_RUN_ENTRYPOINT = '/app/mcp-host/dist/core/execution/runSession.js'
+export const EXECUTION_RESULT_PORT = 9300
+export const EXECUTION_POD_UID_ENV = 'EXECUTION_POD_UID'
export const EXECUTION_WORKSPACE_MOUNT_PATH = '/workspace'
export const EXECUTION_SCRATCH_MOUNT_PATH = '/scratch'
export const EXECUTION_TMP_MOUNT_PATH = '/tmp'
@@ -451,11 +454,11 @@ export function buildHostExecutionJob(
approved.input.sha256,
String(approved.timeoutMs),
],
- // The caller attaches to this init container to stream the payload;
- // stdinOnce closes the stream after the single input.
- stdin: true,
- stdinOnce: true,
- tty: false,
+ // One private HTTP stream is verified before this init process exits.
+ // No attach/exec subresource or service-account token is required.
+ env: [
+ { name: EXECUTION_POD_UID_ENV, valueFrom: { fieldRef: { fieldPath: 'metadata.uid' } } },
+ ],
volumeMounts: [
{ name: INPUT_VOLUME_NAME, mountPath: EXECUTION_INPUT_MOUNT_PATH, readOnly: false },
],
@@ -481,7 +484,15 @@ export function buildHostExecutionJob(
env: [
{ name: 'HOME', value: workingDir },
{ name: 'TMPDIR', value: EXECUTION_TMP_MOUNT_PATH },
+ { name: EXECUTION_POD_UID_ENV, valueFrom: { fieldRef: { fieldPath: 'metadata.uid' } } },
],
+ ports: [{ name: 'result', containerPort: EXECUTION_RESULT_PORT, protocol: 'TCP' }],
+ readinessProbe: {
+ tcpSocket: { port: 'result' },
+ periodSeconds: 1,
+ timeoutSeconds: 1,
+ failureThreshold: 5,
+ },
volumeMounts: executorMounts,
resources: {
requests: { cpu: '100m', memory: '64Mi' },
@@ -540,7 +551,9 @@ export function buildHostExecutionJob(
},
spec: {
backoffLimit: 0,
- activeDeadlineSeconds: Math.ceil(approved.timeoutMs / 1000),
+ // Includes the bounded private-result delivery window. Command runtime
+ // itself is still limited by the launcher to the approved timeout.
+ activeDeadlineSeconds: Math.ceil(approved.timeoutMs / 1000) + 60,
template: {
metadata: { labels, annotations },
spec: podSpec,
diff --git a/host-context-controller/src/hostExecution/networkPolicy.test.ts b/host-context-controller/src/hostExecution/networkPolicy.test.ts
new file mode 100644
index 000000000..635bbf50a
--- /dev/null
+++ b/host-context-controller/src/hostExecution/networkPolicy.test.ts
@@ -0,0 +1,84 @@
+import { describe, expect, it } from 'vitest'
+import type * as k8s from '@kubernetes/client-node'
+import { readFileSync } from 'node:fs'
+import { resolve } from 'node:path'
+import { parseAllDocuments } from 'yaml'
+
+function policies(path: string): k8s.V1NetworkPolicy[] {
+ return parseAllDocuments(readFileSync(resolve(__dirname, '../../../', path), 'utf8'))
+ .map(document => document.toJSON())
+ .filter(object => object?.kind === 'NetworkPolicy')
+}
+
+describe('private execution network lane', () => {
+ it('excludes execution Pods from every inherited static Host egress grant', () => {
+ const list = policies('deploy/base/mcp-host/networkpolicies.yaml')
+ const names = ['mcp-host', 'allow-dns-egress-mcp-host', 'allow-k8s-api-egress-mcp-host']
+ for (const name of names) {
+ const policy = list.find(item => item.metadata?.name === name)
+ expect(policy?.spec?.podSelector).toEqual({
+ matchLabels: { 'clerum.io/managed-by': 'host-context-controller' },
+ matchExpressions: [
+ { key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] },
+ ],
+ })
+ expect(policy?.spec?.egress?.length).toBeGreaterThan(0)
+ }
+ expect(list.find(p => p.metadata?.name === 'deny-all-mcp-host')?.spec?.podSelector).toEqual({})
+ })
+
+ it('admits only HCC on the private result port and grants no execution egress', () => {
+ const policy = policies('deploy/base/mcp-host/networkpolicies.yaml').find(
+ item => item.metadata?.name === 'host-execution-private'
+ )
+ expect(policy?.spec).toEqual({
+ podSelector: {
+ matchLabels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ 'clerum.io/role': 'host-execution',
+ },
+ },
+ policyTypes: ['Ingress', 'Egress'],
+ ingress: [
+ {
+ from: [
+ {
+ namespaceSelector: {
+ matchLabels: { 'kubernetes.io/metadata.name': 'control-plane' },
+ },
+ podSelector: { matchLabels: { app: 'host-context-controller' } },
+ },
+ ],
+ ports: [
+ { port: 9300, protocol: 'TCP' },
+ { port: 9301, protocol: 'TCP' },
+ ],
+ },
+ ],
+ egress: [],
+ })
+ const reverse = policies('deploy/base/control-plane/networkpolicies.yaml').find(
+ item => item.metadata?.name === 'hcc-to-private-execution-results'
+ )
+ expect(reverse?.spec?.podSelector).toEqual({ matchLabels: { app: 'host-context-controller' } })
+ expect(reverse?.spec?.egress).toEqual([
+ {
+ to: [
+ {
+ namespaceSelector: { matchLabels: { 'kubernetes.io/metadata.name': 'mcp-host' } },
+ podSelector: {
+ matchLabels: {
+ 'clerum.io/managed-by': 'host-context-controller',
+ 'clerum.io/role': 'host-execution',
+ },
+ },
+ },
+ ],
+ ports: [
+ { port: 9300, protocol: 'TCP' },
+ { port: 9301, protocol: 'TCP' },
+ ],
+ },
+ ])
+ })
+})
diff --git a/host-context-controller/src/hostExecution/operations.test.ts b/host-context-controller/src/hostExecution/operations.test.ts
index c4b74db84..be724775d 100644
--- a/host-context-controller/src/hostExecution/operations.test.ts
+++ b/host-context-controller/src/hostExecution/operations.test.ts
@@ -1,8 +1,13 @@
import { describe, expect, it, vi } from 'vitest'
import type * as k8s from '@kubernetes/client-node'
+import { Readable } from 'node:stream'
import type { VerifiedMcpHostPrincipal } from '../mcpApiAuthentication'
import { HostExecutionAuthorization, type HostExecutionHostRecord } from './authorization'
-import { type TrustedHostExecutionIdentity, buildHostExecutionJob } from './jobFactory'
+import {
+ type ApprovedExecutionRequest,
+ type TrustedHostExecutionIdentity,
+ buildHostExecutionJob,
+} from './jobFactory'
import { HostExecutionOperations } from './operations'
const identity: TrustedHostExecutionIdentity = {
@@ -44,14 +49,14 @@ const capturedResult = {
stderr: '',
}
-function fixture() {
+function fixture(approvedRequest: ApprovedExecutionRequest = request) {
let host: HostExecutionHostRecord | null = {
name: identity.hostName,
namespace: identity.namespace,
uid: identity.hostUid,
generation: identity.hostGeneration,
}
- let job: k8s.V1Job | null = buildHostExecutionJob(identity, request)
+ let job: k8s.V1Job | null = buildHostExecutionJob(identity, approvedRequest)
job.metadata!.uid = jobUid
const pod: k8s.V1Pod = {
metadata: {
@@ -69,14 +74,15 @@ function fixture() {
],
},
status: {
+ podIP: '10.244.0.7',
containerStatuses: [
{
name: 'executor',
image: identity.image,
imageID: 'unit-image',
- ready: false,
+ ready: true,
restartCount: 0,
- state: { terminated: { exitCode: 0 } },
+ state: { running: {} },
},
],
},
@@ -97,18 +103,31 @@ function fixture() {
const core = {
listNamespacedPod: vi.fn(async (_request: unknown) => ({ items: pods })),
readNamespacedPod: vi.fn(async (_request: unknown) => pod),
- readNamespacedPodLog: vi.fn(async (_request: unknown) => JSON.stringify(capturedResult)),
+ }
+ const results = {
+ read: vi.fn(async (_target: unknown): Promise<string | null> => JSON.stringify(capturedResult)),
+ clear: vi.fn(async (_target: unknown) => {}),
+ }
+ const inputs = {
+ ready: vi.fn(async (_target: unknown) => true),
+ send: vi.fn(
+ async (_target: unknown, _input: Readable, _bytes: number, _signal?: AbortSignal) => {}
+ ),
}
const authorization = new HostExecutionAuthorization(async () => host)
const operations = new HostExecutionOperations(
batch as unknown as ConstructorParameters<typeof HostExecutionOperations>[0],
core as unknown as ConstructorParameters<typeof HostExecutionOperations>[1],
- authorization
+ authorization,
+ results,
+ inputs
)
return {
operations,
batch,
core,
+ results,
+ inputs,
pod,
getJob: () => job!,
setJob: (value: k8s.V1Job | null) => {
@@ -178,20 +197,14 @@ describe('Host execution operations', () => {
const renewed = { ...principal, jti: 'renewed-unit-test' }
const result = await f.operations.inspect(renewed, handle)
expect(result).toEqual({ state: 'completed', podUid, result: capturedResult })
- expect(f.core.readNamespacedPodLog).toHaveBeenCalledWith(
- expect.objectContaining({
- container: 'executor',
- follow: false,
- limitBytes: 98_305,
- })
- )
+ expect(f.results.read).toHaveBeenCalledWith({ podUid, podIp: '10.244.0.7' })
expect(f.batch.createNamespacedJob).toHaveBeenCalledTimes(1)
})
it('does not publish output if generation changes during its retrieval', async () => {
const f = fixture()
const handle = await f.operations.start(principal, identity, request)
- f.core.readNamespacedPodLog.mockImplementationOnce(async () => {
+ f.results.read.mockImplementationOnce(async () => {
f.setHost({
name: identity.hostName,
namespace: identity.namespace,
@@ -212,28 +225,29 @@ describe('Host execution operations', () => {
await expect(f.operations.inspect(principal, handle)).rejects.toThrow(
change === 'job' ? 'job_uid_replaced' : 'pod_owner_mismatch'
)
- expect(f.core.readNamespacedPodLog).not.toHaveBeenCalled()
+ expect(f.results.read).not.toHaveBeenCalled()
}
})
- it('reports queued or running without fetching logs', async () => {
+ it('reports queued without I/O and running while the result is pending', async () => {
const f = fixture()
const handle = await f.operations.start(principal, identity, request)
f.setPods([])
await expect(f.operations.inspect(principal, handle)).resolves.toEqual({ state: 'queued' })
f.setPods([f.pod])
f.pod.status!.containerStatuses![0].state = { running: {} }
+ f.results.read.mockResolvedValueOnce(null)
await expect(f.operations.inspect(principal, handle)).resolves.toEqual({
state: 'running',
podUid,
})
- expect(f.core.readNamespacedPodLog).not.toHaveBeenCalled()
+ expect(f.results.read).toHaveBeenCalledTimes(1)
})
it('refuses an oversized producer frame rather than publishing a partial result', async () => {
const f = fixture()
const handle = await f.operations.start(principal, identity, request)
- f.core.readNamespacedPodLog.mockResolvedValueOnce('x'.repeat(100_000))
+ f.results.read.mockResolvedValueOnce('x'.repeat(100_000))
await expect(f.operations.inspect(principal, handle)).rejects.toThrow(
'execution_result_invalid'
)
@@ -269,10 +283,10 @@ describe('Host execution operations', () => {
await expect(f.operations.cancel(principal, handle)).rejects.toThrow('API unavailable')
})
- it('withholds logs when the Pod is replaced while log retrieval is pending', async () => {
+ it('withholds results when the Pod is replaced during retrieval', async () => {
const f = fixture()
const handle = await f.operations.start(principal, identity, request)
- f.core.readNamespacedPodLog.mockImplementationOnce(async () => {
+ f.results.read.mockImplementationOnce(async () => {
f.pod.metadata!.uid = 'replacement-pod'
return 'output from a replaced pod'
})
@@ -290,4 +304,109 @@ describe('Host execution operations', () => {
'execution_pod_inventory_ambiguous'
)
})
+
+ it('opens and streams exactly the prepared input only after receiver readiness and authority checks', async () => {
+ const attachment: ApprovedExecutionRequest = {
+ ...request,
+ kind: 'attachment',
+ input: { byteLength: 3, sha256: 'a'.repeat(64) },
+ }
+ const f = fixture(attachment)
+ f.pod.status!.initContainerStatuses = [
+ {
+ name: 'input-receiver',
+ image: identity.image,
+ imageID: 'unit-input-image',
+ ready: false,
+ restartCount: 0,
+ state: { running: {} },
+ },
+ ]
+ const handle = await f.operations.start(principal, identity, attachment)
+ const input = Readable.from([Buffer.from([0, 255, 17])])
+ const open = vi.fn(async () => input)
+ await expect(f.operations.deliverInput(principal, handle, open)).resolves.toEqual({
+ state: 'input_delivered',
+ podUid,
+ })
+ expect(open).toHaveBeenCalledTimes(1)
+ expect(f.inputs.send).toHaveBeenCalledWith({ podUid, podIp: '10.244.0.7' }, input, 3, undefined)
+ expect(input.destroyed).toBe(true)
+ f.pod.status!.initContainerStatuses[0].state = { terminated: { exitCode: 0 } }
+ await expect(f.operations.deliverInput(principal, handle, open)).resolves.toEqual({
+ state: 'input_delivered',
+ podUid,
+ })
+ expect(open).toHaveBeenCalledTimes(1)
+ expect(f.inputs.send).toHaveBeenCalledTimes(1)
+ })
+
+ it('does not open a file for a pending or replaced receiver', async () => {
+ const attachment: ApprovedExecutionRequest = {
+ ...request,
+ kind: 'attachment',
+ input: { byteLength: 3, sha256: 'a'.repeat(64) },
+ }
+ const f = fixture(attachment)
+ f.pod.status!.initContainerStatuses = [
+ {
+ name: 'input-receiver',
+ image: identity.image,
+ imageID: 'unit-input-image',
+ ready: false,
+ restartCount: 0,
+ state: { running: {} },
+ },
+ ]
+ const handle = await f.operations.start(principal, identity, attachment)
+ const open = vi.fn(async () => Readable.from([]))
+ f.inputs.ready.mockResolvedValueOnce(false)
+ await expect(f.operations.deliverInput(principal, handle, open)).resolves.toEqual({
+ state: 'input_pending',
+ podUid,
+ })
+ expect(open).not.toHaveBeenCalled()
+ f.inputs.ready.mockImplementationOnce(async () => {
+ f.pod.metadata!.uid = 'replacement'
+ return true
+ })
+ await expect(f.operations.deliverInput(principal, handle, open)).rejects.toThrow(
+ 'pod_uid_replaced'
+ )
+ expect(open).not.toHaveBeenCalled()
+ })
+
+ it('closes an opened input without delivering bytes when authority changes during file opening', async () => {
+ const attachment: ApprovedExecutionRequest = {
+ ...request,
+ kind: 'attachment',
+ input: { byteLength: 3, sha256: 'a'.repeat(64) },
+ }
+ const f = fixture(attachment)
+ f.pod.status!.initContainerStatuses = [
+ {
+ name: 'input-receiver',
+ image: identity.image,
+ imageID: 'unit-input-image',
+ ready: false,
+ restartCount: 0,
+ state: { running: {} },
+ },
+ ]
+ const handle = await f.operations.start(principal, identity, attachment)
+ const input = Readable.from([Buffer.from('private')])
+ await expect(
+ f.operations.deliverInput(principal, handle, async () => {
+ f.setHost({
+ name: identity.hostName,
+ namespace: identity.namespace,
+ uid: identity.hostUid,
+ generation: 8,
+ })
+ return input
+ })
+ ).rejects.toThrow('host_generation_changed')
+ expect(f.inputs.send).not.toHaveBeenCalled()
+ expect(input.destroyed).toBe(true)
+ })
})
diff --git a/host-context-controller/src/hostExecution/operations.ts b/host-context-controller/src/hostExecution/operations.ts
index e0ac77480..a3bb83839 100644
--- a/host-context-controller/src/hostExecution/operations.ts
+++ b/host-context-controller/src/hostExecution/operations.ts
@@ -1,7 +1,9 @@
import type * as k8s from '@kubernetes/client-node'
+import type { Readable } from 'node:stream'
import type { VerifiedMcpHostPrincipal } from '../mcpApiAuthentication'
import { getErrorCode, observeCreate, observeExistenceRead } from '../utils'
import { HostExecutionAuthorization, type HostExecutionBinding } from './authorization'
+import type { ExecutionInputTransport } from './inputTransport'
import {
type ApprovedExecutionRequest,
EXECUTION_EXECUTOR_CONTAINER_NAME,
@@ -12,20 +14,14 @@ import {
validateHostExecutionJob,
validateHostExecutionPod,
} from './jobFactory'
-import {
- EXECUTION_RESULT_MAX_BYTES,
- type HostExecutionResult,
- parseHostExecutionResult,
-} from './result'
+import { type HostExecutionResult, parseHostExecutionResult } from './result'
+import type { ExecutionResultTransport } from './resultTransport'
type BatchApi = Pick<
k8s.BatchV1Api,
'createNamespacedJob' | 'readNamespacedJob' | 'deleteNamespacedJob'
>
-type CoreApi = Pick<
- k8s.CoreV1Api,
- 'listNamespacedPod' | 'readNamespacedPod' | 'readNamespacedPodLog'
->
+type CoreApi = Pick<k8s.CoreV1Api, 'listNamespacedPod' | 'readNamespacedPod'>
/** Internal receipt retained with the prepared operation, never reconstructed
* from a new upload or a caller-selected Host name. Contains no bearer token.
@@ -39,7 +35,7 @@ export interface HostExecutionHandle {
export type HostExecutionObservation =
| { state: 'queued' }
| { state: 'waiting_for_input' | 'running'; podUid: string }
- | { state: 'failed'; podUid: string; reason: 'input_receive_failed' }
+ | { state: 'failed'; podUid: string; reason: 'input_receive_failed' | 'execution_terminated' }
| { state: 'completed'; podUid: string; result: HostExecutionResult }
function bindingFor(identity: TrustedHostExecutionIdentity): HostExecutionBinding {
@@ -80,7 +76,9 @@ export class HostExecutionOperations {
constructor(
private readonly batch: BatchApi,
private readonly core: CoreApi,
- private readonly authorization: HostExecutionAuthorization
+ private readonly authorization: HostExecutionAuthorization,
+ private readonly results: Pick<ExecutionResultTransport, 'read' | 'clear'>,
+ private readonly inputs: Pick<ExecutionInputTransport, 'ready' | 'send'>
) {}
async start(
@@ -146,6 +144,66 @@ export class HostExecutionOperations {
return pods.items
}
+ private async revalidatePod(
+ handle: HostExecutionHandle,
+ name: string,
+ uid: string
+ ): Promise<void> {
+ const job = await this.readJob(handle)
+ if (!job) throw new Error('execution_not_found')
+ const pod = await this.core.readNamespacedPod({ namespace: handle.identity.namespace, name })
+ validateHostExecutionPod(pod, job, handle.identity, handle.request, uid)
+ }
+
+ async deliverInput(
+ principal: VerifiedMcpHostPrincipal,
+ handle: HostExecutionHandle,
+ openInput: () => Promise<Readable>,
+ signal?: AbortSignal
+ ): Promise<{ state: 'input_pending' | 'input_delivered'; podUid?: string }> {
+ const binding = bindingFor(handle.identity)
+ await this.authorization.revalidate(principal, binding)
+ if (handle.request.kind !== 'attachment' || !handle.request.input) {
+ throw new Error('execution_input_contract_invalid')
+ }
+ const job = await this.readJob(handle)
+ if (!job) throw new Error('execution_not_found')
+ const pods = await this.readPods(handle)
+ await this.authorization.revalidate(principal, binding)
+ if (!pods.length) return { state: 'input_pending' }
+ const pod = pods[0]
+ validateHostExecutionPod(pod, job, handle.identity, handle.request)
+ const podUid = pod.metadata!.uid!
+ const receiver = pod.status?.initContainerStatuses?.find(
+ container => container.name === EXECUTION_INPUT_RECEIVER_CONTAINER_NAME
+ )
+ if (receiver?.state?.terminated) {
+ if (receiver.state.terminated.exitCode === 0) return { state: 'input_delivered', podUid }
+ throw new Error('execution_input_rejected')
+ }
+ if (!receiver?.state?.running) return { state: 'input_pending', podUid }
+ const podIp = pod.status?.podIP
+ if (!podIp || pod.spec?.hostNetwork === true) throw new Error('execution_result_target_invalid')
+ const target = { podUid, podIp }
+ const ready = await this.inputs.ready(target)
+ await this.revalidatePod(handle, pod.metadata!.name!, podUid)
+ await this.authorization.revalidate(principal, binding)
+ if (!ready) return { state: 'input_pending', podUid }
+ // The caller opens only the owner/generation/incarnation-bound file. This
+ // callback is never invoked for a queued, stale or foreign operation.
+ const input = await openInput()
+ try {
+ await this.revalidatePod(handle, pod.metadata!.name!, podUid)
+ await this.authorization.revalidate(principal, binding)
+ await this.inputs.send(target, input, handle.request.input.byteLength, signal)
+ await this.revalidatePod(handle, pod.metadata!.name!, podUid)
+ await this.authorization.revalidate(principal, binding)
+ return { state: 'input_delivered', podUid }
+ } finally {
+ input.destroy()
+ }
+ }
+
async inspect(
principal: VerifiedMcpHostPrincipal,
handle: HostExecutionHandle
@@ -163,13 +221,15 @@ export class HostExecutionOperations {
const executor = pod.status?.containerStatuses?.find(
container => container.name === EXECUTION_EXECUTOR_CONTAINER_NAME
)
- if (!executor?.state?.terminated) {
+ if (!executor?.state?.running) {
const receiver = pod.status?.initContainerStatuses?.find(
container => container.name === EXECUTION_INPUT_RECEIVER_CONTAINER_NAME
)
if (receiver?.state?.terminated && receiver.state.terminated.exitCode !== 0) {
return { state: 'failed', podUid, reason: 'input_receive_failed' }
}
+ if (executor?.state?.terminated)
+ return { state: 'failed', podUid, reason: 'execution_terminated' }
return {
state:
handle.request.kind === 'attachment' && !executor?.state?.running
@@ -178,24 +238,16 @@ export class HostExecutionOperations {
podUid,
}
}
+ if (!executor.ready) return { state: 'running', podUid }
const podName = pod.metadata!.name!
- const output = await this.core.readNamespacedPodLog({
- namespace: handle.identity.namespace,
- name: podName,
- container: EXECUTION_EXECUTOR_CONTAINER_NAME,
- follow: false,
- limitBytes: EXECUTION_RESULT_MAX_BYTES + 1,
- })
+ const podIp = pod.status?.podIP
+ if (!podIp || pod.spec?.hostNetwork === true) throw new Error('execution_result_target_invalid')
+ const output = await this.results.read({ podUid, podIp })
// A replaced Job cannot supply a result for the saved operation even if
// it uses the same name. Check again after retrieving private output.
- const currentJob = await this.readJob(handle)
- if (!currentJob) throw new Error('execution_not_found')
- const currentPod = await this.core.readNamespacedPod({
- namespace: handle.identity.namespace,
- name: podName,
- })
- validateHostExecutionPod(currentPod, currentJob, handle.identity, handle.request, podUid)
+ await this.revalidatePod(handle, podName, podUid)
await this.authorization.revalidate(principal, binding)
+ if (output === null) return { state: 'running', podUid }
return {
state: 'completed',
podUid,
diff --git a/host-context-controller/src/hostExecution/resultTransport.test.ts b/host-context-controller/src/hostExecution/resultTransport.test.ts
new file mode 100644
index 000000000..aad42e8e4
--- /dev/null
+++ b/host-context-controller/src/hostExecution/resultTransport.test.ts
@@ -0,0 +1,111 @@
+import { describe, expect, it, vi } from 'vitest'
+import { EXECUTION_RESULT_MAX_BYTES } from './result'
+import { EXECUTION_POD_UID_HEADER, ExecutionResultTransport } from './resultTransport'
+
+const target = { podUid: '00000000-1111-4111-8111-000000000004', podIp: '10.244.0.7' }
+const headers = { [EXECUTION_POD_UID_HEADER]: target.podUid, 'content-type': 'application/json' }
+
+describe('private execution result transport', () => {
+ it('requests only the fixed Pod port/path with UID binding and a finite abort signal', async () => {
+ const read = vi.fn<typeof fetch>(async () => new Response('{"result":"bounded"}', { headers }))
+ await expect(new ExecutionResultTransport(5_000, read).read(target)).resolves.toBe(
+ '{"result":"bounded"}'
+ )
+ expect(read).toHaveBeenCalledWith('http://10.244.0.7:9300/result', {
+ method: 'GET',
+ headers: { [EXECUTION_POD_UID_HEADER]: target.podUid, 'cache-control': 'no-store' },
+ redirect: 'error',
+ signal: expect.any(AbortSignal),
+ })
+ })
+
+ it('treats readiness separately from failures and never delivers a reused-IP result', async () => {
+ const read = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response('', { status: 425, headers }))
+ .mockResolvedValueOnce(
+ new Response('foreign result', {
+ headers: { ...headers, [EXECUTION_POD_UID_HEADER]: 'foreign-pod' },
+ })
+ )
+ const transport = new ExecutionResultTransport(5_000, read)
+ await expect(transport.read(target)).resolves.toBeNull()
+ await expect(transport.read(target)).rejects.toThrow('execution_result_binding_mismatch')
+ })
+
+ it('rejects caller URLs, loopback, link-local, multicast and malformed identity before I/O', async () => {
+ const read = vi.fn<typeof fetch>()
+ const transport = new ExecutionResultTransport(5_000, read)
+ for (const podIp of [
+ 'http://host/path',
+ '127.0.0.1',
+ '169.254.1.2',
+ '0.0.0.0',
+ '224.0.0.1',
+ '::1',
+ '::',
+ 'fe80::1',
+ 'ff00::1',
+ '::ffff:127.0.0.1',
+ '::ffff:7f00:1',
+ '0:0:0:0:0:0:0:1',
+ ]) {
+ await expect(transport.read({ ...target, podIp })).rejects.toThrow(
+ 'execution_result_target_invalid'
+ )
+ }
+ await expect(transport.read({ ...target, podUid: 'caller-supplied-name' })).rejects.toThrow(
+ 'execution_result_target_invalid'
+ )
+ expect(read).not.toHaveBeenCalled()
+ })
+
+ it('supports an actual IPv6 Pod address without caller-selected syntax', async () => {
+ const read = vi.fn<typeof fetch>(async () => new Response('{}', { headers }))
+ await new ExecutionResultTransport(5_000, read).read({ ...target, podIp: 'fd00::17' })
+ expect(read.mock.calls[0]?.[0]).toBe('http://[fd00::17]:9300/result')
+ })
+
+ it('bounds streamed bytes even when no content length is present', async () => {
+ let cancelled = false
+ const body = new ReadableStream<Uint8Array>({
+ start(controller) {
+ controller.enqueue(new Uint8Array(EXECUTION_RESULT_MAX_BYTES + 1))
+ },
+ cancel() {
+ cancelled = true
+ },
+ })
+ const read = vi.fn<typeof fetch>(async () => new Response(body, { headers }))
+ await expect(new ExecutionResultTransport(5_000, read).read(target)).rejects.toThrow(
+ 'execution_result_invalid'
+ )
+ expect(cancelled).toBe(true)
+ })
+
+ it('rejects an oversized declared body, non-JSON response and unavailable endpoint', async () => {
+ for (const response of [
+ new Response('{}', {
+ headers: { ...headers, 'content-length': String(EXECUTION_RESULT_MAX_BYTES + 1) },
+ }),
+ new Response('{}', { headers: { ...headers, 'content-type': 'text/html' } }),
+ new Response('{}', { status: 503, headers }),
+ ]) {
+ const read = vi.fn<typeof fetch>(async () => response)
+ await expect(new ExecutionResultTransport(5_000, read).read(target)).rejects.toThrow(
+ /execution_result_(invalid|unavailable)/
+ )
+ }
+ })
+
+ it('clears only the same Pod result and keeps a failed clear pending', async () => {
+ const read = vi
+ .fn<typeof fetch>()
+ .mockResolvedValueOnce(new Response(null, { status: 204, headers }))
+ .mockResolvedValueOnce(new Response(null, { status: 503, headers }))
+ const transport = new ExecutionResultTransport(5_000, read)
+ await expect(transport.clear(target)).resolves.toBeUndefined()
+ expect(read.mock.calls[0]?.[1]?.method).toBe('DELETE')
+ await expect(transport.clear(target)).rejects.toThrow('execution_result_clear_pending')
+ })
+})
diff --git a/host-context-controller/src/hostExecution/resultTransport.ts b/host-context-controller/src/hostExecution/resultTransport.ts
new file mode 100644
index 000000000..1b397bc0b
--- /dev/null
+++ b/host-context-controller/src/hostExecution/resultTransport.ts
@@ -0,0 +1,120 @@
+import { isIP } from 'node:net'
+import { EXECUTION_RESULT_MAX_BYTES } from './result'
+
+export const EXECUTION_RESULT_PORT = 9300
+export const EXECUTION_POD_UID_HEADER = 'x-execution-pod-uid'
+
+/** Address must come from the exact, live, API-validated execution Pod. */
+export interface ExecutionPodTarget {
+ podUid: string
+ podIp: string
+}
+
+export function executionPodAddress(target: ExecutionPodTarget): string {
+ const { podIp, podUid } = target
+ if (!/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/.test(podUid)) {
+ throw new Error('execution_result_target_invalid')
+ }
+ const kind = isIP(podIp)
+ const canonical =
+ kind === 6 && !podIp.includes('%')
+ ? new URL(`http://[${podIp}]/`).hostname.slice(1, -1).toLowerCase()
+ : podIp
+ const ipv4 = kind === 4 ? podIp : ''
+ const first = Number(ipv4.split('.')[0])
+ if (
+ !kind ||
+ podIp.includes('%') ||
+ canonical === '::' ||
+ canonical === '::1' ||
+ /^fe[89ab]/i.test(canonical) ||
+ /^ff/i.test(canonical) ||
+ canonical.startsWith('::ffff:') ||
+ (ipv4 && (first === 0 || first === 127 || first >= 224 || ipv4.startsWith('169.254.')))
+ ) {
+ throw new Error('execution_result_target_invalid')
+ }
+ return kind === 6 ? `[${canonical}]` : podIp
+}
+
+/**
+ * Private Pod-to-HCC result transport. It neither reads container logs nor
+ * forwards credentials. Network policy must admit only HCC to this port.
+ * The Pod UID header prevents delivery from a subsequently reused Pod IP.
+ */
+export class ExecutionResultTransport {
+ constructor(
+ private readonly timeoutMs: number,
+ private readonly fetchResponse: typeof fetch = fetch
+ ) {
+ if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > 60_000) {
+ throw new Error('execution_result_timeout_invalid')
+ }
+ }
+
+ private async request(
+ target: ExecutionPodTarget,
+ method: 'GET' | 'DELETE',
+ signal?: AbortSignal
+ ): Promise<Response> {
+ const deadline = AbortSignal.timeout(this.timeoutMs)
+ const response = await this.fetchResponse(
+ `http://${executionPodAddress(target)}:${EXECUTION_RESULT_PORT}/result`,
+ {
+ method,
+ headers: { [EXECUTION_POD_UID_HEADER]: target.podUid, 'cache-control': 'no-store' },
+ redirect: 'error',
+ signal: signal ? AbortSignal.any([signal, deadline]) : deadline,
+ }
+ )
+ if (response.headers.get(EXECUTION_POD_UID_HEADER) !== target.podUid) {
+ await response.body?.cancel()
+ throw new Error('execution_result_binding_mismatch')
+ }
+ return response
+ }
+
+ async read(target: ExecutionPodTarget, signal?: AbortSignal): Promise<string | null> {
+ const response = await this.request(target, 'GET', signal)
+ if (response.status === 425) {
+ await response.body?.cancel()
+ return null
+ }
+ if (
+ response.status !== 200 ||
+ response.headers.get('content-type')?.split(';', 1)[0].trim() !== 'application/json' ||
+ !response.body
+ ) {
+ await response.body?.cancel()
+ throw new Error('execution_result_unavailable')
+ }
+ const declared = response.headers.get('content-length')
+ if (declared && (!/^\d+$/.test(declared) || Number(declared) > EXECUTION_RESULT_MAX_BYTES)) {
+ await response.body.cancel()
+ throw new Error('execution_result_invalid')
+ }
+ const reader = response.body.getReader()
+ const chunks: Uint8Array[] = []
+ let bytes = 0
+ try {
+ for (;;) {
+ const { value, done } = await reader.read()
+ if (done) break
+ bytes += value.byteLength
+ if (bytes > EXECUTION_RESULT_MAX_BYTES) throw new Error('execution_result_invalid')
+ chunks.push(value)
+ }
+ return Buffer.concat(chunks).toString('utf8')
+ } finally {
+ await reader.cancel()
+ reader.releaseLock()
+ }
+ }
+
+ /** A result-clear acknowledgement is not a physical workload/store receipt. */
+ async clear(target: ExecutionPodTarget, signal?: AbortSignal): Promise<void> {
+ const response = await this.request(target, 'DELETE', signal)
+ await response.body?.cancel()
+ if (response.status !== 204) throw new Error('execution_result_clear_pending')
+ }
+}
diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.ts
index b87f4b42b..74992409e 100644
--- a/host-context-controller/src/networkPolicyReconciler.test.ts
+++ b/host-context-controller/src/networkPolicyReconciler.test.ts
@@ -535,6 +535,28 @@ describe('NetworkPolicyReconciler', () => {
// ─── L1: Infrastructure Policies ───────────────────────────────────
describe('L1 — ensureInfrastructurePolicies', () => {
+ it('keeps trusted Host infrastructure access while excluding isolated execution Pods', async () => {
+ mockApi.readNamespacedNetworkPolicy.mockRejectedValue({ code: 404 })
+ await reconciler.ensureDefaultPolicies()
+ const emitted = mockApi.createNamespacedNetworkPolicy.mock.calls.map(
+ (call: unknown[]) => (call[0] as { body: k8s.V1NetworkPolicy }).body
+ )
+ const exclusion = [{ key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] }]
+ for (const kind of ['dns', 'hcc-api', 'k8s-api']) {
+ const selector = emitted.find(p => p.metadata?.name === `allow-${kind}-egress-mcp-host`)
+ ?.spec?.podSelector
+ expect(selector).toEqual({
+ ...(kind === 'dns' ? {} : { matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE } }),
+ matchExpressions: exclusion,
+ })
+ }
+ expect(
+ emitted.find(p => p.metadata?.name === 'deny-all-mcp-host')?.spec?.podSelector
+ ).toEqual({})
+ expect(
+ emitted.find(p => p.metadata?.name === 'allow-dns-egress-mcp-server')?.spec?.podSelector
+ ).toEqual({})
+ })
it.each([
['deny-all-mcp-server', 'default-deny'],
['allow-dns-egress-mcp-server', 'infrastructure'],
diff --git a/host-context-controller/src/networkPolicyReconciler.ts b/host-context-controller/src/networkPolicyReconciler.ts
index 01c7342de..a38749fee 100644
--- a/host-context-controller/src/networkPolicyReconciler.ts
+++ b/host-context-controller/src/networkPolicyReconciler.ts
@@ -433,7 +433,10 @@ export function isPublicDnsHostname(host: string): boolean {
function hccApiEgressPodSelector(namespace: string): k8s.V1LabelSelector {
if (namespace === config.hostNamespace) {
- return { matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE } }
+ return {
+ matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },
+ matchExpressions: [{ key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] }],
+ }
}
if (namespace === config.namespace) {
return { matchLabels: { app: 'mcp-proxy' } }
@@ -449,7 +452,10 @@ function hccApiEgressPodSelector(namespace: string): k8s.V1LabelSelector {
function k8sApiEgressPodSelector(namespace: string): k8s.V1LabelSelector {
if (namespace === config.hostNamespace) {
- return { matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE } }
+ return {
+ matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },
+ matchExpressions: [{ key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] }],
+ }
}
// Runtime workload namespaces are deny-by-default for apiserver access. A
@@ -723,7 +729,14 @@ export class NetworkPolicyReconciler {
},
},
spec: {
- podSelector: {},
+ podSelector:
+ namespace === config.hostNamespace
+ ? {
+ matchExpressions: [
+ { key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] },
+ ],
+ }
+ : {},
policyTypes: ['Egress'],
egress,
},
diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.json
index 7a702113a..3d9a15dd4 100644
--- a/mcp-host/package-lock.json
+++ b/mcp-host/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.486",
+ "version": "0.1.487",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-mcp-host",
- "version": "0.1.486",
+ "version": "0.1.487",
"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 668c9959f..edc364693 100644
--- a/mcp-host/package.json
+++ b/mcp-host/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-mcp-host",
- "version": "0.1.486",
+ "version": "0.1.487",
"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/execution/receiveSession.test.ts b/mcp-host/src/core/execution/receiveSession.test.ts
new file mode 100644
index 000000000..6f56274cc
--- /dev/null
+++ b/mcp-host/src/core/execution/receiveSession.test.ts
@@ -0,0 +1,322 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { createHash } from 'node:crypto'
+import { mkdtemp, readFile, readdir, rm, stat } from 'node:fs/promises'
+import { type ClientRequest, request as httpRequest } from 'node:http'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+import { EXECUTION_INPUT_MAX_BYTES } from './receiveInput'
+import {
+ EXECUTION_INPUT_CONTENT_TYPE,
+ EXECUTION_INPUT_TIMEOUT_MAX_MS,
+ EXECUTION_INPUT_UID_HEADER,
+ ReceiveSession,
+ ReceiveSessionError,
+ ReceiveSessionOptions,
+ startReceiveSession,
+} from './receiveSession'
+
+const POD_UID = '7f1f0d2c-3a4b-4c5d-8e9f-0a1b2c3d4e5f'
+const OTHER_UID = '22222222-3333-4444-8555-666666666666'
+const BINARY = Buffer.from([0, 1, 2, 0x7f, 0x80, 0xff, 0x0a])
+const DIGEST = createHash('sha256').update(BINARY).digest('hex')
+
+const sessions: ReceiveSession[] = []
+const dirs: string[] = []
+const openRequests: ClientRequest[] = []
+
+afterEach(async () => {
+ for (const request of openRequests.splice(0)) request.destroy()
+ for (const session of sessions.splice(0)) await session.close()
+ for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true })
+})
+
+async function inputDir(): Promise<string> {
+ const dir = await mkdtemp(join(tmpdir(), 'pr932-input-session-'))
+ dirs.push(dir)
+ return dir
+}
+
+async function openSession(
+ overrides: Partial<ReceiveSessionOptions> = {}
+): Promise<ReceiveSession> {
+ const session = await startReceiveSession({
+ bytes: BINARY.length,
+ sha256: DIGEST,
+ timeoutMs: 30_000,
+ podUid: POD_UID,
+ host: '127.0.0.1',
+ port: 0,
+ graceMs: 1_000,
+ ...overrides,
+ })
+ sessions.push(session)
+ return session
+}
+
+const baseUrl = (session: ReceiveSession): string => `http://127.0.0.1:${session.port}`
+
+function uidHeaders(uid?: string | null): Record<string, string> {
+ return uid === null ? {} : { [EXECUTION_INPUT_UID_HEADER]: uid ?? POD_UID }
+}
+
+const post = (session: ReceiveSession, body: Buffer, uid?: string | null): Promise<Response> =>
+ fetch(`${baseUrl(session)}/input`, {
+ method: 'POST',
+ headers: { 'content-type': EXECUTION_INPUT_CONTENT_TYPE, ...uidHeaders(uid) },
+ body: new Uint8Array(body),
+ })
+
+const ready = (session: ReceiveSession, uid?: string | null): Promise<Response> =>
+ fetch(`${baseUrl(session)}/ready`, { headers: uidHeaders(uid) })
+
+async function waitUntil(predicate: () => boolean, timeoutMs = 3_000): Promise<void> {
+ const started = Date.now()
+ while (!predicate()) {
+ if (Date.now() - started > timeoutMs) throw new Error('condition was never met')
+ await new Promise(resolve => setTimeout(resolve, 20))
+ }
+}
+
+async function waitForFile(dir: string): Promise<Buffer> {
+ const target = join(dir, 'source')
+ const started = Date.now()
+ while (Date.now() - started < 2_000) {
+ try {
+ return await readFile(target)
+ } catch {
+ await new Promise(resolve => setTimeout(resolve, 20))
+ }
+ }
+ throw new Error('input file was never published')
+}
+
+/** The session end is observable as a refused connection. */
+async function waitForListenerClose(session: ReceiveSession, timeoutMs = 3_000): Promise<void> {
+ const started = Date.now()
+ for (;;) {
+ try {
+ await fetch(`${baseUrl(session)}/ready`, { headers: uidHeaders() })
+ } catch {
+ return
+ }
+ if (Date.now() - started > timeoutMs) throw new Error('listener never closed')
+ await new Promise(resolve => setTimeout(resolve, 25))
+ }
+}
+
+describe('private execution input session', () => {
+ it('accepts one authorized POST, streams it and publishes the exact file', async () => {
+ const dir = await inputDir()
+ let outcome = ''
+ const session = await openSession({
+ directory: dir,
+ onSettled: settled => {
+ outcome = settled
+ },
+ })
+
+ expect((await ready(session)).status).toBe(204)
+ const response = await post(session, BINARY)
+ expect(response.status).toBe(204)
+ expect(await response.text()).toBe('')
+ expect(response.headers.get(EXECUTION_INPUT_UID_HEADER)).toBe(POD_UID)
+
+ await waitUntil(() => outcome === 'received')
+ expect(await waitForFile(dir)).toEqual(BINARY)
+ expect((await stat(join(dir, 'source'))).mode & 0o777).toBe(0o444)
+ expect(await readdir(dir)).toEqual(['source'])
+ })
+
+ it('never writes input bytes to the launcher streams', async () => {
+ const dir = await inputDir()
+ const writes: string[] = []
+ const intercept = () =>
+ ((chunk: unknown) => {
+ writes.push(String(chunk))
+ return true
+ }) as unknown as typeof process.stdout.write
+ const originalOut = process.stdout.write
+ const originalErr = process.stderr.write
+ process.stdout.write = intercept()
+ process.stderr.write = intercept()
+ try {
+ const session = await openSession({ directory: dir })
+ expect((await post(session, BINARY)).status).toBe(204)
+ await waitForFile(dir)
+ } finally {
+ process.stdout.write = originalOut
+ process.stderr.write = originalErr
+ }
+ expect(writes).toEqual([])
+ })
+
+ it('serves readiness only to the exact Pod UID', async () => {
+ const session = await openSession()
+
+ const accepted = await ready(session)
+ expect(accepted.status).toBe(204)
+ expect(await accepted.text()).toBe('')
+ expect(accepted.headers.get(EXECUTION_INPUT_UID_HEADER)).toBe(POD_UID)
+
+ for (const uid of [null, OTHER_UID, '']) {
+ const denied = await ready(session, uid)
+ expect(denied.status).toBe(404)
+ expect(await denied.text()).toBe('')
+ expect(denied.headers.get(EXECUTION_INPUT_UID_HEADER)).toBeNull()
+ }
+ })
+
+ it('ignores a foreign UID without a file and without consuming the session', async () => {
+ const dir = await inputDir()
+ const session = await openSession({ directory: dir })
+
+ const foreign = await post(session, BINARY, OTHER_UID)
+ expect(foreign.status).toBe(404)
+ expect(await foreign.text()).toBe('')
+ expect(foreign.headers.get(EXECUTION_INPUT_UID_HEADER)).toBeNull()
+ expect(await readdir(dir)).toEqual([])
+
+ // The authorized sender still delivers exactly once.
+ expect((await post(session, BINARY)).status).toBe(204)
+ expect(await waitForFile(dir)).toEqual(BINARY)
+ })
+
+ it('rejects wrong length or digest with a fixed empty 400 and no file', async () => {
+ const cases: Array<[Buffer, string]> = [
+ [Buffer.concat([BINARY, Buffer.from([1])]), DIGEST],
+ [BINARY.subarray(0, BINARY.length - 1), DIGEST],
+ [BINARY, createHash('sha256').update('other bytes').digest('hex')],
+ ]
+ for (const [body, sha256] of cases) {
+ const dir = await inputDir()
+ let outcome = ''
+ const session = await openSession({
+ directory: dir,
+ sha256,
+ onSettled: settled => {
+ outcome = settled
+ },
+ })
+
+ const response = await post(session, body)
+ expect(response.status).toBe(400)
+ expect(await response.text()).toBe('')
+ await waitUntil(() => outcome === 'rejected')
+ expect(await readdir(dir)).toEqual([])
+
+ // The consumed context rejects a replay instead of re-running anything.
+ const replay = await post(session, BINARY)
+ expect(replay.status).toBe(409)
+ expect(await replay.text()).toBe('')
+ await expect(ready(session)).resolves.toMatchObject({ status: 404 })
+ expect(await readdir(dir)).toEqual([])
+ }
+ })
+
+ it('rejects a wrong content type once and consumes the session', async () => {
+ const dir = await inputDir()
+ const session = await openSession({ directory: dir })
+
+ const wrongType = await fetch(`${baseUrl(session)}/input`, {
+ method: 'POST',
+ headers: { 'content-type': 'text/plain', ...uidHeaders() },
+ body: BINARY,
+ })
+ expect(wrongType.status).toBe(415)
+ expect(await wrongType.text()).toBe('')
+ expect(await readdir(dir)).toEqual([])
+
+ expect((await post(session, BINARY)).status).toBe(409)
+ expect(await readdir(dir)).toEqual([])
+ })
+
+ it('ends a stalled transfer at the finite deadline and publishes no file', async () => {
+ const dir = await inputDir()
+ let outcome = ''
+ const session = await openSession({
+ directory: dir,
+ timeoutMs: 200,
+ graceMs: 200,
+ onSettled: settled => {
+ outcome = settled
+ },
+ })
+
+ const stalled = httpRequest({
+ host: '127.0.0.1',
+ port: session.port,
+ path: '/input',
+ method: 'POST',
+ headers: {
+ 'content-type': EXECUTION_INPUT_CONTENT_TYPE,
+ [EXECUTION_INPUT_UID_HEADER]: POD_UID,
+ },
+ })
+ openRequests.push(stalled)
+ stalled.on('error', () => {})
+ stalled.write(BINARY.subarray(0, 3))
+ await waitUntil(() => outcome === 'rejected')
+
+ expect(await readdir(dir)).toEqual([])
+ await waitForListenerClose(session)
+ })
+
+ it('ends an idle session at the finite deadline', async () => {
+ let outcome = ''
+ const session = await openSession({
+ timeoutMs: 150,
+ graceMs: 150,
+ onSettled: settled => {
+ outcome = settled
+ },
+ })
+
+ expect((await ready(session)).status).toBe(204)
+ await waitUntil(() => outcome === 'rejected')
+ await waitForListenerClose(session)
+ })
+
+ it('rejects an invalid session contract without reserving a listener', async () => {
+ let received = 0
+ const invalid: Array<Partial<ReceiveSessionOptions>> = [
+ { podUid: 'not-a-pod-uid' },
+ { podUid: '' },
+ { podUid: POD_UID.toUpperCase() },
+ { bytes: -1 },
+ { bytes: 1.5 },
+ { bytes: EXECUTION_INPUT_MAX_BYTES + 1 },
+ { sha256: 'A'.repeat(64) },
+ { sha256: 'a'.repeat(63) },
+ { sha256: 'z'.repeat(64) },
+ { timeoutMs: 0 },
+ { timeoutMs: 1.5 },
+ { timeoutMs: Number.NaN },
+ { timeoutMs: EXECUTION_INPUT_TIMEOUT_MAX_MS + 1 },
+ { graceMs: -1 },
+ { directory: '' },
+ ]
+ for (const override of invalid) {
+ const error = await startReceiveSession({
+ bytes: BINARY.length,
+ sha256: DIGEST,
+ timeoutMs: 1_000,
+ podUid: POD_UID,
+ host: '127.0.0.1',
+ port: 0,
+ receive: async () => {
+ received += 1
+ },
+ ...override,
+ }).then(
+ async session => {
+ await session.close()
+ return null
+ },
+ (failure: unknown) => failure
+ )
+ expect(error).toBeInstanceOf(ReceiveSessionError)
+ expect((error as ReceiveSessionError).code).toBe('invalid_session_contract')
+ }
+ expect(received).toBe(0)
+ })
+})
diff --git a/mcp-host/src/core/execution/receiveSession.ts b/mcp-host/src/core/execution/receiveSession.ts
new file mode 100644
index 000000000..7bdd4ec75
--- /dev/null
+++ b/mcp-host/src/core/execution/receiveSession.ts
@@ -0,0 +1,225 @@
+import { type IncomingMessage, type ServerResponse, createServer } from 'node:http'
+import { EXECUTION_INPUT_MAX_BYTES, receiveExecutionInput } from './receiveInput'
+
+/** Fixed in-Pod port for the private input session (the result session uses 9300). */
+export const EXECUTION_INPUT_PORT = 9301
+/** Downward-API variable carrying the real Pod UID of this Job Pod. */
+export const EXECUTION_POD_UID_ENV = 'EXECUTION_POD_UID'
+/** Exact UID header; the same Downward-API gate the result session uses. */
+export const EXECUTION_INPUT_UID_HEADER = 'x-execution-pod-uid'
+/** Fixed private directory the trusted receiver writes. */
+export const EXECUTION_INPUT_DIRECTORY = '/input'
+export const EXECUTION_INPUT_CONTENT_TYPE = 'application/octet-stream'
+/** Mirrors the receiver's own stream-deadline ceiling for CLI validation. */
+export const EXECUTION_INPUT_TIMEOUT_MAX_MS = 1_500_000
+/** Total session life after the input deadline. */
+export const EXECUTION_INPUT_GRACE_MS = 60_000
+
+export type ReceiveSessionOutcome = 'received' | 'rejected'
+export type ReceiveSessionErrorCode = 'invalid_session_contract' | 'session_bind_failed'
+
+export class ReceiveSessionError extends Error {
+ constructor(readonly code: ReceiveSessionErrorCode) {
+ super(code)
+ this.name = 'ReceiveSessionError'
+ }
+}
+
+export interface ReceiveSessionOptions {
+ bytes: number
+ sha256: string
+ timeoutMs: number
+ podUid: string
+ /** Tests write to a temporary directory; the Pod uses the fixed /input. */
+ directory?: string
+ host?: string
+ port?: number
+ graceMs?: number
+ /** Injectable for tests only; production always uses the receiver. */
+ receive?: typeof receiveExecutionInput
+ /** Called once with the final outcome, after the response is flushed. */
+ onSettled?: (outcome: ReceiveSessionOutcome) => void
+}
+
+export interface ReceiveSession {
+ readonly port: number
+ close(): Promise<void>
+}
+
+const POD_UID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
+const SHA256_PATTERN = /^[0-9a-f]{64}$/
+
+function invalidContract(options: ReceiveSessionOptions): boolean {
+ const graceMs = options.graceMs ?? EXECUTION_INPUT_GRACE_MS
+ return (
+ !POD_UID_PATTERN.test(options.podUid) ||
+ !Number.isSafeInteger(options.bytes) ||
+ options.bytes < 0 ||
+ options.bytes > EXECUTION_INPUT_MAX_BYTES ||
+ typeof options.sha256 !== 'string' ||
+ !SHA256_PATTERN.test(options.sha256) ||
+ !Number.isSafeInteger(options.timeoutMs) ||
+ options.timeoutMs <= 0 ||
+ options.timeoutMs > EXECUTION_INPUT_TIMEOUT_MAX_MS ||
+ !Number.isSafeInteger(graceMs) ||
+ graceMs < 0 ||
+ typeof (options.directory ?? EXECUTION_INPUT_DIRECTORY) !== 'string' ||
+ (options.directory ?? EXECUTION_INPUT_DIRECTORY).length === 0
+ )
+}
+
+/**
+ * Private input session for one approved operation. The listener is reserved
+ * before a single `POST /input` is accepted, the body is streamed straight into
+ * the trusted receiver (never buffered whole, never logged), and the CLI exits
+ * only after the response is flushed — that exit is what lets Kubernetes start
+ * the executor. The Pod UID header stops an IP-reuse or bystander caller; the
+ * real authority stays with HCC admission and the network policy.
+ */
+export async function startReceiveSession(options: ReceiveSessionOptions): Promise<ReceiveSession> {
+ if (invalidContract(options)) throw new ReceiveSessionError('invalid_session_contract')
+ const {
+ bytes,
+ sha256,
+ timeoutMs,
+ podUid,
+ directory = EXECUTION_INPUT_DIRECTORY,
+ host = '0.0.0.0',
+ port = EXECUTION_INPUT_PORT,
+ graceMs = EXECUTION_INPUT_GRACE_MS,
+ receive = receiveExecutionInput,
+ onSettled,
+ } = options
+
+ let state: 'idle' | 'receiving' | 'received' | 'failed' = 'idle'
+ let settled = false
+ let deadline: NodeJS.Timeout | undefined
+ let closing: Promise<void> | undefined
+
+ const settle = (outcome: ReceiveSessionOutcome): void => {
+ if (settled) return
+ settled = true
+ onSettled?.(outcome)
+ }
+ const authorized = (req: IncomingMessage): boolean =>
+ req.headers[EXECUTION_INPUT_UID_HEADER] === podUid
+ const reply = (res: ServerResponse, status: number): void => {
+ res.statusCode = status
+ res.setHeader(EXECUTION_INPUT_UID_HEADER, podUid)
+ res.setHeader('cache-control', 'no-store')
+ res.end()
+ }
+ // A caller without the exact Pod UID gets no body, no state change and no echo.
+ const deny = (req: IncomingMessage, res: ServerResponse): void => {
+ // Drain any body so a denied caller cannot reset the connection.
+ req.resume()
+ res.statusCode = 404
+ res.end()
+ }
+
+ const server = createServer((req, res) => {
+ if (!authorized(req)) {
+ deny(req, res)
+ return
+ }
+ if (req.method === 'GET' && req.url === '/ready') {
+ if (state === 'received' || state === 'failed') {
+ deny(req, res)
+ return
+ }
+ reply(res, 204)
+ return
+ }
+ if (req.method === 'POST' && req.url === '/input') {
+ // The single POST context is consumed by the first accepted attempt; a
+ // replay never re-runs the receiver and never replaces a published file.
+ if (state !== 'idle') {
+ req.resume()
+ reply(res, 409)
+ return
+ }
+ if (req.headers['content-type'] !== EXECUTION_INPUT_CONTENT_TYPE) {
+ state = 'failed'
+ req.resume()
+ res.once('finish', () => settle('rejected'))
+ reply(res, 415)
+ return
+ }
+ state = 'receiving'
+ receive(req, directory, bytes, sha256, timeoutMs).then(
+ () => {
+ state = 'received'
+ res.once('finish', () => settle('received'))
+ reply(res, 204)
+ },
+ () => {
+ state = 'failed'
+ // Fixed empty rejection: never the reason, the bytes or the digest.
+ res.once('finish', () => settle('rejected'))
+ reply(res, 400)
+ }
+ )
+ return
+ }
+ deny(req, res)
+ })
+ server.headersTimeout = 5_000
+ server.requestTimeout = 10_000
+ server.keepAliveTimeout = 1_000
+ server.maxConnections = 8
+
+ try {
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(port, host, () => {
+ server.off('error', reject)
+ resolve()
+ })
+ })
+ } catch {
+ throw new ReceiveSessionError('session_bind_failed')
+ }
+
+ const address = server.address()
+ const boundPort = typeof address === 'object' && address !== null ? address.port : port
+
+ async function close(): Promise<void> {
+ if (closing) return closing
+ if (deadline) clearTimeout(deadline)
+ closing = new Promise<void>(resolve => server.close(() => resolve()))
+ // A stalled transfer holds a non-idle socket; drop it rather than wait.
+ server.closeAllConnections()
+ return closing
+ }
+
+ deadline = setTimeout(() => {
+ // Finite life: a peer that stalls mid-transfer still ends the session.
+ // The library only closes; the CLI owns the PID1 exit.
+ void close()
+ settle('rejected')
+ }, timeoutMs + graceMs)
+
+ return { port: boundPort, close }
+}
+
+if (require.main === module) {
+ // CLI: <bytes> <sha256> <timeoutMs>. Nothing is printed: the input arrives
+ // over the private listener; UID guards IP reuse, not caller authority.
+ const podUid = process.env[EXECUTION_POD_UID_ENV] ?? ''
+ const [rawBytes, rawSha256, rawTimeoutMs] = process.argv.slice(2)
+ if (
+ !/^\d+$/.test(rawBytes ?? '') ||
+ !/^[0-9a-f]{64}$/.test(rawSha256 ?? '') ||
+ !/^\d+$/.test(rawTimeoutMs ?? '')
+ ) {
+ process.exit(1)
+ }
+ startReceiveSession({
+ bytes: Number(rawBytes),
+ sha256: rawSha256,
+ timeoutMs: Number(rawTimeoutMs),
+ podUid,
+ // Exit 0 only after a flushed 204: Kubernetes starts the executor then.
+ onSettled: outcome => process.exit(outcome === 'received' ? 0 : 1),
+ }).catch(() => process.exit(1))
+}
diff --git a/mcp-host/src/core/execution/runSession.test.ts b/mcp-host/src/core/execution/runSession.test.ts
new file mode 100644
index 000000000..6a885678c
--- /dev/null
+++ b/mcp-host/src/core/execution/runSession.test.ts
@@ -0,0 +1,310 @@
+import { afterEach, describe, expect, it } from 'vitest'
+import { once } from 'node:events'
+import { createServer } from 'node:http'
+import { connect } from 'node:net'
+import { type ExecutionResult, MAX_EXECUTION_TIMEOUT_MS } from './runExecution'
+import {
+ EXECUTION_RESULT_MAX_BYTES,
+ EXECUTION_RESULT_UID_HEADER,
+ ExecutionSession,
+ ExecutionSessionError,
+ ExecutionSessionOptions,
+ startExecutionSession,
+} from './runSession'
+
+const POD_UID = '6f1f0d2c-3a4b-4c5d-8e9f-0a1b2c3d4e5f'
+const OTHER_UID = '11111111-2222-4333-8444-555555555555'
+const BINARY = Buffer.from([0, 1, 2, 0x7f, 0x80, 0xff])
+
+const sampleResult: ExecutionResult = {
+ reason: 'exited',
+ exitCode: 0,
+ signal: null,
+ truncated: false,
+ stdout: BINARY.toString('base64'),
+ stderr: Buffer.from('stderr-bytes').toString('base64'),
+}
+
+const sessions: ExecutionSession[] = []
+afterEach(async () => {
+ for (const session of sessions.splice(0)) await session.close()
+})
+
+async function openSession(
+ overrides: Partial<ExecutionSessionOptions> = {}
+): Promise<ExecutionSession> {
+ const session = await startExecutionSession({
+ timeoutMs: 30_000,
+ argv: ['/bin/true'],
+ podUid: POD_UID,
+ host: '127.0.0.1',
+ port: 0,
+ graceMs: 1_000,
+ run: async () => sampleResult,
+ ...overrides,
+ })
+ sessions.push(session)
+ return session
+}
+
+const resultUrl = (session: ExecutionSession): string => `http://127.0.0.1:${session.port}/result`
+
+function headersFor(uid?: string | null): Record<string, string> {
+ return uid === null ? {} : { [EXECUTION_RESULT_UID_HEADER]: uid ?? POD_UID }
+}
+
+const get = (session: ExecutionSession, uid?: string | null): Promise<Response> =>
+ fetch(resultUrl(session), { headers: headersFor(uid) })
+
+const del = (session: ExecutionSession, uid?: string | null): Promise<Response> =>
+ fetch(resultUrl(session), { method: 'DELETE', headers: headersFor(uid) })
+
+async function waitForResult(session: ExecutionSession): Promise<Response> {
+ for (let attempt = 0; attempt < 80; attempt += 1) {
+ const response = await get(session)
+ if (response.status !== 425) return response
+ await new Promise(resolve => setTimeout(resolve, 25))
+ }
+ throw new Error('result was never published')
+}
+
+async function waitUntil(predicate: () => boolean, timeoutMs = 3_000): Promise<void> {
+ const started = Date.now()
+ while (!predicate()) {
+ if (Date.now() - started > timeoutMs) throw new Error('condition was never met')
+ await new Promise(resolve => setTimeout(resolve, 20))
+ }
+}
+
+describe('private execution result session', () => {
+ it('answers 425 while running and then one bounded frame for the exact Pod UID', async () => {
+ let release!: (result: ExecutionResult) => void
+ const session = await openSession({
+ run: () =>
+ new Promise<ExecutionResult>(resolve => {
+ release = resolve
+ }),
+ })
+
+ const early = await get(session)
+ expect(early.status).toBe(425)
+ expect(await early.text()).toBe('')
+ expect(early.headers.get(EXECUTION_RESULT_UID_HEADER)).toBe(POD_UID)
+
+ release(sampleResult)
+ const ready = await waitForResult(session)
+ expect(ready.status).toBe(200)
+ expect(ready.headers.get('content-type')).toBe('application/json')
+ expect(ready.headers.get(EXECUTION_RESULT_UID_HEADER)).toBe(POD_UID)
+ const body = await ready.text()
+ expect(Buffer.byteLength(body)).toBeLessThanOrEqual(EXECUTION_RESULT_MAX_BYTES)
+ const parsed = JSON.parse(body) as ExecutionResult
+ expect(parsed).toEqual(sampleResult)
+ expect(Buffer.from(parsed.stdout, 'base64')).toEqual(BINARY)
+ expect(Buffer.from(parsed.stderr, 'base64').toString('utf8')).toBe('stderr-bytes')
+
+ const again = await get(session)
+ expect(again.status).toBe(200)
+ expect(await again.text()).toBe(body)
+ })
+
+ it('serves nothing to a missing or foreign Pod UID', async () => {
+ const session = await openSession()
+ await waitForResult(session)
+
+ for (const uid of [null, OTHER_UID, '']) {
+ const response = await get(session, uid)
+ expect(response.status).toBe(404)
+ expect(await response.text()).toBe('')
+ expect(response.headers.get(EXECUTION_RESULT_UID_HEADER)).toBeNull()
+ }
+
+ const deniedDelete = await del(session, OTHER_UID)
+ expect(deniedDelete.status).toBe(404)
+ expect(await deniedDelete.text()).toBe('')
+ // A rejected DELETE must not clear the frame or close the listener.
+ expect((await get(session)).status).toBe(200)
+ })
+
+ it('reserves the listener before the approved command starts', async () => {
+ const probe = createServer()
+ await new Promise<void>(resolve => probe.listen(0, '127.0.0.1', () => resolve()))
+ const address = probe.address()
+ const port = typeof address === 'object' && address !== null ? address.port : 0
+ await new Promise<void>(resolve => probe.close(() => resolve()))
+
+ let observed = 0
+ const session = await openSession({
+ port,
+ run: async () => {
+ const response = await fetch(`http://127.0.0.1:${port}/result`, {
+ headers: { [EXECUTION_RESULT_UID_HEADER]: POD_UID },
+ })
+ observed = response.status
+ await response.text()
+ return sampleResult
+ },
+ })
+
+ expect((await waitForResult(session)).status).toBe(200)
+ expect(observed).toBe(425)
+ })
+
+ it('clears the frame and closes the listener after an authorized DELETE', async () => {
+ let closedCalls = 0
+ const session = await openSession({
+ onClosed: () => {
+ closedCalls += 1
+ },
+ })
+ await waitForResult(session)
+
+ const response = await del(session)
+ expect(response.status).toBe(204)
+ expect(await response.text()).toBe('')
+ expect(response.headers.get(EXECUTION_RESULT_UID_HEADER)).toBe(POD_UID)
+
+ await waitUntil(() => closedCalls === 1)
+ await expect(fetch(resultUrl(session))).rejects.toThrow()
+ })
+
+ it('ends the finite session when the executor never settles', async () => {
+ let closedCalls = 0
+ const session = await openSession({
+ timeoutMs: 150,
+ graceMs: 150,
+ run: () => new Promise<ExecutionResult>(() => {}),
+ onClosed: () => {
+ closedCalls += 1
+ },
+ })
+
+ expect((await get(session)).status).toBe(425)
+ await waitUntil(() => closedCalls === 1)
+ await expect(fetch(resultUrl(session))).rejects.toThrow()
+ })
+
+ it('closes an incomplete request and notifies once instead of waiting on its socket', async () => {
+ let closedCalls = 0
+ const session = await openSession({
+ onClosed: () => {
+ closedCalls += 1
+ },
+ })
+ const socket = connect({ host: '127.0.0.1', port: session.port })
+ let failure: string | undefined
+ socket.on('error', error => {
+ failure = (error as NodeJS.ErrnoException).code
+ })
+ try {
+ await once(socket, 'connect')
+ socket.write('GET /result HTTP/1.1\r\nHost: local\r\n')
+ const gone = new Promise<void>(resolve => socket.once('close', () => resolve()))
+ await Promise.all([session.close(), session.close(), gone])
+ expect(closedCalls).toBe(1)
+ expect(socket.destroyed).toBe(true)
+ expect(failure === undefined || failure === 'ECONNRESET').toBe(true)
+ } finally {
+ socket.destroy()
+ }
+ })
+
+ it('rejects an invalid session contract without reserving a listener', async () => {
+ let ran = 0
+ const invalid: Array<Partial<ExecutionSessionOptions>> = [
+ { podUid: 'not-a-pod-uid' },
+ { podUid: '' },
+ { podUid: POD_UID.toUpperCase() },
+ { timeoutMs: 0 },
+ { timeoutMs: 1.5 },
+ { timeoutMs: Number.NaN },
+ { timeoutMs: MAX_EXECUTION_TIMEOUT_MS + 1 },
+ { argv: [] },
+ { argv: [''] },
+ { argv: ['x\0y'] },
+ { graceMs: -1 },
+ ]
+ for (const override of invalid) {
+ const error = await startExecutionSession({
+ timeoutMs: 1_000,
+ argv: ['/bin/true'],
+ podUid: POD_UID,
+ host: '127.0.0.1',
+ port: 0,
+ run: async () => {
+ ran += 1
+ return sampleResult
+ },
+ ...override,
+ }).then(
+ async session => {
+ await session.close()
+ return null
+ },
+ (failure: unknown) => failure
+ )
+ expect(error).toBeInstanceOf(ExecutionSessionError)
+ expect((error as ExecutionSessionError).code).toBe('invalid_session_contract')
+ }
+ expect(ran).toBe(0)
+ })
+
+ it('fails closed instead of sending an oversized frame', async () => {
+ const session = await openSession({
+ run: async () => ({ ...sampleResult, stdout: 'A'.repeat(200_000) }),
+ })
+
+ const response = await waitForResult(session)
+ expect(response.status).toBe(500)
+ expect(await response.text()).toBe('')
+ expect(response.headers.get(EXECUTION_RESULT_UID_HEADER)).toBe(POD_UID)
+ })
+
+ it('never writes result bytes to the launcher streams', async () => {
+ const writes: string[] = []
+ const intercept = () =>
+ ((chunk: unknown) => {
+ writes.push(String(chunk))
+ return true
+ }) as unknown as typeof process.stdout.write
+ const originalOut = process.stdout.write
+ const originalErr = process.stderr.write
+ process.stdout.write = intercept()
+ process.stderr.write = intercept()
+ try {
+ const session = await openSession()
+ expect((await waitForResult(session)).status).toBe(200)
+ await (await del(session)).text()
+ } finally {
+ process.stdout.write = originalOut
+ process.stderr.write = originalErr
+ }
+ expect(writes).toEqual([])
+ })
+
+ it('serves the real execution result of a local fixture', async () => {
+ // The fixture self-terminates through its watchdog; runExecution does not
+ // expose the child PID, so no PID is retained by this suite.
+ const session = await openSession({
+ argv: [
+ process.execPath,
+ '-e',
+ 'setTimeout(() => process.exit(9), 30_000); ' +
+ "process.stdout.write(Buffer.from([1, 2, 255])); process.stderr.write('e'); process.exit(3)",
+ ],
+ run: undefined,
+ })
+
+ const response = await waitForResult(session)
+ expect(response.status).toBe(200)
+ const parsed = JSON.parse(await response.text()) as ExecutionResult
+ expect(parsed).toMatchObject({
+ reason: 'exited',
+ exitCode: 3,
+ signal: null,
+ truncated: false,
+ })
+ expect([...Buffer.from(parsed.stdout, 'base64')]).toEqual([1, 2, 255])
+ expect(Buffer.from(parsed.stderr, 'base64').toString('utf8')).toBe('e')
+ })
+})
diff --git a/mcp-host/src/core/execution/runSession.ts b/mcp-host/src/core/execution/runSession.ts
new file mode 100644
index 000000000..e026de3d1
--- /dev/null
+++ b/mcp-host/src/core/execution/runSession.ts
@@ -0,0 +1,221 @@
+import { type IncomingMessage, type ServerResponse, createServer } from 'node:http'
+import { type ExecutionResult, MAX_EXECUTION_TIMEOUT_MS, runExecution } from './runExecution'
+
+/** Fixed in-Pod port for the private result session. */
+export const EXECUTION_RESULT_PORT = 9300
+/** Downward-API variable carrying the real Pod UID of this Job Pod. */
+export const EXECUTION_POD_UID_ENV = 'EXECUTION_POD_UID'
+/** Exact UID header required on every result request and echoed on replies. */
+export const EXECUTION_RESULT_UID_HEADER = 'x-execution-pod-uid'
+/** One bounded result frame; the captured base64 output fits with headroom. */
+export const EXECUTION_RESULT_MAX_BYTES = 96 * 1024
+/** Total session life after the execution deadline. */
+export const EXECUTION_SESSION_GRACE_MS = 60_000
+
+export type ExecutionSessionErrorCode = 'invalid_session_contract' | 'session_bind_failed'
+
+export class ExecutionSessionError extends Error {
+ constructor(readonly code: ExecutionSessionErrorCode) {
+ super(code)
+ this.name = 'ExecutionSessionError'
+ }
+}
+
+export interface ExecutionSessionOptions {
+ timeoutMs: number
+ argv: string[]
+ podUid: string
+ /** Tests bind loopback and port 0; the Pod uses the fixed port. */
+ host?: string
+ port?: number
+ graceMs?: number
+ /** Injectable for tests only; production always uses runExecution. */
+ run?: (timeoutMs: number, argv: string[]) => Promise<ExecutionResult>
+ /** Called once the session can no longer serve a result. */
+ onClosed?: () => void
+}
+
+export interface ExecutionSession {
+ readonly port: number
+ close(): Promise<void>
+}
+
+const POD_UID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
+
+function invalidContract(options: ExecutionSessionOptions): boolean {
+ return (
+ !POD_UID_PATTERN.test(options.podUid) ||
+ !Number.isSafeInteger(options.timeoutMs) ||
+ options.timeoutMs <= 0 ||
+ options.timeoutMs > MAX_EXECUTION_TIMEOUT_MS ||
+ !Number.isSafeInteger(options.graceMs ?? EXECUTION_SESSION_GRACE_MS) ||
+ (options.graceMs ?? EXECUTION_SESSION_GRACE_MS) < 0 ||
+ !Array.isArray(options.argv) ||
+ options.argv.length === 0 ||
+ typeof options.argv[0] !== 'string' ||
+ options.argv[0].length === 0 ||
+ options.argv.some(argument => typeof argument !== 'string' || argument.includes('\0'))
+ )
+}
+
+/**
+ * Private result session for one approved operation. The listener is reserved
+ * before the command starts, serves exactly one bounded result frame to a
+ * HCC over its private network lane. The UID prevents Pod-IP reuse; it is not
+ * user authorization. HCC must separately validate the signed caller and the
+ * original operation binding. Nothing is written to stdout, stderr or logs.
+ *
+ * A successful DELETE closes the session. Verified Pod runtime termination is
+ * the physical cleanup boundary; HTTP or API absence alone does not prove it.
+ */
+export async function startExecutionSession(
+ options: ExecutionSessionOptions
+): Promise<ExecutionSession> {
+ if (invalidContract(options)) throw new ExecutionSessionError('invalid_session_contract')
+ const {
+ timeoutMs,
+ argv,
+ podUid,
+ host = '0.0.0.0',
+ port = EXECUTION_RESULT_PORT,
+ graceMs = EXECUTION_SESSION_GRACE_MS,
+ run = runExecution,
+ onClosed,
+ } = options
+
+ let state: 'running' | 'ready' | 'failed' = 'running'
+ let frame: string | null = null
+ let closed = false
+ let deadline: NodeJS.Timeout | undefined
+ let closing: Promise<void> | undefined
+
+ const authorized = (req: IncomingMessage): boolean =>
+ req.headers[EXECUTION_RESULT_UID_HEADER] === podUid
+ const reply = (res: ServerResponse, status: number, body?: string): void => {
+ res.statusCode = status
+ res.setHeader(EXECUTION_RESULT_UID_HEADER, podUid)
+ res.setHeader('cache-control', 'no-store')
+ if (body === undefined) {
+ res.end()
+ return
+ }
+ res.setHeader('content-type', 'application/json')
+ res.setHeader('content-length', String(Buffer.byteLength(body)))
+ res.end(body)
+ }
+ // A caller without the exact Pod UID gets no body, no result and no UID echo.
+ const deny = (res: ServerResponse): void => {
+ res.statusCode = 404
+ res.end()
+ }
+
+ const server = createServer((req, res) => {
+ if (req.url !== '/result') {
+ deny(res)
+ return
+ }
+ if (!authorized(req)) {
+ deny(res)
+ return
+ }
+ if (req.method === 'GET') {
+ if (state === 'running') {
+ reply(res, 425)
+ return
+ }
+ if (
+ state === 'failed' ||
+ frame === null ||
+ Buffer.byteLength(frame) > EXECUTION_RESULT_MAX_BYTES
+ ) {
+ reply(res, 500)
+ return
+ }
+ reply(res, 200, frame)
+ return
+ }
+ if (req.method === 'DELETE') {
+ frame = null
+ reply(res, 204)
+ // The caller reads the empty acknowledgement first; then the listener and
+ // the PID1 lifetime end.
+ res.on('finish', () => {
+ void close()
+ })
+ return
+ }
+ deny(res)
+ })
+ server.headersTimeout = 5_000
+ server.requestTimeout = 10_000
+ server.keepAliveTimeout = 1_000
+ server.maxConnections = 8
+
+ try {
+ await new Promise<void>((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(port, host, () => {
+ server.off('error', reject)
+ resolve()
+ })
+ })
+ } catch {
+ throw new ExecutionSessionError('session_bind_failed')
+ }
+
+ const address = server.address()
+ const boundPort = typeof address === 'object' && address !== null ? address.port : port
+
+ async function close(): Promise<void> {
+ if (closing) return closing
+ closed = true
+ if (deadline) clearTimeout(deadline)
+ frame = null
+ // Revocation must not wait indefinitely on a partial request or an active
+ // download. The acknowledgement is already finished before DELETE calls
+ // this path; outstanding result streams are invalidated by closure.
+ closing = new Promise<void>(resolve => server.close(() => resolve())).then(() => {
+ onClosed?.()
+ })
+ server.closeAllConnections()
+ return closing
+ }
+
+ deadline = setTimeout(() => {
+ // Finite life: the executor may never settle, so the session ends anyway.
+ // The library only closes; the CLI owns the PID1 exit.
+ void close()
+ }, timeoutMs + graceMs)
+
+ // The listener is already reserved; the approved command starts only now.
+ run(timeoutMs, argv).then(
+ result => {
+ if (closed) return
+ frame = JSON.stringify(result)
+ state = 'ready'
+ },
+ () => {
+ if (closed) return
+ state = 'failed'
+ }
+ )
+
+ return { port: boundPort, close }
+}
+
+if (require.main === module) {
+ // CLI: <timeoutMs> <exe> [...args]. Nothing is printed: the result is served
+ // over the private listener; network policy and HCC own caller authority.
+ const podUid = process.env[EXECUTION_POD_UID_ENV] ?? ''
+ const [rawTimeoutMs, ...approvedArgv] = process.argv.slice(2)
+ const timeoutMs = Number(rawTimeoutMs)
+ if (!/^\d+$/.test(rawTimeoutMs ?? '')) process.exit(1)
+ startExecutionSession({
+ timeoutMs,
+ argv: approvedArgv,
+ podUid,
+ // The Pod is PID1 here: a served DELETE or the finite session deadline ends
+ // it. The closed listener is not by itself proof of cleanup.
+ onClosed: () => process.exit(0),
+ }).catch(() => process.exit(1))
+}