Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
revert: remove the separate-Pod Host execution scaffolding
Alfredo Lopeza695e5b1611d
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex ff69417b7..33f2df8e4 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.712",+ "version": "0.1.713","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.712",+ "version": "0.1.713","dependencies": {"@clerum/display-field": "file:../packages/display-field","@clerum/grok-provider-attempt-contract": "file:../packages/grok-provider-attempt-contract",diff --git a/control-api/package.json b/control-api/package.jsonindex 7488e270c..0a60f5958 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.712",+ "version": "0.1.713","description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets","main": "dist/main.js","engines": {diff --git a/control-api/src/utils/auth/mcpHostJwtToken.ts b/control-api/src/utils/auth/mcpHostJwtToken.tsindex 168c55c77..052460ee1 100644--- a/control-api/src/utils/auth/mcpHostJwtToken.ts+++ b/control-api/src/utils/auth/mcpHostJwtToken.ts@@ -182,9 +182,6 @@ export const ALL_MCP_HOST_CONTROL_SCOPES = [// eligible broker target. Never add it to user-declarable Host/Recipe CRD fields.'llm:codex:execute','llm:grok:execute',- // Internal native-tool transport. Only HCC's Host-bound access lineage may- // use this at the execution gateway; it adds no attachment/user approval.- 'host:tools:execute',] as constexport type McpHostControlScope = (typeof ALL_MCP_HOST_CONTROL_SCOPES)[number]diff --git a/deploy/base/control-plane/networkpolicies.yaml b/deploy/base/control-plane/networkpolicies.yamlindex 7e2c499a6..b51a1dc6c 100644--- a/deploy/base/control-plane/networkpolicies.yaml+++ b/deploy/base/control-plane/networkpolicies.yaml@@ -999,34 +999,3 @@ spec:- ipBlock:cidr: 0.0.0.0/0except: []------# 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: TCPdiff --git a/deploy/base/mcp-host/networkpolicies.yaml b/deploy/base/mcp-host/networkpolicies.yamlindex 9d561e0ce..c3bf4c687 100644--- a/deploy/base/mcp-host/networkpolicies.yaml+++ b/deploy/base/mcp-host/networkpolicies.yaml@@ -27,10 +27,6 @@ spec:podSelector:matchLabels:clerum.io/managed-by: host-context-controller- matchExpressions:- - key: clerum.io/role- operator: NotIn- values: [host-execution]policyTypes:- Egressegress:@@ -54,10 +50,6 @@ spec:podSelector:matchLabels:clerum.io/managed-by: host-context-controller- matchExpressions:- - key: clerum.io/role- operator: NotIn- values: [host-execution]policyTypes:- Ingress- Egress@@ -150,10 +142,6 @@ spec:podSelector:matchLabels:clerum.io/managed-by: host-context-controller- matchExpressions:- - key: clerum.io/role- operator: NotIn- values: [host-execution]policyTypes:- Egressegress:@@ -165,36 +153,3 @@ spec:protocol: TCP- port: 8443protocol: 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.jsonindex 363072972..ad07e3807 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.379",+ "version": "0.1.380","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.379",+ "version": "0.1.380","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.jsonindex 61dc8a6c6..264e3c7bd 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.379",+ "version": "0.1.380","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/createMetrics.test.ts b/host-context-controller/src/createMetrics.test.tsindex 777769db3..ba8a5464a 100644--- a/host-context-controller/src/createMetrics.test.ts+++ b/host-context-controller/src/createMetrics.test.ts@@ -74,7 +74,7 @@ describe('Kubernetes create instrumentation', () => {}visit(file)}- expect(kinds).toHaveLength(25)+ expect(kinds).toHaveLength(24)expect([...new Set(kinds)].sort()).toEqual([...CREATE_KINDS].sort())})diff --git a/host-context-controller/src/existenceReadMetrics.test.ts b/host-context-controller/src/existenceReadMetrics.test.tsindex 8cd58be85..c71df72ba 100644--- a/host-context-controller/src/existenceReadMetrics.test.ts+++ b/host-context-controller/src/existenceReadMetrics.test.ts@@ -28,10 +28,6 @@ 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::revalidatePod::readNamespacedPod': [- 1,- 'Exact Pod UID revalidation across private input/output transport awaits',- ],'hostReconciler.ts::readHostDeploymentOrNull::readNamespacedDeployment': [1,'Input to runtime binding and refresh decisions',@@ -189,7 +185,6 @@ function readProductionSources(): Record<string, string> {function assertReadInventory(sources: Record<string, string>): void {const expectedWrapped: Record<string, number> = {- 'hostExecution/operations.ts': 1,'utils.ts': 1,'hostReconciler.ts': 9,'reconciler.ts': 3,@@ -259,8 +254,8 @@ function assertReadInventory(sources: Record<string, string>): void {expect(reason.length, id).toBeGreaterThan(0)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(45)+ expect(Object.values(wrapped).reduce((sum, count) => sum + count, 0)).toBe(26)+ expect(Object.values(excluded).reduce((sum, count) => sum + count, 0)).toBe(44)}it('classifies every direct dot-property production SDK read as observed or explicitly excluded', () => {diff --git a/host-context-controller/src/hostExecution/authorization.test.ts b/host-context-controller/src/hostExecution/authorization.test.tsdeleted file mode 100644index bbd0e31f2..000000000--- a/host-context-controller/src/hostExecution/authorization.test.ts+++ /dev/null@@ -1,422 +0,0 @@-import { describe, expect, it, vi } from 'vitest'-import type { VerifiedMcpHostPrincipal } from '../mcpApiAuthentication'-import {- HostExecutionAuthorization,- HostExecutionAuthorizationError,- HostExecutionAuthorizationErrorCode,- HostExecutionBinding,- HostExecutionHostRecord,- ReadHostRecord,-} from './authorization'--const HOST_UID = '9f0e3a5c-5f1e-4a4e-9a2d-3f4c5b6a7d8e'--const principal: VerifiedMcpHostPrincipal = {- subject: 'mcp-host/standalone',- hostName: 'chatllm',- hostUid: HOST_UID,- namespace: 'mcp-host',- jti: 'jti-0001',- issuedAt: 1_700_000_000,- expiresAt: 4_102_444_800,- audiences: ['host-context-controller'],- nativeExecutionAllowed: true,-}--const liveHost: HostExecutionHostRecord = {- name: 'chatllm',- namespace: 'mcp-host',- uid: HOST_UID,- generation: 7,-}--/** Reader stub that records calls and serves the supplied sequence. */-function reader(...records: Array<HostExecutionHostRecord | null | undefined>) {- const calls: Array<[string, string]> = []- const readHost = (async (name: string, namespace: string) => {- calls.push([name, namespace])- return records.length > 1 ? records.shift() : records[0]- }) as ReadHostRecord- return { readHost, calls }-}--async function rejection(run: () => Promise<unknown>): Promise<HostExecutionAuthorizationError> {- try {- await run()- } catch (error) {- if (error instanceof HostExecutionAuthorizationError) return error- throw error- }- throw new Error('expected HostExecutionAuthorizationError')-}--function expectCode(- error: HostExecutionAuthorizationError,- code: HostExecutionAuthorizationErrorCode-) {- expect(error.code).toBe(code)- expect(error.message).toBe(code)-}--async function bindingFor(- authorization: HostExecutionAuthorization-): Promise<HostExecutionBinding> {- return authorization.authorize(principal)-}--describe('Host execution authorization', () => {- it('binds a granted principal to the live Host it names', async () => {- const { readHost, calls } = reader(liveHost)- const binding = await bindingFor(new HostExecutionAuthorization(readHost))-- expect(calls).toEqual([['chatllm', 'mcp-host']])- expect(binding).toEqual({- hostName: 'chatllm',- hostUid: HOST_UID,- namespace: 'mcp-host',- generation: 7,- })- expect(Object.isFrozen(binding)).toBe(true)- expect(() => {- ;(binding as { hostUid: string }).hostUid = 'foreign'- }).toThrow()- })-- it('revalidates against the live Host and tolerates resourceVersion churn', async () => {- const churned = { ...liveHost, resourceVersion: '2031' }- const { readHost, calls } = reader(liveHost, churned)- const authorization = new HostExecutionAuthorization(readHost)- const binding = await bindingFor(authorization)-- await expect(authorization.revalidate(principal, binding)).resolves.toBeUndefined()- expect(calls).toEqual([- ['chatllm', 'mcp-host'],- ['chatllm', 'mcp-host'],- ])- })-- it('waits for the live re-read and rejects a generation change after it', async () => {- let release!: (record: HostExecutionHostRecord) => void- const pending = new Promise<HostExecutionHostRecord>(resolve => {- release = resolve- })- const authorization = new HostExecutionAuthorization(() => pending)- const binding: HostExecutionBinding = Object.freeze({- hostName: 'chatllm',- hostUid: HOST_UID,- namespace: 'mcp-host',- generation: 7,- })-- let outcome = ''- const attempt = authorization.revalidate(principal, binding).then(- () => {- outcome = 'resolved'- },- (error: HostExecutionAuthorizationError) => {- outcome = error.code- }- )- await Promise.resolve()- expect(outcome).toBe('')-- release({ ...liveHost, generation: 8 })- await attempt- expect(outcome).toBe('host_generation_changed')- })-- it('requires the signed native execution scope before any read', async () => {- const forged = [- { ...principal, nativeExecutionAllowed: undefined },- { ...principal, nativeExecutionAllowed: 1 as unknown as true },- { ...principal, nativeExecutionAllowed: 'true' as unknown as true },- ]- for (const candidate of forged) {- const { readHost, calls } = reader(liveHost)- const error = await rejection(() =>- new HostExecutionAuthorization(readHost).authorize(candidate)- )- expectCode(error, 'native_execution_not_authorized')- expect(calls).toEqual([])- }- })-- it('rejects an expired principal before any read, in both directions', async () => {- const expired = { ...principal, expiresAt: Math.floor(Date.now() / 1000) - 1 }- const { readHost, calls } = reader(liveHost)- const authorization = new HostExecutionAuthorization(readHost)-- expectCode(await rejection(() => authorization.authorize(expired)), 'principal_expired')- const binding = await bindingFor(authorization)- expectCode(- await rejection(() => authorization.revalidate(expired, binding)),- 'principal_expired'- )- expect(calls).toEqual([['chatllm', 'mcp-host']])- })-- it('withholds authority when the grant expires while the authorize read is pending', async () => {- vi.useFakeTimers()- try {- vi.setSystemTime(new Date('2026-10-05T10:00:00Z'))- const starting = Math.floor(Date.now() / 1000)- const calls: Array<[string, string]> = []- let release!: (record: HostExecutionHostRecord) => void- const pending = new Promise<HostExecutionHostRecord>(resolve => {- release = resolve- })- const authorization = new HostExecutionAuthorization(async (name, namespace) => {- calls.push([name, namespace])- return pending- })-- let outcome = ''- const attempt = authorization.authorize({ ...principal, expiresAt: starting + 5 }).then(- binding => {- outcome = `granted:${binding.generation}`- },- (error: HostExecutionAuthorizationError) => {- outcome = error.code- }- )- await Promise.resolve()- expect(outcome).toBe('')- expect(calls).toEqual([['chatllm', 'mcp-host']])-- vi.setSystemTime(new Date('2026-10-05T10:00:06Z'))- release(liveHost)- await attempt- expect(outcome).toBe('principal_expired')- } finally {- vi.useRealTimers()- }- })-- it('withholds confirmation when the grant expires while the revalidate read is pending', async () => {- vi.useFakeTimers()- try {- vi.setSystemTime(new Date('2026-10-05T10:00:00Z'))- const starting = Math.floor(Date.now() / 1000)- const expiring = { ...principal, expiresAt: starting + 5 }- const binding = await bindingFor(new HostExecutionAuthorization(reader(liveHost).readHost))-- let release!: (record: HostExecutionHostRecord) => void- const pending = new Promise<HostExecutionHostRecord>(resolve => {- release = resolve- })- const authorization = new HostExecutionAuthorization(() => pending)-- let outcome = ''- const attempt = authorization.revalidate(expiring, binding).then(- () => {- outcome = 'confirmed'- },- (error: HostExecutionAuthorizationError) => {- outcome = error.code- }- )- await Promise.resolve()- expect(outcome).toBe('')-- vi.setSystemTime(new Date('2026-10-05T10:00:06Z'))- release(liveHost)- await attempt- expect(outcome).toBe('principal_expired')- } finally {- vi.useRealTimers()- }- })-- it('never defaults a missing or malformed principal identity', async () => {- // Kubernetes bounds: Host name is a DNS-1123 subdomain (<=253, dot-joined- // labels), namespace is a DNS-1123 label (<=63, no dots).- const longName = ['a'.repeat(63), 'b'.repeat(63), 'c'.repeat(63), 'd'.repeat(61)].join('.')- const malformed = [- { ...principal, hostName: '' },- { ...principal, hostName: 'ChatLLM' },- { ...principal, hostName: 'chatllm_1' },- { ...principal, hostName: 'chatllm..internal' },- { ...principal, hostName: `${longName}a` },- { ...principal, hostUid: '' },- { ...principal, hostUid: 'uid with spaces' },- { ...principal, namespace: '' },- { ...principal, namespace: 'Bad_Namespace' },- { ...principal, namespace: 'a'.repeat(64) },- { ...principal, namespace: 'mcp.host' },- { ...principal, expiresAt: Number.NaN },- ]- for (const candidate of malformed) {- const { readHost, calls } = reader(liveHost)- expectCode(- await rejection(() => new HostExecutionAuthorization(readHost).authorize(candidate)),- 'principal_invalid'- )- expect(calls).toEqual([])- }- const noUid = { ...principal } as Partial<VerifiedMcpHostPrincipal>- delete noUid.hostUid- const { readHost, calls } = reader(liveHost)- expectCode(- await rejection(() =>- new HostExecutionAuthorization(readHost).authorize(noUid as VerifiedMcpHostPrincipal)- ),- 'principal_invalid'- )- expect(calls).toEqual([])- })-- it('accepts a dotted or 253-character Host subdomain with a label namespace', async () => {- const longestName = ['a'.repeat(63), 'b'.repeat(63), 'c'.repeat(63), 'd'.repeat(61)].join('.')- expect(longestName).toHaveLength(253)- for (const hostName of ['chatllm.tenant-1', longestName]) {- const { readHost, calls } = reader({ ...liveHost, name: hostName })- const binding = await new HostExecutionAuthorization(readHost).authorize({- ...principal,- hostName,- })- expect(binding.hostName).toBe(hostName)- expect(calls).toEqual([[hostName, 'mcp-host']])- }- })-- it('rejects a missing Host record instead of granting by name alone', async () => {- const missing = reader(null)- expectCode(- await rejection(() => bindingFor(new HostExecutionAuthorization(missing.readHost))),- 'host_not_found'- )- const absent = reader(undefined)- expectCode(- await rejection(() => bindingFor(new HostExecutionAuthorization(absent.readHost))),- 'host_not_found'- )- })-- it('rejects a foreign UID for the requested Host name', async () => {- const foreign = reader({ ...liveHost, uid: 'a1b2c3d4-0000-4000-8000-000000000000' })- expectCode(- await rejection(() => bindingFor(new HostExecutionAuthorization(foreign.readHost))),- 'host_identity_mismatch'- )- })-- it('rejects a record for another Host name or namespace', async () => {- for (const record of [- { ...liveHost, name: 'other-host' },- { ...liveHost, namespace: 'other-namespace' },- ]) {- const { readHost } = reader(record)- expectCode(- await rejection(() => bindingFor(new HostExecutionAuthorization(readHost))),- 'host_identity_mismatch'- )- }- })-- it('rejects a deleting Host on authorize and on revalidate', async () => {- const deleting = { ...liveHost, deletionTimestamp: '2026-10-05T10:00:00Z' }- const first = reader(deleting)- expectCode(- await rejection(() => bindingFor(new HostExecutionAuthorization(first.readHost))),- 'host_deleted'- )- const second = reader(liveHost, deleting)- const authorization = new HostExecutionAuthorization(second.readHost)- const binding = await bindingFor(authorization)- expectCode(await rejection(() => authorization.revalidate(principal, binding)), 'host_deleted')- })-- it('rejects a malformed live record or generation', async () => {- const malformed: unknown[] = [- { ...liveHost, generation: 0 },- { ...liveHost, generation: -1 },- { ...liveHost, generation: 1.5 },- { ...liveHost, generation: Number.NaN },- { ...liveHost, generation: '3' },- { ...liveHost, uid: '' },- { ...liveHost, name: 42 },- 'chatllm',- ]- for (const record of malformed) {- const { readHost } = reader(record as HostExecutionHostRecord)- expectCode(- await rejection(() => bindingFor(new HostExecutionAuthorization(readHost))),- 'host_record_invalid'- )- }- })-- it('rejects a recreated Host UID after authorize', async () => {- const recreated = { ...liveHost, uid: 'b1b2c3d4-1111-4111-8111-111111111111' }- const { readHost } = reader(liveHost, recreated)- const authorization = new HostExecutionAuthorization(readHost)- const binding = await bindingFor(authorization)-- expectCode(- await rejection(() => authorization.revalidate(principal, binding)),- 'host_uid_recreated'- )- })-- it('rejects a changed generation and a mismatched live namespace after authorize', async () => {- const generation = reader(liveHost, { ...liveHost, generation: 8 })- const first = new HostExecutionAuthorization(generation.readHost)- const firstBinding = await bindingFor(first)- expectCode(- await rejection(() => first.revalidate(principal, firstBinding)),- 'host_generation_changed'- )-- const namespace = reader(liveHost, { ...liveHost, namespace: 'other-namespace' })- const second = new HostExecutionAuthorization(namespace.readHost)- const secondBinding = await bindingFor(second)- expectCode(- await rejection(() => second.revalidate(principal, secondBinding)),- 'host_identity_mismatch'- )- })-- it('rejects a binding that belongs to another principal before reading', async () => {- const { readHost, calls } = reader(liveHost)- const authorization = new HostExecutionAuthorization(readHost)- const foreignBinding: HostExecutionBinding = Object.freeze({- hostName: 'other-host',- hostUid: HOST_UID,- namespace: 'mcp-host',- generation: 7,- })-- expectCode(- await rejection(() => authorization.revalidate(principal, foreignBinding)),- 'host_identity_mismatch'- )- const foreignUid = Object.freeze({- ...foreignBinding,- hostUid: 'c1b2c3d4-2222-4222-8222-222222222222',- })- expectCode(- await rejection(() => authorization.revalidate(principal, foreignUid)),- 'host_identity_mismatch'- )- expect(calls).toEqual([])- })-- it('reports fixed codes without leaking token or actor material', async () => {- const cases: Array<[VerifiedMcpHostPrincipal, HostExecutionHostRecord | null]> = [- [{ ...principal, nativeExecutionAllowed: undefined }, liveHost],- [{ ...principal, expiresAt: 1 }, liveHost],- [principal, null],- [principal, { ...liveHost, uid: 'foreign-uid' }],- ]- for (const [candidate, record] of cases) {- const { readHost } = reader(record)- const error = await rejection(() =>- new HostExecutionAuthorization(readHost).authorize(candidate)- )- expect(error.message).toBe(error.code)- for (const secret of [principal.jti, principal.subject, 'jti-0001']) {- expect(error.message).not.toContain(secret)- }- }- })-})diff --git a/host-context-controller/src/hostExecution/authorization.ts b/host-context-controller/src/hostExecution/authorization.tsdeleted file mode 100644index 5b162db0d..000000000--- a/host-context-controller/src/hostExecution/authorization.ts+++ /dev/null@@ -1,172 +0,0 @@-/**- * Host execution authorization gate (PR #932 / issue #986).- *- * The signed `host:tools:execute` scope is the only way a principal becomes- * `nativeExecutionAllowed`, and this class binds that grant to one live Host- * object: exact name, namespace and UID plus a positive generation. It never- * grants execution from a Host name alone, never defaults a missing identity,- * and never reads, logs or embeds token material.- */-import type { VerifiedMcpHostPrincipal } from '../mcpApiAuthentication'--/** Minimal live server record the gate needs; the reader supplies it. */-export interface HostExecutionHostRecord {- name: string- namespace: string- uid: string- generation: number- deletionTimestamp?: string-}--export type ReadHostRecord = (- name: string,- namespace: string-) => Promise<HostExecutionHostRecord | null>--export type HostExecutionAuthorizationErrorCode =- | 'native_execution_not_authorized'- | 'principal_invalid'- | 'principal_expired'- | 'host_not_found'- | 'host_record_invalid'- | 'host_identity_mismatch'- | 'host_deleted'- | 'host_uid_recreated'- | 'host_generation_changed'--export class HostExecutionAuthorizationError extends Error {- constructor(readonly code: HostExecutionAuthorizationErrorCode) {- super(code)- this.name = 'HostExecutionAuthorizationError'- }-}--/** Immutable authority snapshot; carries no token, subject or credential. */-export interface HostExecutionBinding {- readonly hostName: string- readonly hostUid: string- readonly namespace: string- readonly generation: number-}--const DNS1123_LABEL = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/-const CANONICAL_UID = /^[A-Za-z0-9._:-]{1,128}$/--function fail(code: HostExecutionAuthorizationErrorCode): never {- throw new HostExecutionAuthorizationError(code)-}--function isDns1123Label(value: unknown): value is string {- return (- typeof value === 'string' && value.length > 0 && value.length <= 63 && DNS1123_LABEL.test(value)- )-}--/** Host names are DNS-1123 subdomains: <=253 characters of dot-joined labels. */-function isDns1123Subdomain(value: unknown): value is string {- return (- typeof value === 'string' &&- value.length > 0 &&- value.length <= 253 &&- value.split('.').every(isDns1123Label)- )-}--/**- * The scope check comes first so an old credential token cannot reach any read,- * and a malformed or absent identity field is rejected instead of defaulted.- */-function requireGrantedPrincipal(principal: VerifiedMcpHostPrincipal, nowSeconds: number): void {- if (principal.nativeExecutionAllowed !== true) fail('native_execution_not_authorized')- if (- !isDns1123Subdomain(principal.hostName) ||- typeof principal.hostUid !== 'string' ||- !CANONICAL_UID.test(principal.hostUid) ||- !isDns1123Label(principal.namespace)- ) {- fail('principal_invalid')- }- requireUnexpiredPrincipal(principal, nowSeconds)-}--/**- * Re-checked after every await: the live read can outlive the grant, and- * authority must never be handed out or confirmed for an expired principal.- */-function requireUnexpiredPrincipal(principal: VerifiedMcpHostPrincipal, nowSeconds: number): void {- if (!Number.isSafeInteger(principal.expiresAt)) fail('principal_invalid')- if (principal.expiresAt <= nowSeconds) fail('principal_expired')-}--/** A missing Host is a distinct failure from a Host that returns nonsense. */-function requireLiveHost(record: unknown): HostExecutionHostRecord {- if (record === null || record === undefined) fail('host_not_found')- if (typeof record !== 'object') fail('host_record_invalid')- const candidate = record as Partial<HostExecutionHostRecord>- if (- typeof candidate.name !== 'string' ||- candidate.name.length === 0 ||- typeof candidate.namespace !== 'string' ||- candidate.namespace.length === 0 ||- typeof candidate.uid !== 'string' ||- candidate.uid.length === 0- ) {- fail('host_record_invalid')- }- if (!Number.isSafeInteger(candidate.generation) || (candidate.generation as number) <= 0) {- fail('host_record_invalid')- }- return candidate as HostExecutionHostRecord-}--export class HostExecutionAuthorization {- constructor(private readonly readHost: ReadHostRecord) {}-- /** Binds one granted principal to the live Host it names. */- async authorize(principal: VerifiedMcpHostPrincipal): Promise<HostExecutionBinding> {- requireGrantedPrincipal(principal, Math.floor(Date.now() / 1000))- const live = requireLiveHost(await this.readHost(principal.hostName, principal.namespace))- requireUnexpiredPrincipal(principal, Math.floor(Date.now() / 1000))- if (live.deletionTimestamp !== undefined) fail('host_deleted')- if (- live.name !== principal.hostName ||- live.namespace !== principal.namespace ||- live.uid !== principal.hostUid- ) {- fail('host_identity_mismatch')- }- return Object.freeze({- hostName: live.name,- hostUid: live.uid,- namespace: live.namespace,- generation: live.generation,- })- }-- /**- * Re-reads the live Host after any await, before an operation starts or a- * result is published. UID and generation are compared, not resourceVersion:- * heartbeat status writes churn resourceVersion without changing authority.- */- async revalidate(- principal: VerifiedMcpHostPrincipal,- binding: HostExecutionBinding- ): Promise<void> {- requireGrantedPrincipal(principal, Math.floor(Date.now() / 1000))- if (- binding.hostName !== principal.hostName ||- binding.namespace !== principal.namespace ||- binding.hostUid !== principal.hostUid- ) {- fail('host_identity_mismatch')- }- const live = requireLiveHost(await this.readHost(binding.hostName, binding.namespace))- requireUnexpiredPrincipal(principal, Math.floor(Date.now() / 1000))- if (live.deletionTimestamp !== undefined) fail('host_deleted')- if (live.name !== binding.hostName || live.namespace !== binding.namespace) {- fail('host_identity_mismatch')- }- if (live.uid !== binding.hostUid) fail('host_uid_recreated')- if (live.generation !== binding.generation) fail('host_generation_changed')- }-}diff --git a/host-context-controller/src/hostExecution/inputTransport.test.ts b/host-context-controller/src/hostExecution/inputTransport.test.tsdeleted file mode 100644index b0cf100a7..000000000--- a/host-context-controller/src/hostExecution/inputTransport.test.ts+++ /dev/null@@ -1,91 +0,0 @@-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.tsdeleted file mode 100644index 589282513..000000000--- a/host-context-controller/src/hostExecution/inputTransport.ts+++ /dev/null@@ -1,87 +0,0 @@-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.launcher.test.ts b/host-context-controller/src/hostExecution/jobFactory.launcher.test.tsdeleted file mode 100644index f33d0c6f8..000000000--- a/host-context-controller/src/hostExecution/jobFactory.launcher.test.ts+++ /dev/null@@ -1,117 +0,0 @@-import { describe, expect, it } from 'vitest'-import type * as k8s from '@kubernetes/client-node'-import { spawnSync } from 'node:child_process'-import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'-import { tmpdir } from 'node:os'-import { dirname, join } from 'node:path'-import {- ApprovedExecutionRequest,- EXECUTION_RUN_ENTRYPOINT,- TrustedHostExecutionIdentity,- buildHostExecutionJob,-} from './jobFactory'--const identity: TrustedHostExecutionIdentity = {- hostName: 'chatllm',- hostUid: '9f0e3a5c-5f1e-4a4e-9a2d-3f4c5b6a7d8e',- namespace: 'mcp-host',- operationId: '7b1f0d2c-3a4b-4c5d-8e9f-0a1b2c3d4e5f',- hostGeneration: 7,- image: 'registry.example.com/evenfire/mcp-host@sha256:0123456789abcdef',- workspacePvcName: 'chatllm-workspace',- userKey: '0123456789abcdef',- workspaceLayoutPrefix: 'workspace/',-}--const baseRequest: ApprovedExecutionRequest = {- kind: 'workspace',- argv: [],- timeoutMs: 60_000,- scratchBytes: 33_554_432,-}--function podSpec(job: k8s.V1Job): k8s.V1PodSpec {- return job.spec!.template.spec!-}--/**- * Local launch-contract falsifier, not a Linux /proc or Kubernetes check. The- * assembled Job command is executed with only its fixed image entrypoint- * replaced by a synthetic Node fixture, so the wrapper's real descriptors,- * output sinks and argument passing are observed from a child process.- */-describe('executor launcher contract', () => {- it('keeps wrapper stdio private and passes the approved vector literally', () => {- const dir = mkdtempSync(join(tmpdir(), 'host-execution-launcher-'))- try {- const reportPath = join(dir, 'report.json')- const fixturePath = join(dir, 'fixture.cjs')- const sideEffect = (name: string) => join(dir, `pwned-${name}`)- const argv = [- 'plain',- 'a b',- '"double quoted"',- "'single quoted'",- `$(touch ${sideEffect('dollar')})`,- '`touch ' + sideEffect('backtick') + '`',- `; touch ${sideEffect('semicolon')}`,- `&& touch ${sideEffect('and')}`,- `| touch ${sideEffect('pipe')}`,- '$HOME',- '*',- ]- const fixture = [- "const fs = require('node:fs')",- 'const describeFd = fd => {',- ' const stat = fs.fstatSync(fd)',- ' return { isCharacterDevice: stat.isCharacterDevice(), rdev: stat.rdev }',- '}',- 'fs.writeFileSync(process.env.LAUNCHER_FIXTURE_REPORT, JSON.stringify({',- ' argv: process.argv.slice(2),',- ' fd1: describeFd(1),',- ' fd2: describeFd(2),',- " devNullRdev: fs.statSync('/dev/null').rdev,",- '}))',- "process.stdout.write('LAUNCHER_FIXTURE_STDOUT_SENTINEL')",- "process.stderr.write('LAUNCHER_FIXTURE_STDERR_SENTINEL')",- ].join('\n')- writeFileSync(fixturePath, fixture)-- const job = buildHostExecutionJob(identity, { ...baseRequest, argv })- const command = [...podSpec(job).containers![0].command!]- const entrypointIndex = command.indexOf(EXECUTION_RUN_ENTRYPOINT)- expect(entrypointIndex).toBeGreaterThanOrEqual(0)- command[entrypointIndex] = fixturePath-- const result = spawnSync(command[0]!, command.slice(1), {- encoding: 'utf8',- timeout: 5_000,- env: {- ...process.env,- PATH: `${dirname(process.execPath)}:${process.env.PATH ?? ''}`,- LAUNCHER_FIXTURE_REPORT: reportPath,- },- })- expect(result.error).toBeUndefined()- expect(result.signal).toBeNull()- expect(result.status).toBe(0)-- const report = JSON.parse(readFileSync(reportPath, 'utf8')) as {- argv: string[]- fd1: { isCharacterDevice: boolean; rdev: number }- fd2: { isCharacterDevice: boolean; rdev: number }- devNullRdev: number- }- expect(report.argv).toEqual([String(baseRequest.timeoutMs), ...argv])- expect(report.fd1).toEqual({ isCharacterDevice: true, rdev: report.devNullRdev })- expect(report.fd2).toEqual({ isCharacterDevice: true, rdev: report.devNullRdev })- expect(result.stdout).not.toContain('LAUNCHER_FIXTURE_STDOUT_SENTINEL')- expect(result.stderr).not.toContain('LAUNCHER_FIXTURE_STDERR_SENTINEL')- for (const name of ['dollar', 'backtick', 'semicolon', 'and', 'pipe']) {- expect(existsSync(sideEffect(name))).toBe(false)- }- } finally {- rmSync(dir, { recursive: true, force: true })- }- })-})diff --git a/host-context-controller/src/hostExecution/jobFactory.test.ts b/host-context-controller/src/hostExecution/jobFactory.test.tsdeleted file mode 100644index ecb848fd2..000000000--- a/host-context-controller/src/hostExecution/jobFactory.test.ts+++ /dev/null@@ -1,879 +0,0 @@-import { describe, expect, it } from 'vitest'-import type * as k8s from '@kubernetes/client-node'-import { MANAGED_BY_LABEL, MANAGED_BY_VALUE } from '../constants'-import {- ApprovedExecutionRequest,- EXECUTION_ARGV_MAX_BYTES,- EXECUTION_CONTRACT_FINGERPRINT_ANNOTATION,- EXECUTION_HOST_GENERATION_ANNOTATION,- EXECUTION_HOST_UID_LABEL,- EXECUTION_INPUT_MAX_BYTES,- EXECUTION_INPUT_MOUNT_PATH,- EXECUTION_INPUT_RECEIVER_CONTAINER_NAME,- EXECUTION_OPERATION_LABEL,- EXECUTION_RECEIVE_INPUT_ENTRYPOINT,- EXECUTION_ROLE_LABEL,- EXECUTION_ROLE_VALUE,- EXECUTION_RUN_ENTRYPOINT,- EXECUTION_RUN_LAUNCHER_SCRIPT,- EXECUTION_SCRATCH_MAX_BYTES,- EXECUTION_SCRATCH_MOUNT_PATH,- EXECUTION_TIMEOUT_MAX_MS,- EXECUTION_TMP_MOUNT_PATH,- EXECUTION_WORKSPACE_MOUNT_PATH,- HOST_OWNER_API_VERSION,- HostExecutionJobError,- HostExecutionRecordError,- TrustedHostExecutionIdentity,- buildHostExecutionJob,- hostExecutionContractFingerprint,- hostExecutionJobName,- hostExecutionRequestFingerprint,- validateHostExecutionJob,- validateHostExecutionPod,-} from './jobFactory'--const identity: TrustedHostExecutionIdentity = {- hostName: 'chatllm',- hostUid: '9f0e3a5c-5f1e-4a4e-9a2d-3f4c5b6a7d8e',- namespace: 'mcp-host',- operationId: '7b1f0d2c-3a4b-4c5d-8e9f-0a1b2c3d4e5f',- hostGeneration: 7,- image: 'registry.example.com/evenfire/mcp-host@sha256:0123456789abcdef',- workspacePvcName: 'chatllm-workspace',- userKey: '0123456789abcdef',- workspaceLayoutPrefix: 'workspace/',-}--const workspaceRequest: ApprovedExecutionRequest = {- kind: 'workspace',- argv: ['/usr/bin/git', 'status', '--short'],- timeoutMs: 60_000,- scratchBytes: 33_554_432,-}--const attachmentRequest: ApprovedExecutionRequest = {- kind: 'attachment',- argv: ['node', '/app/mcp-host/dist/core/tools/attachmentRead.js', '/input/source'],- timeoutMs: 120_000,- scratchBytes: 16_777_216,- input: { byteLength: 1_048_576, sha256: 'a'.repeat(64) },-}--const expectedLabels = {- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,- [EXECUTION_OPERATION_LABEL]: identity.operationId,- [EXECUTION_HOST_UID_LABEL]: identity.hostUid,- [EXECUTION_ROLE_LABEL]: EXECUTION_ROLE_VALUE,-}--function podSpec(job: k8s.V1Job): k8s.V1PodSpec {- return job.spec!.template.spec!-}--function volume(job: k8s.V1Job, name: string): k8s.V1Volume {- const found = podSpec(job).volumes!.find(candidate => candidate.name === name)- if (!found) throw new Error(`volume ${name} missing`)- return found-}--function mountAt(container: k8s.V1Container, mountPath: string): k8s.V1VolumeMount {- const found = (container.volumeMounts ?? []).find(candidate => candidate.mountPath === mountPath)- if (!found) throw new Error(`mount ${mountPath} missing`)- return found-}--function collectNamespaces(value: unknown, found: string[] = []): string[] {- if (Array.isArray(value)) {- for (const item of value) collectNamespaces(item, found)- return found- }- if (value && typeof value === 'object') {- for (const [key, child] of Object.entries(value)) {- if (key === 'namespace' && typeof child === 'string') found.push(child)- else collectNamespaces(child, found)- }- }- return found-}--/** Returns the thrown validation error so the exact rejected field is asserted. */-function rejection(run: () => unknown): HostExecutionJobError {- try {- run()- } catch (error) {- if (error instanceof HostExecutionJobError) return error- throw error- }- throw new Error('expected HostExecutionJobError')-}--function rejectionRecord(run: () => unknown): HostExecutionRecordError {- try {- run()- } catch (error) {- if (error instanceof HostExecutionRecordError) return error- throw error- }- throw new Error('expected HostExecutionRecordError')-}--/** A Job as the API returns it: the emitted spec plus a server UID. */-function storedJob(uid = 'job-uid-0001'): k8s.V1Job {- const job = buildHostExecutionJob(identity, workspaceRequest)- job.metadata!.uid = uid- return job-}--function ownedPod(job: k8s.V1Job): k8s.V1Pod {- return {- metadata: {- name: `${job.metadata!.name}-abc12`,- namespace: job.metadata!.namespace,- uid: 'pod-uid-0001',- annotations: { ...(job.spec!.template.metadata!.annotations ?? {}) },- ownerReferences: [- {- apiVersion: 'batch/v1',- kind: 'Job',- name: job.metadata!.name,- uid: job.metadata!.uid,- controller: true,- },- ],- },- } as k8s.V1Pod-}--describe('bounded Host execution job factory', () => {- it('requests native collection of finished Jobs and their private input Pods without a caller', () => {- for (const request of [workspaceRequest, attachmentRequest]) {- const job = buildHostExecutionJob(identity, request)- // activeDeadlineSeconds stops work, but leaves terminated Pods and their- // input volumes behind unless the Kubernetes TTL controller collects- // the Job. A lost/disconnected caller must not retain those copies.- expect(job.spec!.ttlSecondsAfterFinished).toBe(0)- expect(job.spec!.activeDeadlineSeconds).toBeLessThanOrEqual(- Math.ceil(EXECUTION_TIMEOUT_MAX_MS / 1000) + 60- )- }- })-- it('encodes one workspace Job under the Host owner with targetable labels', () => {- const job = buildHostExecutionJob(identity, workspaceRequest)-- expect(job.apiVersion).toBe('batch/v1')- expect(job.kind).toBe('Job')- expect(job.metadata!.name).toBe(`host-exec-${identity.operationId}`)- expect(job.metadata!.name!.length).toBeLessThanOrEqual(63)- expect(job.metadata!.namespace).toBe(identity.namespace)- expect(job.metadata!.labels).toEqual(expectedLabels)- expect(job.spec!.template.metadata!.labels).toEqual(expectedLabels)- // blockOwnerDeletion would require owner/finalizer RBAC this feature does- // not hold; the exact UID still binds the reference to one Host object.- expect(job.metadata!.ownerReferences).toEqual([- {- apiVersion: HOST_OWNER_API_VERSION,- kind: 'Host',- name: identity.hostName,- uid: identity.hostUid,- controller: true,- },- ])-- expect(job.spec!.backoffLimit).toBe(0)- expect(job.spec!.activeDeadlineSeconds).toBe(120)- expect(podSpec(job).restartPolicy).toBe('Never')- expect(podSpec(job).initContainers).toBeUndefined()- expect(volume(job, 'workspace').persistentVolumeClaim).toEqual({- claimName: identity.workspacePvcName,- readOnly: false,- })-- const executor = podSpec(job).containers![0]- expect(executor.command).toEqual([- '/bin/sh',- '-c',- EXECUTION_RUN_LAUNCHER_SCRIPT,- 'node',- EXECUTION_RUN_ENTRYPOINT,- String(workspaceRequest.timeoutMs),- ...workspaceRequest.argv,- ])- expect(executor.args).toBeUndefined()- expect(executor.workingDir).toBe(EXECUTION_WORKSPACE_MOUNT_PATH)- 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' } } },- ])- })-- it('mounts exactly one explicit subPath for the dual layout, the legacy root and _system', () => {- const cases: Array<[TrustedHostExecutionIdentity['workspaceLayoutPrefix'], string, string]> = [- ['workspace/', identity.userKey, `workspace/users/${identity.userKey}`],- ['', identity.userKey, `users/${identity.userKey}`],- ['workspace/', '_system', 'workspace/users/_system'],- ]- for (const [workspaceLayoutPrefix, userKey, expectedSubPath] of cases) {- const job = buildHostExecutionJob(- { ...identity, workspaceLayoutPrefix, userKey },- workspaceRequest- )- const executor = podSpec(job).containers![0]- const subPaths = (executor.volumeMounts ?? [])- .map(candidate => candidate.subPath)- .filter((candidate): candidate is string => candidate !== undefined)- expect(subPaths).toEqual([expectedSubPath])- expect(subPaths[0]).not.toBe('')- expect(subPaths[0]).not.toBe('users')- expect(subPaths[0]).not.toBe('state')- expect(mountAt(executor, EXECUTION_WORKSPACE_MOUNT_PATH).readOnly).toBe(false)- }- })-- it('never mounts the workspace PVC or store for an attachment operation', () => {- const job = buildHostExecutionJob(identity, attachmentRequest)-- expect(podSpec(job).initContainers).toHaveLength(1)- expect(- podSpec(job)- .volumes!.map(candidate => candidate.name)- .sort()- ).toEqual(['input', 'scratch'])- for (const candidate of podSpec(job).volumes!) {- expect(candidate.persistentVolumeClaim).toBeUndefined()- expect(candidate.emptyDir).toBeDefined()- }-- const executor = podSpec(job).containers![0]- expect((executor.volumeMounts ?? []).map(candidate => candidate.mountPath).sort()).toEqual([- EXECUTION_INPUT_MOUNT_PATH,- EXECUTION_SCRATCH_MOUNT_PATH,- EXECUTION_TMP_MOUNT_PATH,- ])- expect(mountAt(executor, EXECUTION_INPUT_MOUNT_PATH)).toEqual({- name: 'input',- mountPath: EXECUTION_INPUT_MOUNT_PATH,- readOnly: true,- })- expect((executor.volumeMounts ?? []).every(candidate => candidate.subPath === undefined)).toBe(- true- )- // The attachment workspace is the writable scratch volume, never the PVC.- expect(executor.workingDir).toBe(EXECUTION_SCRATCH_MOUNT_PATH)- 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])- })-- it('gives the trusted init receiver exclusive read-write input and the exact arguments', () => {- const receiver = podSpec(buildHostExecutionJob(identity, attachmentRequest)).initContainers![0]-- expect(receiver.name).toBe(EXECUTION_INPUT_RECEIVER_CONTAINER_NAME)- expect(receiver.image).toBe(identity.image)- expect(receiver.command).toEqual([- 'node',- EXECUTION_RECEIVE_INPUT_ENTRYPOINT,- String(attachmentRequest.input!.byteLength),- attachmentRequest.input!.sha256,- String(attachmentRequest.timeoutMs),- ])- expect(receiver.args).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 },- ])- })-- it('hardens every container and denies credential, runtime-env and host namespace access', () => {- for (const request of [workspaceRequest, attachmentRequest]) {- const job = buildHostExecutionJob(identity, request)- const spec = podSpec(job)- const containers = [...(spec.initContainers ?? []), ...spec.containers!]- expect(containers.length).toBeGreaterThanOrEqual(1)- for (const container of containers) {- expect(container.securityContext).toEqual({- allowPrivilegeEscalation: false,- privileged: false,- readOnlyRootFilesystem: true,- runAsNonRoot: true,- runAsUser: 1001,- runAsGroup: 1001,- capabilities: { drop: ['ALL'] },- seccompProfile: { type: 'RuntimeDefault' },- })- }- expect(spec.automountServiceAccountToken).toBe(false)- expect(spec.enableServiceLinks).toBe(false)- expect(spec.hostPID).toBe(false)- expect(spec.hostIPC).toBe(false)- expect(spec.hostNetwork).toBe(false)- expect(spec.shareProcessNamespace).toBe(false)- expect(spec.securityContext).toEqual({- runAsNonRoot: true,- runAsUser: 1001,- runAsGroup: 1001,- fsGroup: 1001,- seccompProfile: { type: 'RuntimeDefault' },- })- for (const candidate of spec.volumes!) {- expect(candidate.secret).toBeUndefined()- expect(candidate.configMap).toBeUndefined()- expect(candidate.hostPath).toBeUndefined()- expect(candidate.projected).toBeUndefined()- }- }- })-- it('bounds /scratch and /tmp with one memory volume and a finite memory limit', () => {- const job = buildHostExecutionJob(identity, workspaceRequest)- const scratch = volume(job, 'scratch')- expect(scratch.emptyDir).toEqual({- medium: 'Memory',- sizeLimit: String(workspaceRequest.scratchBytes),- })- const executor = podSpec(job).containers![0]- expect(mountAt(executor, EXECUTION_SCRATCH_MOUNT_PATH).name).toBe('scratch')- expect(mountAt(executor, EXECUTION_TMP_MOUNT_PATH).name).toBe('scratch')- expect(- (executor.volumeMounts ?? []).filter(candidate => candidate.name === 'scratch')- ).toHaveLength(2)- expect(podSpec(job).volumes!.map(candidate => candidate.name)).not.toContain('tmp')- expect(executor.resources!.requests).toEqual({ cpu: '100m', memory: '64Mi' })- // 256Mi working set + 11Mi maximum input + the 32Mi aggregate scratch bound.- expect(executor.resources!.limits).toEqual({ cpu: '1', memory: '299Mi' })-- const receiver = podSpec(buildHostExecutionJob(identity, attachmentRequest)).initContainers![0]- expect(receiver.resources!.limits).toEqual({ cpu: '250m', memory: '256Mi' })- expect(volume(buildHostExecutionJob(identity, attachmentRequest), 'input').emptyDir).toEqual({- medium: 'Memory',- sizeLimit: String(EXECUTION_INPUT_MAX_BYTES),- })- })-- it('derives the bounded deadline from the requested timeout and rejects the edges', () => {- const at = (timeoutMs: number) =>- buildHostExecutionJob(identity, { ...workspaceRequest, timeoutMs }).spec!- .activeDeadlineSeconds-- 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- ).toBe('request.timeoutMs')- }- })-- it('preserves the approved vector, allows empty arguments after argv[0] and bounds its bytes', () => {- const emptyTail: ApprovedExecutionRequest = {- ...workspaceRequest,- argv: ['/bin/sh', '-c', ''],- }- expect(- podSpec(buildHostExecutionJob(identity, emptyTail)).containers![0].command!.slice(6)- ).toEqual(['/bin/sh', '-c', ''])- expect(- podSpec(- buildHostExecutionJob(identity, { ...workspaceRequest, argv: ['node', '', ''] })- ).containers![0].command!.slice(6)- ).toEqual(['node', '', ''])-- // The fixed launcher keeps the caller's array literal and unaliased.- const argv = ['/usr/bin/git', 'status']- const job = buildHostExecutionJob(identity, { ...workspaceRequest, argv })- argv.push('--porcelain')- expect(podSpec(job).containers![0].command!.slice(6)).toEqual(['/usr/bin/git', 'status'])- expect(podSpec(job).containers![0].args).toBeUndefined()-- // Aggregate UTF-8 bound, measured in bytes rather than characters.- const halfBound = 'é'.repeat(EXECUTION_ARGV_MAX_BYTES / 2)- expect(- podSpec(- buildHostExecutionJob(identity, { ...workspaceRequest, argv: [halfBound] })- ).containers![0].command!.slice(6)- ).toEqual([halfBound])- for (const bad of [- [''],- ['a'.repeat(EXECUTION_ARGV_MAX_BYTES), 'x'],- ['node', halfBound],- ['node', 'é'.repeat(EXECUTION_ARGV_MAX_BYTES / 2 + 1)],- ]) {- expect(- rejection(() => buildHostExecutionJob(identity, { ...workspaceRequest, argv: bad })).field- ).toMatch(/^request\.argv/)- }- })-- it('rejects a client PVC or image override and every unknown request field', () => {- const overrides: Array<Record<string, unknown>> = [- { workspacePvcName: 'other-workspace' },- { image: 'registry.example.com/attacker/image:latest' },- { pvc: 'other-workspace' },- { namespace: 'other-namespace' },- ]- for (const override of overrides) {- const raw = { ...workspaceRequest, ...override }- const error = rejection(() =>- buildHostExecutionJob(identity, raw as ApprovedExecutionRequest)- )- expect(error.field).toBe(`request.${Object.keys(override)[0]}`)- }- })-- it('rejects invalid argument vectors and out-of-bound integers upfront', () => {- const argvCases: Array<[unknown, string]> = [- [[], 'request.argv'],- ['git status', 'request.argv'],- [['ok', 42], 'request.argv[1]'],- [['a\0b'], 'request.argv[0]'],- [['ok', 'a\0b'], 'request.argv[1]'],- [[''], 'request.argv[0]'],- ]- for (const [argv, field] of argvCases) {- expect(- rejection(() =>- buildHostExecutionJob(identity, {- ...workspaceRequest,- argv: argv as string[],- })- ).field- ).toBe(field)- }- for (const scratchBytes of [0, -1, 1.5, EXECUTION_SCRATCH_MAX_BYTES + 1]) {- expect(- rejection(() => buildHostExecutionJob(identity, { ...workspaceRequest, scratchBytes }))- .field- ).toBe('request.scratchBytes')- }- })-- it('requires the attachment input contract and rejects a workspace input', () => {- expect(- rejection(() =>- buildHostExecutionJob(identity, {- kind: 'attachment',- argv: attachmentRequest.argv,- timeoutMs: attachmentRequest.timeoutMs,- scratchBytes: attachmentRequest.scratchBytes,- })- ).field- ).toBe('request.input')- expect(- rejection(() =>- buildHostExecutionJob(identity, { ...workspaceRequest, input: attachmentRequest.input })- ).field- ).toBe('request.input')-- const badInputs: Array<Record<string, unknown>> = [- { byteLength: -1, sha256: 'a'.repeat(64) },- { byteLength: 1.5, sha256: 'a'.repeat(64) },- { byteLength: EXECUTION_INPUT_MAX_BYTES + 1, sha256: 'a'.repeat(64) },- { byteLength: 1, sha256: 'A'.repeat(64) },- { byteLength: 1, sha256: 'a'.repeat(63) },- { byteLength: 1, sha256: 'z'.repeat(64) },- { byteLength: 1, sha256: 'a'.repeat(64), path: '/etc/passwd' },- ]- for (const input of badInputs) {- expect(- rejection(() =>- buildHostExecutionJob(identity, {- ...attachmentRequest,- input: input as unknown as ApprovedExecutionRequest['input'],- })- ).field- ).toMatch(/^request\.input/)- }-- // An exact empty input is a valid file, not a missing one.- const emptyInput: ApprovedExecutionRequest = {- ...attachmentRequest,- input: {- byteLength: 0,- sha256: 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855',- },- }- expect(- podSpec(buildHostExecutionJob(identity, emptyInput)).initContainers![0].command![2]- ).toBe('0')- })-- it('rejects identity values that would produce an invalid or cross-namespace Job', () => {- const badIdentities: Array<Partial<TrustedHostExecutionIdentity>> = [- { hostName: '' },- { hostName: 'ChatLLM' },- { hostName: '-chatllm' },- { hostName: 'a'.repeat(254) },- { hostUid: 'not-a-uuid' },- { hostUid: identity.hostUid.toUpperCase() },- { namespace: 'Bad_Namespace' },- { namespace: 'a'.repeat(64) },- { operationId: identity.operationId.toUpperCase() },- { operationId: '7b1f0d2c' },- { image: 'registry.example.com/img:tag with space' },- { image: '' },- { workspacePvcName: 'not/a/name' },- { userKey: '0123456789ABCDEF' },- { userKey: '0123456789abcde' },- { userKey: '../etc' },- {- workspaceLayoutPrefix: 'workspace' as TrustedHostExecutionIdentity['workspaceLayoutPrefix'],- },- ]- for (const override of badIdentities) {- const error = rejection(() =>- buildHostExecutionJob({ ...identity, ...override }, workspaceRequest)- )- expect(error.field).toBe(`identity.${Object.keys(override)[0]}`)- }- expect(rejection(() => buildHostExecutionJob(null as never, workspaceRequest)).field).toBe(- 'identity'- )- expect(rejection(() => buildHostExecutionJob(identity, null as never)).field).toBe('request')- expect(- rejection(() =>- buildHostExecutionJob(identity, {- ...workspaceRequest,- kind: 'network' as ApprovedExecutionRequest['kind'],- })- ).field- ).toBe('request.kind')- })-- it('uses the server-resolved image for every container and keeps one Host namespace', () => {- const job = buildHostExecutionJob(identity, {- ...attachmentRequest,- input: { byteLength: 5, sha256: 'b'.repeat(64) },- })- for (const container of [...(podSpec(job).initContainers ?? []), ...podSpec(job).containers!]) {- expect(container.image).toBe(identity.image)- }- expect(collectNamespaces(job)).toEqual([identity.namespace])- expect(identity.userKey).toBe('0123456789abcdef')- })-- it('emits server-owned generation and full-contract fingerprint annotations', () => {- const job = buildHostExecutionJob(identity, workspaceRequest)- const fingerprint = hostExecutionContractFingerprint(identity, workspaceRequest)- const expected = {- [EXECUTION_HOST_GENERATION_ANNOTATION]: '7',- [EXECUTION_CONTRACT_FINGERPRINT_ANNOTATION]: fingerprint,- }-- expect(job.metadata!.annotations).toEqual(expected)- expect(job.spec!.template.metadata!.annotations).toEqual(expected)- expect(fingerprint).toMatch(/^[0-9a-f]{64}$/)- // Contract fingerprint binds the server-resolved identity...- for (const variant of [- { image: 'registry.example.com/evenfire/mcp-host@sha256:ffffffffffffffff' },- { workspacePvcName: 'other-workspace' },- { userKey: 'fedcba9876543210' },- { workspaceLayoutPrefix: '' as const },- { hostGeneration: 8 },- { hostUid: 'a1b2c3d4-0000-4000-8000-000000000000' },- ]) {- expect(- hostExecutionContractFingerprint({ ...identity, ...variant }, workspaceRequest)- ).not.toBe(fingerprint)- }- // ...and the approved request, in a fixed order.- expect(hostExecutionContractFingerprint({ ...identity }, { ...workspaceRequest })).toBe(- fingerprint- )- expect(- hostExecutionContractFingerprint(identity, { ...workspaceRequest, timeoutMs: 60_001 })- ).not.toBe(fingerprint)- expect(- hostExecutionContractFingerprint(identity, {- ...workspaceRequest,- argv: ['/usr/bin/git', 'diff'],- })- ).not.toBe(fingerprint)- expect(- hostExecutionContractFingerprint(identity, {- ...attachmentRequest,- input: { ...attachmentRequest.input!, sha256: 'c'.repeat(64) },- })- ).not.toBe(hostExecutionContractFingerprint(identity, attachmentRequest))- // The request-only fingerprint stays identity-free.- expect(hostExecutionRequestFingerprint(workspaceRequest)).not.toBe(fingerprint)- expect(hostExecutionRequestFingerprint({ ...workspaceRequest, timeoutMs: 60_001 })).not.toBe(- hostExecutionRequestFingerprint(workspaceRequest)- )- expect(hostExecutionRequestFingerprint(workspaceRequest)).toBe(- hostExecutionRequestFingerprint({ ...workspaceRequest })- )- })-- it('validates a Job re-read from the API against identity and request', () => {- const job = storedJob()- const before = JSON.stringify(job)-- expect(() => validateHostExecutionJob(job, identity, workspaceRequest)).not.toThrow()- // Re-reading must not rewrite the record it just proved.- expect(JSON.stringify(job)).toBe(before)-- expect(- rejectionRecord(() => validateHostExecutionJob(storedJob(''), identity, workspaceRequest))- .code- ).toBe('job_record_invalid')- })-- it('rejects a Job owned by another or recreated Host, even with the exact labels', () => {- const forgedOwners = [- undefined,- [],- [- {- apiVersion: HOST_OWNER_API_VERSION,- kind: 'Host',- name: identity.hostName,- uid: 'a1b2c3d4-0000-4000-8000-000000000000',- controller: true,- },- ],- [- {- apiVersion: HOST_OWNER_API_VERSION,- kind: 'Host',- name: identity.hostName,- uid: identity.hostUid,- controller: false,- },- ],- [- {- apiVersion: 'clerum.io/v1',- kind: 'Host',- name: identity.hostName,- uid: identity.hostUid,- controller: true,- },- ],- [- {- apiVersion: HOST_OWNER_API_VERSION,- kind: 'Host',- name: 'other-host',- uid: identity.hostUid,- controller: true,- },- ],- [- {- apiVersion: HOST_OWNER_API_VERSION,- kind: 'Host',- name: identity.hostName,- uid: identity.hostUid,- controller: true,- },- {- apiVersion: HOST_OWNER_API_VERSION,- kind: 'Host',- name: identity.hostName,- uid: 'b1b2c3d4-1111-4111-8111-111111111111',- controller: false,- },- ],- ]- for (const ownerReferences of forgedOwners) {- const job = storedJob()- job.metadata!.ownerReferences = ownerReferences as k8s.V1OwnerReference[] | undefined- // The labels are untouched on purpose: they never prove anything.- expect(job.metadata!.labels).toEqual(expectedLabels)- expect(- rejectionRecord(() => validateHostExecutionJob(job, identity, workspaceRequest)).code- ).toBe('job_owner_mismatch')- }- })-- it('rejects a Job emitted for another image, PVC, userKey or layout', () => {- const job = storedJob()- const variants: Array<Partial<TrustedHostExecutionIdentity>> = [- { image: 'registry.example.com/evenfire/mcp-host@sha256:ffffffffffffffff' },- { workspacePvcName: 'other-workspace' },- { userKey: 'fedcba9876543210' },- { workspaceLayoutPrefix: '' },- ]- for (const variant of variants) {- // Owner, name, generation, UID and labels stay exact on purpose: only the- // contract binding can reject a Job emitted for another identity.- expect(job.metadata!.labels).toEqual(expectedLabels)- expect(- rejectionRecord(() =>- validateHostExecutionJob(- job,- { ...identity, ...variant },- workspaceRequest,- job.metadata!.uid- )- ).code- ).toBe('job_contract_mismatch')- }- })-- it('rejects a stale generation or a different request on the stored Job', () => {- const job = storedJob()- expect(- rejectionRecord(() =>- validateHostExecutionJob(job, { ...identity, hostGeneration: 8 }, workspaceRequest)- ).code- ).toBe('job_generation_mismatch')- const staleAnnotation = storedJob()- staleAnnotation.metadata!.annotations![EXECUTION_HOST_GENERATION_ANNOTATION] = '6'- expect(- rejectionRecord(() => validateHostExecutionJob(staleAnnotation, identity, workspaceRequest))- .code- ).toBe('job_generation_mismatch')-- const otherRequest: ApprovedExecutionRequest = {- ...workspaceRequest,- argv: ['/usr/bin/git', 'status', '--porcelain'],- }- expect(rejectionRecord(() => validateHostExecutionJob(job, identity, otherRequest)).code).toBe(- 'job_contract_mismatch'- )- const replacedFingerprint = storedJob()- replacedFingerprint.metadata!.annotations![EXECUTION_CONTRACT_FINGERPRINT_ANNOTATION] =- 'd'.repeat(64)- expect(- rejectionRecord(() =>- validateHostExecutionJob(replacedFingerprint, identity, workspaceRequest)- ).code- ).toBe('job_contract_mismatch')- })-- it('rejects a stored Job with another deterministic name, operation or namespace', () => {- const renamed = storedJob()- renamed.metadata!.name = hostExecutionJobName('a1b2c3d4-0000-4000-8000-000000000000')- expect(- rejectionRecord(() => validateHostExecutionJob(renamed, identity, workspaceRequest)).code- ).toBe('job_identity_mismatch')- const foreignNamespace = storedJob()- foreignNamespace.metadata!.namespace = 'other-namespace'- expect(- rejectionRecord(() => validateHostExecutionJob(foreignNamespace, identity, workspaceRequest))- .code- ).toBe('job_identity_mismatch')- expect(- rejectionRecord(() =>- validateHostExecutionJob(- storedJob(),- { ...identity, operationId: 'a1b2c3d4-0000-4000-8000-000000000000' },- workspaceRequest- )- ).code- ).toBe('job_identity_mismatch')- })-- it('validates the Pod against the exact Job owner UID and namespace before attach', () => {- const job = storedJob()- const pod = ownedPod(job)-- expect(() => validateHostExecutionPod(pod, job, identity, workspaceRequest)).not.toThrow()- expect(- rejectionRecord(() =>- validateHostExecutionPod({ ...pod, metadata: undefined }, job, identity, workspaceRequest)- ).code- ).toBe('pod_record_invalid')- })-- it('rejects a Pod owned by another Job, another namespace or no owner', () => {- const job = storedJob()- const pod = ownedPod(job)- const foreignOwner = {- ...pod,- metadata: {- ...pod.metadata,- ownerReferences: [- {- apiVersion: 'batch/v1',- kind: 'Job',- name: job.metadata!.name,- uid: 'c1b2c3d4-2222-4222-8222-222222222222',- controller: true,- },- ],- },- }- const notController = {- ...pod,- metadata: {- ...pod.metadata,- ownerReferences: [{ ...pod.metadata!.ownerReferences![0], controller: false }],- },- }- const ownerless = { ...pod, metadata: { ...pod.metadata, ownerReferences: [] } }- const foreignNamespace = {- ...pod,- metadata: { ...pod.metadata, namespace: 'other-namespace' },- }-- for (const candidate of [foreignOwner, notController, ownerless]) {- expect(- rejectionRecord(() =>- validateHostExecutionPod(candidate as k8s.V1Pod, job, identity, workspaceRequest)- ).code- ).toBe('pod_owner_mismatch')- }- expect(- rejectionRecord(() =>- validateHostExecutionPod(foreignNamespace as k8s.V1Pod, job, identity, workspaceRequest)- ).code- ).toBe('pod_namespace_mismatch')- // A Pod owned by a replaced Job (same name, different Job UID) is rejected.- const replacedJob = storedJob('job-uid-0002')- expect(- rejectionRecord(() => validateHostExecutionPod(pod, replacedJob, identity, workspaceRequest))- .code- ).toBe('pod_owner_mismatch')- // A re-read that resolves to another object UID is rejected when the- // earlier UID is supplied, and accepted when it is the same object.- expect(- rejectionRecord(() =>- validateHostExecutionJob(- storedJob('job-uid-0002'),- identity,- workspaceRequest,- 'job-uid-0001'- )- ).code- ).toBe('job_uid_replaced')- expect(() =>- validateHostExecutionJob(- storedJob('job-uid-0001'),- identity,- workspaceRequest,- 'job-uid-0001'- )- ).not.toThrow()- expect(- rejectionRecord(() =>- validateHostExecutionPod(pod, job, identity, workspaceRequest, 'pod-uid-0000')- ).code- ).toBe('pod_uid_replaced')- expect(() =>- validateHostExecutionPod(pod, job, identity, workspaceRequest, 'pod-uid-0001')- ).not.toThrow()- })-- it('requires a positive safe Host generation in the trusted identity', () => {- for (const hostGeneration of [0, -1, 1.5, Number.NaN, '7' as unknown as number]) {- expect(- rejection(() => buildHostExecutionJob({ ...identity, hostGeneration }, workspaceRequest))- .field- ).toBe('identity.hostGeneration')- }- })-})diff --git a/host-context-controller/src/hostExecution/jobFactory.ts b/host-context-controller/src/hostExecution/jobFactory.tsdeleted file mode 100644index 0ea529565..000000000--- a/host-context-controller/src/hostExecution/jobFactory.ts+++ /dev/null@@ -1,738 +0,0 @@-/**- * Bounded per-operation Host execution job factory (PR #932 / issue #986).- *- * Pure encoder for one `batch/v1` Job in the Host's own namespace: no I/O, no- * environment reads, no image resolution and no activation. Admission, gateway- * authorization and the attach transport stay with the caller, and unit- * coverage is not a physical isolation verdict.- */-import type * as k8s from '@kubernetes/client-node'-import { createHash } from 'node:crypto'-import { MANAGED_BY_LABEL, MANAGED_BY_VALUE } from '../constants'--/** Hard input bound, mirrored from the receiver's `EXECUTION_INPUT_MAX_BYTES`. */-export const EXECUTION_INPUT_MAX_BYTES = 11_534_336-export const EXECUTION_TIMEOUT_MIN_MS = 1_000-/** Mirrors the receiver's own stream-deadline ceiling so it passes through. */-export const EXECUTION_TIMEOUT_MAX_MS = 1_500_000-export const EXECUTION_SCRATCH_MIN_BYTES = 1_048_576-/** Aggregate bound of the single memory-backed scratch volume. */-export const EXECUTION_SCRATCH_MAX_BYTES = 268_435_456-/** Aggregate UTF-8 bound of the approved argument vector. */-export const EXECUTION_ARGV_MAX_BYTES = 65_536--/** Only served Host version; a collected ownerReference must name it exactly. */-export const HOST_OWNER_API_VERSION = 'clerum.io/v1alpha1'--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/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'-/**- * Fixed launcher for the executor. The approved vector is passed only as- * positional parameters, and the wrapper's stdout/stderr become /dev/null- * before Node replaces the shell, so PID 1 exposes no container output- * descriptors to a same-UID child. `/bin/sh` and Node ship in every image.- */-export const EXECUTION_RUN_LAUNCHER_SCRIPT = 'exec "$0" "$@" >/dev/null 2>&1'-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'-/** The receiver hardcodes this directory; the executor reads `source` under it. */-export const EXECUTION_INPUT_MOUNT_PATH = '/input'--/** Labels on the Job and on the Pod template, for cancellation and policy. */-export const EXECUTION_OPERATION_LABEL = 'clerum.io/operation'-export const EXECUTION_HOST_UID_LABEL = 'clerum.io/host-uid'-export const EXECUTION_ROLE_LABEL = 'clerum.io/role'-export const EXECUTION_ROLE_VALUE = 'host-execution'--/**- * Server-owned annotations on the Job and the Pod template. Labels only select- * records; this pair is what proves which Host generation and which full- * execution contract the record was emitted for.- */-export const EXECUTION_HOST_GENERATION_ANNOTATION = 'clerum.io/host-generation'-export const EXECUTION_CONTRACT_FINGERPRINT_ANNOTATION = 'clerum.io/execution-fingerprint'--const WORKSPACE_VOLUME_NAME = 'workspace'-const INPUT_VOLUME_NAME = 'input'-const SCRATCH_VOLUME_NAME = 'scratch'-const RUN_AS_UID = 1001-const RUN_AS_GID = 1001-const MEBIBYTE = 1024 * 1024-/** Node working set the memory limit adds above the scratch volume and input. */-const EXECUTOR_MEMORY_BASE_BYTES = 256 * MEBIBYTE--const UUID_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}$/-const DNS1123_LABEL_PATTERN = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/-const DNS1123_SUBDOMAIN_PATTERN = /^[a-z0-9]([-a-z0-9.]*[a-z0-9])?$/-/** Lowercase image reference shape; the registry resolves the real authority. */-const IMAGE_REFERENCE_PATTERN = /^[a-z0-9][A-Za-z0-9._\-/:@]*$/--const REQUEST_KEYS = new Set(['kind', 'argv', 'timeoutMs', 'scratchBytes', 'input'])-const INPUT_KEYS = new Set(['byteLength', 'sha256'])--/**- * Server-resolved identity of the Host and of the single operation; only these- * resolved values reach the emitted Job.- */-export interface TrustedHostExecutionIdentity {- hostName: string- hostUid: string- namespace: string- operationId: string- hostGeneration: number- image: string- workspacePvcName: string- userKey: string- /** `workspace/` for the dual-subPath layout, `''` for the legacy PVC root. */- workspaceLayoutPrefix: 'workspace/' | ''-}--export interface ApprovedExecutionInput {- byteLength: number- sha256: string-}--/**- * Bounded request that an admission path already approved. The vector is- * executed as-is: no wrapper shell is added.- */-export interface ApprovedExecutionRequest {- kind: 'workspace' | 'attachment'- argv: string[]- timeoutMs: number- scratchBytes: number- input?: ApprovedExecutionInput-}--export class HostExecutionJobError extends Error {- constructor(- readonly field: string,- detail: string- ) {- super(`${field} ${detail}`)- this.name = 'HostExecutionJobError'- }-}--function fail(field: string, detail: string): never {- throw new HostExecutionJobError(field, detail)-}--function isRecord(value: unknown): value is Record<string, unknown> {- return typeof value === 'object' && value !== null && !Array.isArray(value)-}--function requireName(value: unknown, field: string, maxLength: number, pattern: RegExp): string {- if (- typeof value !== 'string' ||- value.length === 0 ||- value.length > maxLength ||- !pattern.test(value)- ) {- fail(field, `must be a 1..${maxLength} character DNS-1123 name`)- }- return value-}--function requireUuid(value: unknown, field: string): string {- if (typeof value !== 'string' || !UUID_PATTERN.test(value)) {- fail(field, 'must be a lowercase UUID')- }- return value-}--function requireBoundedInteger(value: unknown, field: string, min: number, max: number): number {- if (typeof value !== 'number' || !Number.isSafeInteger(value)) {- fail(field, 'must be a safe integer')- }- if (value < min || value > max) {- fail(field, `must be between ${min} and ${max}`)- }- return value-}--/**- * The executable must be non-empty; later entries may be legitimately empty- * arguments. NUL bytes are rejected and the aggregate UTF-8 size is bounded.- */-function requireArgv(value: unknown): string[] {- if (!Array.isArray(value) || value.length === 0) {- fail('request.argv', 'must be a non-empty argument vector')- }- let bytes = 0- const argv = value.map((entry, index) => {- if (typeof entry !== 'string') {- fail(`request.argv[${index}]`, 'must be a string')- }- if (index === 0 && entry.length === 0) {- fail('request.argv[0]', 'must be a non-empty executable')- }- if (entry.includes('\0')) {- fail(`request.argv[${index}]`, 'must not contain a NUL byte')- }- bytes += Buffer.byteLength(entry, 'utf8')- return entry- })- if (bytes > EXECUTION_ARGV_MAX_BYTES) {- fail('request.argv', `must total at most ${EXECUTION_ARGV_MAX_BYTES} UTF-8 bytes`)- }- return argv-}--function requireInput(value: unknown): ApprovedExecutionInput {- if (!isRecord(value)) {- fail('request.input', 'must be an object')- }- for (const key of Object.keys(value)) {- if (!INPUT_KEYS.has(key)) {- fail(`request.input.${key}`, 'is not part of the approved input contract')- }- }- const byteLength = requireBoundedInteger(- value.byteLength,- 'request.input.byteLength',- 0,- EXECUTION_INPUT_MAX_BYTES- )- if (typeof value.sha256 !== 'string' || !SHA256_PATTERN.test(value.sha256)) {- fail('request.input.sha256', 'must be a lowercase SHA-256 hex digest')- }- return { byteLength, sha256: value.sha256 }-}--function resolveIdentity(value: TrustedHostExecutionIdentity): TrustedHostExecutionIdentity {- if (!isRecord(value)) {- fail('identity', 'must be an object')- }- const {- hostName,- hostUid,- namespace,- operationId,- hostGeneration,- image,- workspacePvcName,- userKey,- workspaceLayoutPrefix,- } = value- requireName(hostName, 'identity.hostName', 253, DNS1123_SUBDOMAIN_PATTERN)- requireUuid(hostUid, 'identity.hostUid')- requireName(namespace, 'identity.namespace', 63, DNS1123_LABEL_PATTERN)- requireUuid(operationId, 'identity.operationId')- requireBoundedInteger(hostGeneration, 'identity.hostGeneration', 1, Number.MAX_SAFE_INTEGER)- if (- typeof image !== 'string' ||- image.length === 0 ||- image.length > 512 ||- !IMAGE_REFERENCE_PATTERN.test(image)- ) {- fail('identity.image', 'must be a 1..512 character lowercase container image reference')- }- requireName(workspacePvcName, 'identity.workspacePvcName', 253, DNS1123_SUBDOMAIN_PATTERN)- if (typeof userKey !== 'string' || (userKey !== '_system' && !/^[0-9a-f]{16}$/.test(userKey))) {- fail('identity.userKey', "must be 16 lowercase hex characters or '_system'")- }- if (workspaceLayoutPrefix !== 'workspace/' && workspaceLayoutPrefix !== '') {- fail('identity.workspaceLayoutPrefix', "must be 'workspace/' or ''")- }- return {- hostName,- hostUid,- namespace,- operationId,- hostGeneration,- image,- workspacePvcName,- userKey,- workspaceLayoutPrefix,- }-}--type ResolvedExecutionRequest =- | { kind: 'workspace'; argv: string[]; timeoutMs: number; scratchBytes: number }- | {- kind: 'attachment'- argv: string[]- timeoutMs: number- scratchBytes: number- input: ApprovedExecutionInput- }--/** The strict key check is what keeps a PVC or image override out of the spec. */-function resolveRequest(value: ApprovedExecutionRequest): ResolvedExecutionRequest {- if (!isRecord(value)) {- fail('request', 'must be an object')- }- for (const key of Object.keys(value)) {- if (!REQUEST_KEYS.has(key)) {- fail(`request.${key}`, 'is not part of the approved execution request')- }- }- const kind = value.kind- if (kind !== 'workspace' && kind !== 'attachment') {- fail('request.kind', "must be 'workspace' or 'attachment'")- }- const argv = requireArgv(value.argv)- const timeoutMs = requireBoundedInteger(- value.timeoutMs,- 'request.timeoutMs',- EXECUTION_TIMEOUT_MIN_MS,- EXECUTION_TIMEOUT_MAX_MS- )- const scratchBytes = requireBoundedInteger(- value.scratchBytes,- 'request.scratchBytes',- EXECUTION_SCRATCH_MIN_BYTES,- EXECUTION_SCRATCH_MAX_BYTES- )- if (kind === 'workspace') {- if (value.input !== undefined) {- fail('request.input', 'is only valid for an attachment operation')- }- return { kind, argv, timeoutMs, scratchBytes }- }- if (value.input === undefined) {- fail('request.input', 'is required for an attachment operation')- }- return { kind, argv, timeoutMs, scratchBytes, input: requireInput(value.input) }-}--function containerSecurityContext(): k8s.V1SecurityContext {- return {- allowPrivilegeEscalation: false,- privileged: false,- readOnlyRootFilesystem: true,- runAsNonRoot: true,- runAsUser: RUN_AS_UID,- runAsGroup: RUN_AS_GID,- capabilities: { drop: ['ALL'] },- seccompProfile: { type: 'RuntimeDefault' },- }-}--/** Deterministic Job name; the operation UUID is the only variable part. */-export function hostExecutionJobName(operationId: string): string {- return `host-exec-${operationId}`-}--/** The effective request parameters, in one fixed order. */-function requestParts(request: ResolvedExecutionRequest): unknown[] {- return [- request.kind,- request.argv,- request.timeoutMs,- request.scratchBytes,- request.kind === 'attachment' ? [request.input.byteLength, request.input.sha256] : null,- ]-}--/** The server-resolved identity fields the emitted Job depends on. */-function identityParts(identity: TrustedHostExecutionIdentity): unknown[] {- return [- identity.hostName,- identity.hostUid,- identity.namespace,- identity.hostGeneration,- identity.operationId,- identity.image,- identity.workspacePvcName,- identity.userKey,- identity.workspaceLayoutPrefix,- ]-}--function fingerprintOf(parts: unknown[]): string {- return createHash('sha256').update(JSON.stringify(parts)).digest('hex')-}--/** SHA-256 over one approved request, independent of any Host identity. */-export function hostExecutionRequestFingerprint(request: ApprovedExecutionRequest): string {- return fingerprintOf(requestParts(resolveRequest(request)))-}--/**- * SHA-256 over the server-resolved identity plus the normalized request the Job- * actually emits. A re-read proves the record was emitted for exactly this- * contract: Host object and generation, operation, image, workspace PVC, layout- * and user, and the approved arguments. It is not isolation proof.- */-export function hostExecutionContractFingerprint(- identity: TrustedHostExecutionIdentity,- request: ApprovedExecutionRequest-): string {- return fingerprintOf([- identityParts(resolveIdentity(identity)),- requestParts(resolveRequest(request)),- ])-}--/**- * Builds the Job for one approved operation; any unknown request field, invalid- * name or out-of-bound integer rejects the request before a Job exists.- */-export function buildHostExecutionJob(- identity: TrustedHostExecutionIdentity,- request: ApprovedExecutionRequest-): k8s.V1Job {- const resolved = resolveIdentity(identity)- const approved = resolveRequest(request)-- const labels: Record<string, string> = {- [MANAGED_BY_LABEL]: MANAGED_BY_VALUE,- [EXECUTION_OPERATION_LABEL]: resolved.operationId,- [EXECUTION_HOST_UID_LABEL]: resolved.hostUid,- [EXECUTION_ROLE_LABEL]: EXECUTION_ROLE_VALUE,- }- const annotations: Record<string, string> = {- [EXECUTION_HOST_GENERATION_ANNOTATION]: String(resolved.hostGeneration),- [EXECUTION_CONTRACT_FINGERPRINT_ANNOTATION]: fingerprintOf([- identityParts(resolved),- requestParts(approved),- ]),- }- // /scratch and /tmp are the same volume, so scratchBytes is the aggregate- // hard bound for both paths.- const scratchVolume: k8s.V1Volume = {- name: SCRATCH_VOLUME_NAME,- emptyDir: { medium: 'Memory', sizeLimit: String(approved.scratchBytes) },- }- const scratchMounts: k8s.V1VolumeMount[] = [- { name: SCRATCH_VOLUME_NAME, mountPath: EXECUTION_SCRATCH_MOUNT_PATH, readOnly: false },- { name: SCRATCH_VOLUME_NAME, mountPath: EXECUTION_TMP_MOUNT_PATH, readOnly: false },- ]-- const workingDir =- approved.kind === 'workspace' ? EXECUTION_WORKSPACE_MOUNT_PATH : EXECUTION_SCRATCH_MOUNT_PATH- const executorMounts: k8s.V1VolumeMount[] =- approved.kind === 'workspace'- ? [- {- name: WORKSPACE_VOLUME_NAME,- mountPath: EXECUTION_WORKSPACE_MOUNT_PATH,- // One explicit user workspace subdirectory: never the PVC root,- // never `users/`, never `state/`.- subPath: `${resolved.workspaceLayoutPrefix}users/${resolved.userKey}`,- readOnly: false,- },- ...scratchMounts,- ]- : [- {- name: INPUT_VOLUME_NAME,- mountPath: EXECUTION_INPUT_MOUNT_PATH,- // The receiver is the only writer; the executor can never rewrite- // the published input.- readOnly: true,- },- ...scratchMounts,- ]-- const volumes: k8s.V1Volume[] = [scratchVolume]- let initContainers: k8s.V1Container[] | undefined-- if (approved.kind === 'workspace') {- volumes.unshift({- name: WORKSPACE_VOLUME_NAME,- persistentVolumeClaim: { claimName: resolved.workspacePvcName, readOnly: false },- })- } else {- volumes.unshift({- name: INPUT_VOLUME_NAME,- emptyDir: { medium: 'Memory', sizeLimit: String(EXECUTION_INPUT_MAX_BYTES) },- })- initContainers = [- {- name: EXECUTION_INPUT_RECEIVER_CONTAINER_NAME,- image: resolved.image,- command: [- 'node',- EXECUTION_RECEIVE_INPUT_ENTRYPOINT,- String(approved.input.byteLength),- approved.input.sha256,- String(approved.timeoutMs),- ],- // 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 },- ],- resources: {- requests: { cpu: '50m', memory: '32Mi' },- limits: { cpu: '250m', memory: '256Mi' },- },- securityContext: containerSecurityContext(),- },- ]- }-- const executor: k8s.V1Container = {- name: EXECUTION_EXECUTOR_CONTAINER_NAME,- image: resolved.image,- // The fixed /bin/sh launcher execs Node with the approved vector as literal- // positional parameters (never interpolated into shell source) and points- // the wrapper's stdout/stderr at /dev/null before exec, so PID 1 exposes no- // container output descriptors to a same-UID child.- command: [- '/bin/sh',- '-c',- EXECUTION_RUN_LAUNCHER_SCRIPT,- 'node',- EXECUTION_RUN_ENTRYPOINT,- String(approved.timeoutMs),- ...approved.argv,- ],- workingDir,- // Fixed server-owned, non-secret values only; `serviceLinks` stays disabled- // so the API server cannot inject service environment into this pod.- 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' },- limits: {- cpu: '1',- // The single scratch volume, the maximum input and the Node working set- // are the only unbounded-looking consumers; this covers all three.- memory: `${Math.ceil(- (EXECUTOR_MEMORY_BASE_BYTES + EXECUTION_INPUT_MAX_BYTES + approved.scratchBytes) /- MEBIBYTE- )}Mi`,- },- },- securityContext: containerSecurityContext(),- }-- const podSpec: k8s.V1PodSpec = {- restartPolicy: 'Never',- automountServiceAccountToken: false,- enableServiceLinks: false,- hostPID: false,- hostIPC: false,- hostNetwork: false,- shareProcessNamespace: false,- securityContext: {- runAsNonRoot: true,- runAsUser: RUN_AS_UID,- runAsGroup: RUN_AS_GID,- fsGroup: RUN_AS_GID,- seccompProfile: { type: 'RuntimeDefault' },- },- ...(initContainers ? { initContainers } : {}),- containers: [executor],- volumes,- }-- return {- apiVersion: 'batch/v1',- kind: 'Job',- metadata: {- // The operation UUID keeps the name unambiguous; the prefix keeps the- // generated pod name inside the 63-character label bound.- name: hostExecutionJobName(resolved.operationId),- namespace: resolved.namespace,- labels,- annotations,- ownerReferences: [- {- apiVersion: HOST_OWNER_API_VERSION,- kind: 'Host',- name: resolved.hostName,- uid: resolved.hostUid,- controller: true,- },- ],- },- spec: {- backoffLimit: 0,- // A terminated Pod can retain the private input volume after a caller- // disconnects. Native Job TTL cleanup collects finished/deadline-failed- // Jobs and their dependent Pods; API absence still is not purge proof.- ttlSecondsAfterFinished: 0,- // 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,- },- },- }-}--export type HostExecutionRecordErrorCode =- | 'job_record_invalid'- | 'job_identity_mismatch'- | 'job_owner_mismatch'- | 'job_generation_mismatch'- | 'job_contract_mismatch'- | 'job_uid_replaced'- | 'pod_record_invalid'- | 'pod_namespace_mismatch'- | 'pod_owner_mismatch'- | 'pod_uid_replaced'--export class HostExecutionRecordError extends Error {- constructor(readonly code: HostExecutionRecordErrorCode) {- super(code)- this.name = 'HostExecutionRecordError'- }-}--function failRecord(code: HostExecutionRecordErrorCode): never {- throw new HostExecutionRecordError(code)-}--interface RecordMetadata {- name: string- namespace: string- uid: string- annotations: Record<string, unknown>- ownerReferences: k8s.V1OwnerReference[]-}--function requireRecordMetadata(- record: unknown,- code: HostExecutionRecordErrorCode-): RecordMetadata {- const metadata = (record as { metadata?: unknown } | null | undefined)?.metadata- if (typeof metadata !== 'object' || metadata === null) failRecord(code)- const { name, namespace, uid, annotations, ownerReferences } = metadata as Record<string, unknown>- if (- typeof name !== 'string' ||- name.length === 0 ||- typeof namespace !== 'string' ||- namespace.length === 0 ||- typeof uid !== 'string' ||- uid.length === 0- ) {- failRecord(code)- }- if (annotations !== undefined && (typeof annotations !== 'object' || annotations === null)) {- failRecord(code)- }- if (ownerReferences !== undefined && !Array.isArray(ownerReferences)) failRecord(code)- return {- name,- namespace,- uid,- annotations: (annotations as Record<string, unknown> | undefined) ?? {},- ownerReferences: (ownerReferences as k8s.V1OwnerReference[] | undefined) ?? [],- }-}--/** Exactly one owner of the expected kind; a second candidate is ambiguous. */-function requireExactOwner(- ownerReferences: k8s.V1OwnerReference[],- apiVersion: string,- kind: string,- code: HostExecutionRecordErrorCode-): k8s.V1OwnerReference {- const owners = ownerReferences.filter(- ref => ref && ref.apiVersion === apiVersion && ref.kind === kind- )- if (owners.length !== 1) failRecord(code)- return owners[0]-}--/**- * Validates a Job re-read from the API against the approved identity and- * request. Labels select a record; only the deterministic name, the exact Host- * ownerReference and the server-owned annotations prove it. Pass the UID bound- * by an earlier validation to reject a replaced Job.- */-export function validateHostExecutionJob(- job: k8s.V1Job,- identity: TrustedHostExecutionIdentity,- request: ApprovedExecutionRequest,- expectedUid?: string-): void {- const resolved = resolveIdentity(identity)- const fingerprint = hostExecutionContractFingerprint(resolved, request)- const metadata = requireRecordMetadata(job, 'job_record_invalid')- if (expectedUid !== undefined && metadata.uid !== expectedUid) failRecord('job_uid_replaced')- if (- metadata.namespace !== resolved.namespace ||- metadata.name !== hostExecutionJobName(resolved.operationId)- ) {- failRecord('job_identity_mismatch')- }- const owner = requireExactOwner(- metadata.ownerReferences,- HOST_OWNER_API_VERSION,- 'Host',- 'job_owner_mismatch'- )- if (- owner.name !== resolved.hostName ||- owner.uid !== resolved.hostUid ||- owner.controller !== true- ) {- failRecord('job_owner_mismatch')- }- if (- metadata.annotations[EXECUTION_HOST_GENERATION_ANNOTATION] !== String(resolved.hostGeneration)- ) {- failRecord('job_generation_mismatch')- }- if (metadata.annotations[EXECUTION_CONTRACT_FINGERPRINT_ANNOTATION] !== fingerprint) {- failRecord('job_contract_mismatch')- }-}--/**- * Validates the Pod the caller is about to attach to or log for: it must be- * owned by the exact validated Job UID, in the Job's namespace. The Job is- * validated first so the chain can never start from an unproven record. Pass- * the pod UID bound by an earlier validation to reject a replaced Pod.- */-export function validateHostExecutionPod(- pod: k8s.V1Pod,- job: k8s.V1Job,- identity: TrustedHostExecutionIdentity,- request: ApprovedExecutionRequest,- expectedPodUid?: string-): void {- validateHostExecutionJob(job, identity, request)- const jobMetadata = requireRecordMetadata(job, 'job_record_invalid')- const podMetadata = requireRecordMetadata(pod, 'pod_record_invalid')- if (expectedPodUid !== undefined && podMetadata.uid !== expectedPodUid) {- failRecord('pod_uid_replaced')- }- if (podMetadata.namespace !== jobMetadata.namespace) failRecord('pod_namespace_mismatch')- const owner = requireExactOwner(- podMetadata.ownerReferences,- 'batch/v1',- 'Job',- 'pod_owner_mismatch'- )- if (- owner.name !== jobMetadata.name ||- owner.uid !== jobMetadata.uid ||- owner.controller !== true- ) {- failRecord('pod_owner_mismatch')- }-}diff --git a/host-context-controller/src/hostExecution/networkPolicy.test.ts b/host-context-controller/src/hostExecution/networkPolicy.test.tsdeleted file mode 100644index 635bbf50a..000000000--- a/host-context-controller/src/hostExecution/networkPolicy.test.ts+++ /dev/null@@ -1,84 +0,0 @@-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.tsdeleted file mode 100644index be724775d..000000000--- a/host-context-controller/src/hostExecution/operations.test.ts+++ /dev/null@@ -1,412 +0,0 @@-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 ApprovedExecutionRequest,- type TrustedHostExecutionIdentity,- buildHostExecutionJob,-} from './jobFactory'-import { HostExecutionOperations } from './operations'--const identity: TrustedHostExecutionIdentity = {- hostName: 'chatllm',- hostUid: '00000000-1111-4111-8111-000000000001',- namespace: 'mcp-host',- hostGeneration: 7,- operationId: '00000000-1111-4111-8111-000000000002',- image: 'clerum/mcp-host:dev',- workspacePvcName: 'chatllm-workspace',- userKey: '0123456789abcdef',- workspaceLayoutPrefix: 'workspace/',-}-const principal: VerifiedMcpHostPrincipal = {- subject: 'mcp-host/standalone',- hostName: identity.hostName,- hostUid: identity.hostUid,- namespace: identity.namespace,- jti: 'execution-unit-test',- issuedAt: Math.floor(Date.now() / 1000),- expiresAt: Math.floor(Date.now() / 1000) + 600,- audiences: ['host-context-controller'],- nativeExecutionAllowed: true,-}-const request = {- kind: 'workspace' as const,- argv: ['/bin/sh', '-c', 'printf approved'],- timeoutMs: 1_500_000,- scratchBytes: 1_048_576,-}-const jobUid = '00000000-1111-4111-8111-000000000003'-const podUid = '00000000-1111-4111-8111-000000000004'-const capturedResult = {- reason: 'exited',- exitCode: 0,- signal: null,- truncated: false,- stdout: Buffer.from('approved').toString('base64'),- stderr: '',-}--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, approvedRequest)- job.metadata!.uid = jobUid- const pod: k8s.V1Pod = {- metadata: {- name: 'host-exec-pod',- namespace: identity.namespace,- uid: podUid,- ownerReferences: [- {- apiVersion: 'batch/v1',- kind: 'Job',- name: job.metadata!.name!,- uid: jobUid,- controller: true,- },- ],- },- status: {- podIP: '10.244.0.7',- containerStatuses: [- {- name: 'executor',- image: identity.image,- imageID: 'unit-image',- ready: true,- restartCount: 0,- state: { running: {} },- },- ],- },- }- const missing = () => Object.assign(new Error('not found'), { code: 404 })- const batch = {- createNamespacedJob: vi.fn(async (_request: unknown) => job!),- readNamespacedJob: vi.fn(async (_request: unknown) => {- if (!job) throw missing()- return job- }),- deleteNamespacedJob: vi.fn(async (_request: unknown) => {- job = null- return {}- }),- }- let pods = [pod]- const core = {- listNamespacedPod: vi.fn(async (_request: unknown) => ({ items: pods })),- readNamespacedPod: vi.fn(async (_request: unknown) => pod),- }- 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,- results,- inputs- )- return {- operations,- batch,- core,- results,- inputs,- pod,- getJob: () => job!,- setJob: (value: k8s.V1Job | null) => {- job = value- },- setHost: (value: HostExecutionHostRecord | null) => {- host = value- },- setPods: (value: k8s.V1Pod[]) => {- pods = value- },- }-}--describe('Host execution operations', () => {- it('creates an approved Job and retains its immutable UID and original authority', async () => {- const f = fixture()- const handle = await f.operations.start(principal, identity, request)- expect(f.batch.createNamespacedJob.mock.calls[0]?.[0]).toEqual({- namespace: identity.namespace,- body: buildHostExecutionJob(identity, request),- })- expect(handle.jobUid).toBe(jobUid)- expect(handle.identity.hostGeneration).toBe(7)- expect(Object.isFrozen(handle)).toBe(true)- expect(Object.isFrozen(handle.request.argv)).toBe(true)- })-- it('rejects a caller generation or Host binding mismatch before creating anything', async () => {- for (const changed of [- { ...identity, hostGeneration: 8 },- { ...identity, namespace: 'foreign' },- { ...identity, hostUid: '00000000-1111-4111-8111-000000000099' },- ]) {- const f = fixture()- await expect(f.operations.start(principal, changed, request)).rejects.toThrow(- 'execution_binding_mismatch'- )- expect(f.batch.createNamespacedJob).not.toHaveBeenCalled()- }- })-- it('withholds a start receipt if the Host changes while creation is pending', async () => {- const f = fixture()- f.batch.createNamespacedJob.mockImplementationOnce(async () => {- f.setHost({- name: identity.hostName,- namespace: identity.namespace,- uid: identity.hostUid,- generation: 8,- })- return f.getJob()- })- await expect(f.operations.start(principal, identity, request)).rejects.toThrow(- 'host_generation_changed'- )- expect(f.batch.deleteNamespacedJob).toHaveBeenCalledWith(- expect.objectContaining({- body: { propagationPolicy: 'Foreground', preconditions: { uid: jobUid } },- })- )- })-- it('reads bounded output with a renewed same-binding token and never remints the Job', async () => {- const f = fixture()- const handle = await f.operations.start(principal, identity, request)- 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.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.results.read.mockImplementationOnce(async () => {- f.setHost({- name: identity.hostName,- namespace: identity.namespace,- uid: identity.hostUid,- generation: 8,- })- return 'unpublished private result'- })- await expect(f.operations.inspect(principal, handle)).rejects.toThrow('host_generation_changed')- })-- it('denies a replaced Job or foreign Pod before reading any output', async () => {- for (const change of ['job', 'pod']) {- const f = fixture()- const handle = await f.operations.start(principal, identity, request)- if (change === 'job') f.getJob().metadata!.uid = 'replaced-job'- else f.pod.metadata!.ownerReferences![0].uid = 'foreign-job'- await expect(f.operations.inspect(principal, handle)).rejects.toThrow(- change === 'job' ? 'job_uid_replaced' : 'pod_owner_mismatch'- )- expect(f.results.read).not.toHaveBeenCalled()- }- })-- 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.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.results.read.mockResolvedValueOnce('x'.repeat(100_000))- await expect(f.operations.inspect(principal, handle)).rejects.toThrow(- 'execution_result_invalid'- )- })-- it('reports cleanup pending until the Job and its exact owned Pods are absent', async () => {- const f = fixture()- const handle = await f.operations.start(principal, identity, request)- await expect(f.operations.cancel(principal, handle)).resolves.toEqual({- state: 'cleanup_pending',- })- expect(f.batch.deleteNamespacedJob).toHaveBeenCalledWith({- namespace: identity.namespace,- name: 'host-exec-' + identity.operationId,- body: { propagationPolicy: 'Foreground', preconditions: { uid: jobUid } },- })- f.setPods([])- await expect(f.operations.cancel(principal, handle)).resolves.toEqual({- state: 'workloads_absent',- })- expect(f.batch.deleteNamespacedJob).toHaveBeenCalledTimes(1)- })-- it('never deletes a replacement and never turns a non-404 failure into absence', async () => {- const f = fixture()- const handle = await f.operations.start(principal, identity, request)- f.getJob().metadata!.uid = 'replacement'- await expect(f.operations.cancel(principal, handle)).rejects.toThrow('job_uid_replaced')- expect(f.batch.deleteNamespacedJob).not.toHaveBeenCalled()- f.batch.readNamespacedJob.mockRejectedValueOnce(- Object.assign(new Error('API unavailable'), { code: 503 })- )- await expect(f.operations.cancel(principal, handle)).rejects.toThrow('API unavailable')- })-- it('withholds results when the Pod is replaced during retrieval', async () => {- const f = fixture()- const handle = await f.operations.start(principal, identity, request)- f.results.read.mockImplementationOnce(async () => {- f.pod.metadata!.uid = 'replacement-pod'- return 'output from a replaced pod'- })- await expect(f.operations.inspect(principal, handle)).rejects.toThrow('pod_uid_replaced')- })-- it('does not certify absence from an incomplete Pod inventory', async () => {- const f = fixture()- const handle = await f.operations.start(principal, identity, request)- f.core.listNamespacedPod.mockResolvedValueOnce({- items: [],- metadata: { _continue: 'more-pods' },- } as never)- await expect(f.operations.inspect(principal, handle)).rejects.toThrow(- '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.tsdeleted file mode 100644index a3bb83839..000000000--- a/host-context-controller/src/hostExecution/operations.ts+++ /dev/null@@ -1,284 +0,0 @@-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,- EXECUTION_INPUT_RECEIVER_CONTAINER_NAME,- type TrustedHostExecutionIdentity,- buildHostExecutionJob,- hostExecutionJobName,- validateHostExecutionJob,- validateHostExecutionPod,-} from './jobFactory'-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'>--/** Internal receipt retained with the prepared operation, never reconstructed- * from a new upload or a caller-selected Host name. Contains no bearer token.- */-export interface HostExecutionHandle {- readonly identity: Readonly<TrustedHostExecutionIdentity>- readonly request: Readonly<ApprovedExecutionRequest>- readonly jobUid: string-}--export type HostExecutionObservation =- | { state: 'queued' }- | { state: 'waiting_for_input' | 'running'; podUid: string }- | { state: 'failed'; podUid: string; reason: 'input_receive_failed' | 'execution_terminated' }- | { state: 'completed'; podUid: string; result: HostExecutionResult }--function bindingFor(identity: TrustedHostExecutionIdentity): HostExecutionBinding {- return {- hostName: identity.hostName,- hostUid: identity.hostUid,- namespace: identity.namespace,- generation: identity.hostGeneration,- }-}--function snapshot(- identity: TrustedHostExecutionIdentity,- request: ApprovedExecutionRequest,- jobUid: string-): HostExecutionHandle {- const copiedRequest = {- ...request,- argv: [...request.argv],- ...(request.input ? { input: { ...request.input } } : {}),- }- Object.freeze(copiedRequest.argv)- if (copiedRequest.input) Object.freeze(copiedRequest.input)- return Object.freeze({- identity: Object.freeze({ ...identity }),- request: Object.freeze(copiedRequest),- jobUid,- })-}--/**- * Finite Kubernetes clients must use makeHostK8sApiClient at composition time.- * Each HTTP operation supplies a freshly verified principal. A 25-minute Job- * therefore does not depend on keeping its original 10-minute JWT alive.- * This backend does not mint scopes, install routes or activate shell tools.- */-export class HostExecutionOperations {- constructor(- private readonly batch: BatchApi,- private readonly core: CoreApi,- private readonly authorization: HostExecutionAuthorization,- private readonly results: Pick<ExecutionResultTransport, 'read' | 'clear'>,- private readonly inputs: Pick<ExecutionInputTransport, 'ready' | 'send'>- ) {}-- async start(- principal: VerifiedMcpHostPrincipal,- identity: TrustedHostExecutionIdentity,- request: ApprovedExecutionRequest- ): Promise<HostExecutionHandle> {- const prepared = snapshot(identity, request, '')- const body = buildHostExecutionJob(prepared.identity, prepared.request)- const binding = await this.authorization.authorize(principal)- if (- binding.hostName !== prepared.identity.hostName ||- binding.namespace !== prepared.identity.namespace ||- binding.hostUid !== prepared.identity.hostUid ||- binding.generation !== prepared.identity.hostGeneration- ) {- throw new Error('execution_binding_mismatch')- }- const created = await observeCreate('Job', () =>- this.batch.createNamespacedJob({ namespace: binding.namespace, body })- )- validateHostExecutionJob(created, prepared.identity, prepared.request)- const handle = snapshot(prepared.identity, prepared.request, created.metadata!.uid!)- try {- await this.authorization.revalidate(principal, binding)- } catch (error) {- // No receipt or output is published under revoked authority. Foreground- // deletion starts cleanup; it is not a claim that all Pods are gone.- await this.deleteExactJob(handle)- throw error- }- return handle- }-- private async readJob(handle: HostExecutionHandle): Promise<k8s.V1Job | null> {- let job: k8s.V1Job- try {- job = await observeExistenceRead('Job', () =>- this.batch.readNamespacedJob({- name: hostExecutionJobName(handle.identity.operationId),- namespace: handle.identity.namespace,- })- )- } catch (error) {- if (getErrorCode(error) === 404) return null- throw error- }- validateHostExecutionJob(job, handle.identity, handle.request, handle.jobUid)- return job- }-- private async readPods(handle: HostExecutionHandle): Promise<k8s.V1Pod[]> {- const pods = await this.core.listNamespacedPod({- namespace: handle.identity.namespace,- labelSelector: `batch.kubernetes.io/controller-uid=${handle.jobUid}`,- limit: 2,- })- // The Job has backoffLimit=0 and no parallelism. An ambiguous or partial- // inventory must never produce output or a workload-absence receipt.- if (pods.metadata?._continue || pods.items.length > 1) {- throw new Error('execution_pod_inventory_ambiguous')- }- 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- ): Promise<HostExecutionObservation> {- const binding = bindingFor(handle.identity)- await this.authorization.revalidate(principal, binding)- 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 === 0) return { state: 'queued' }- const pod = pods[0]- validateHostExecutionPod(pod, job, handle.identity, handle.request)- const podUid = pod.metadata!.uid!- const executor = pod.status?.containerStatuses?.find(- container => container.name === EXECUTION_EXECUTOR_CONTAINER_NAME- )- 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- ? 'waiting_for_input'- : 'running',- podUid,- }- }- if (!executor.ready) return { state: 'running', podUid }- const podName = pod.metadata!.name!- 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.- await this.revalidatePod(handle, podName, podUid)- await this.authorization.revalidate(principal, binding)- if (output === null) return { state: 'running', podUid }- return {- state: 'completed',- podUid,- result: parseHostExecutionResult(output),- }- }-- private async deleteExactJob(handle: HostExecutionHandle): Promise<void> {- await this.batch.deleteNamespacedJob({- name: hostExecutionJobName(handle.identity.operationId),- namespace: handle.identity.namespace,- body: { propagationPolicy: 'Foreground', preconditions: { uid: handle.jobUid } },- })- }-- async cancel(- principal: VerifiedMcpHostPrincipal,- handle: HostExecutionHandle- ): Promise<{ state: 'cleanup_pending' | 'workloads_absent' }> {- const binding = bindingFor(handle.identity)- await this.authorization.revalidate(principal, binding)- const job = await this.readJob(handle)- // Job validation includes the original UID; DELETE also carries its UID- // precondition to close a replacement race after the read.- if (job && !job.metadata?.deletionTimestamp) await this.deleteExactJob(handle)- const remainingJob = await this.readJob(handle)- const pods = await this.readPods(handle)- await this.authorization.revalidate(principal, binding)- // API absence is a workload observation. The file-store lifecycle must- // separately prove removal of staging, cached results and materializations- // before releasing its physical-cleanup fence or storage reservation.- return { state: remainingJob || pods.length ? 'cleanup_pending' : 'workloads_absent' }- }-}diff --git a/host-context-controller/src/hostExecution/result.test.ts b/host-context-controller/src/hostExecution/result.test.tsdeleted file mode 100644index 4672bb50c..000000000--- a/host-context-controller/src/hostExecution/result.test.ts+++ /dev/null@@ -1,54 +0,0 @@-import { describe, expect, it } from 'vitest'-import { EXECUTION_RESULT_MAX_BYTES, parseHostExecutionResult } from './result'--const result = {- reason: 'exited',- exitCode: 7,- signal: null,- truncated: false,- stdout: Buffer.from([0, 255, 128, 10]).toString('base64'),- stderr: '',-}--describe('execution result protocol', () => {- it('preserves arbitrary bytes and the actual command status', () => {- const parsed = parseHostExecutionResult(JSON.stringify(result) + '\n')- expect(parsed).toEqual(result)- expect(Buffer.from(parsed.stdout, 'base64')).toEqual(Buffer.from([0, 255, 128, 10]))- expect(Object.isFrozen(parsed)).toBe(true)- })-- it('accepts the maximum aggregate bytes even when split between streams', () => {- const maximum = {- ...result,- stdout: Buffer.alloc(32_768, 255).toString('base64'),- stderr: Buffer.alloc(32_768, 0).toString('base64'),- }- expect(Buffer.byteLength(JSON.stringify(maximum))).toBeLessThan(EXECUTION_RESULT_MAX_BYTES)- expect(parseHostExecutionResult(JSON.stringify(maximum))).toEqual(maximum)- })-- it('rejects oversized, truncated, concatenated or forged frames', () => {- for (const frame of [- '{',- JSON.stringify(result).slice(0, -1),- JSON.stringify(result).repeat(2),- ' '.repeat(EXECUTION_RESULT_MAX_BYTES + 1),- JSON.stringify({ ...result, injected: true }),- JSON.stringify({ ...result, reason: 'approved' }),- JSON.stringify({ ...result, exitCode: -1 }),- JSON.stringify({ ...result, exitCode: 256 }),- JSON.stringify({ ...result, signal: 'unbounded private exception' }),- JSON.stringify({ ...result, stdout: 'not-base64' }),- JSON.stringify({ ...result, stdout: 'YQ' }),- JSON.stringify({ ...result, truncated: 'true' }),- JSON.stringify({ ...result, stdout: Buffer.alloc(65_537).toString('base64') }),- JSON.stringify({- ...result,- stdout: Buffer.alloc(65_536).toString('base64'),- stderr: 'YQ==',- }),- ])- expect(() => parseHostExecutionResult(frame)).toThrow('execution_result_invalid')- })-})diff --git a/host-context-controller/src/hostExecution/result.ts b/host-context-controller/src/hostExecution/result.tsdeleted file mode 100644index fd48d9f7a..000000000--- a/host-context-controller/src/hostExecution/result.ts+++ /dev/null@@ -1,57 +0,0 @@-/** Result protocol emitted by the private execution launcher, not service logs. */-export interface HostExecutionResult {- reason: 'exited' | 'timeout' | 'output_limit' | 'spawn_failed' | 'invalid_contract'- exitCode: number | null- signal: string | null- truncated: boolean- stdout: string- stderr: string-}--export const EXECUTION_RESULT_MAX_BYTES = 98_304-const OUTPUT_MAX_BYTES = 65_536-const KEYS = ['reason', 'exitCode', 'signal', 'truncated', 'stdout', 'stderr']-const REASONS = new Set(['exited', 'timeout', 'output_limit', 'spawn_failed', 'invalid_contract'])--function invalid(): never {- throw new Error('execution_result_invalid')-}--function decodedSize(value: unknown): number {- if (typeof value !== 'string' || value.length > 87_384) invalid()- if (Buffer.from(value, 'base64').toString('base64') !== value) invalid()- return Buffer.byteLength(value, 'base64')-}--/**- * Fail closed on an incomplete/oversized frame or a noncanonical binary field.- * Raw bytes never become text implicitly and a bad result never reruns a tool.- */-export function parseHostExecutionResult(frame: string): HostExecutionResult {- if (Buffer.byteLength(frame, 'utf8') > EXECUTION_RESULT_MAX_BYTES) invalid()- let value: unknown- try {- value = JSON.parse(frame)- } catch {- invalid()- }- if (!value || typeof value !== 'object' || Array.isArray(value)) invalid()- const result = value as Record<string, unknown>- if (Object.keys(result).length !== KEYS.length || KEYS.some(key => !(key in result))) invalid()- if (typeof result.reason !== 'string' || !REASONS.has(result.reason)) invalid()- if (- result.exitCode !== null &&- (!Number.isSafeInteger(result.exitCode) ||- (result.exitCode as number) < 0 ||- (result.exitCode as number) > 255)- )- invalid()- if (- result.signal !== null &&- (typeof result.signal !== 'string' || !/^SIG[A-Z0-9]{1,16}$/.test(result.signal))- )- invalid()- if (typeof result.truncated !== 'boolean') invalid()- if (decodedSize(result.stdout) + decodedSize(result.stderr) > OUTPUT_MAX_BYTES) invalid()- return Object.freeze(result) as unknown as HostExecutionResult-}diff --git a/host-context-controller/src/hostExecution/resultTransport.test.ts b/host-context-controller/src/hostExecution/resultTransport.test.tsdeleted file mode 100644index aad42e8e4..000000000--- a/host-context-controller/src/hostExecution/resultTransport.test.ts+++ /dev/null@@ -1,111 +0,0 @@-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.tsdeleted file mode 100644index 1b397bc0b..000000000--- a/host-context-controller/src/hostExecution/resultTransport.ts+++ /dev/null@@ -1,120 +0,0 @@-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/mcpApiAuthentication.test.ts b/host-context-controller/src/mcpApiAuthentication.test.tsindex 0f1cebd2f..e6f306364 100644--- a/host-context-controller/src/mcpApiAuthentication.test.ts+++ b/host-context-controller/src/mcpApiAuthentication.test.ts@@ -71,31 +71,6 @@ describe('McpApiAuthenticator', () => {expect(authenticate(sign({}, HCC_MCP_AUDIENCE)).audiences).toEqual([HCC_MCP_AUDIENCE])})- it('delegates native execution only when the verified Host token explicitly carries its scope', () => {- expect(authenticate(sign({ workflowControlScopes: ['host:tools:execute'] }))).toHaveProperty(- 'nativeExecutionAllowed',- true- )- expect(authenticate(sign())).not.toHaveProperty('nativeExecutionAllowed')- expect(- authenticator.authenticate({- authorization: `Bearer ${sign()}`,- 'x-clerum-native-execution': 'true',- })- ).not.toHaveProperty('nativeExecutionAllowed')- })-- it.each([- 'host:tools:execute',- ['host:tools:execute', 'host:tools:execute'],- ['host:tools:execute', null],- [' host:tools:execute'],- ])('does not promote a malformed signed scope list into execution authority', scopes => {- expect(authenticate(sign({ workflowControlScopes: scopes }))).not.toHaveProperty(- 'nativeExecutionAllowed'- )- })-it.each([[WORKFLOW_APPROVAL_AUDIENCE],[[HCC_MCP_AUDIENCE, WORKFLOW_APPROVAL_AUDIENCE, 'third-resource']],diff --git a/host-context-controller/src/mcpApiAuthentication.ts b/host-context-controller/src/mcpApiAuthentication.tsindex c4afaca92..d069b5f67 100644--- a/host-context-controller/src/mcpApiAuthentication.ts+++ b/host-context-controller/src/mcpApiAuthentication.ts@@ -4,8 +4,6 @@ import type { IncomingHttpHeaders } from 'node:http'export const HCC_MCP_AUDIENCE = 'host-context-controller'export const WORKFLOW_APPROVAL_AUDIENCE = 'workflow-approvals'-/** Internal execution transport; attaching a file never grants this scope. */-export const HOST_NATIVE_EXECUTION_SCOPE = 'host:tools:execute'export const MCP_CREDENTIAL_READ_CAPABILITY = 'mcp:credential:read'const HOST_NAME_RE = /^[a-z0-9]([-a-z0-9]*[a-z0-9])?$/@@ -19,8 +17,6 @@ export interface VerifiedMcpHostPrincipal {issuedAt: numberexpiresAt: numberaudiences: readonly string[]- /** Set only from a validated signed scope list, never from request headers. */- nativeExecutionAllowed?: true}export class McpApiAuthenticationError extends Error {@@ -71,17 +67,6 @@ function canonicalHostUid(value: unknown): string | null {return /[^A-Za-z0-9._:-]/.test(normalized) ? null : normalized}-function hasNativeExecutionScope(value: unknown): boolean {- return (- Array.isArray(value) &&- value.length > 0 &&- value.length <= 32 &&- value.every(scope => typeof scope === 'string' && /^[a-z][a-z0-9:_-]{0,63}$/.test(scope)) &&- new Set(value).size === value.length &&- value.includes(HOST_NATIVE_EXECUTION_SCOPE)- )-}-function bearerFromHeaders(headers: IncomingHttpHeaders, rawHeaders: readonly string[]): string {let authorizationCount = 0for (let index = 0; index < rawHeaders.length; index += 2) {@@ -201,9 +186,6 @@ export class McpApiAuthenticator {issuedAt: payload.iat as number,expiresAt: payload.exp as number,audiences,- ...(hasNativeExecutionScope(payload.workflowControlScopes)- ? { nativeExecutionAllowed: true as const }- : {}),}}}diff --git a/host-context-controller/src/metrics.ts b/host-context-controller/src/metrics.tsindex ac027416b..4be4dfa82 100644--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@ -301,7 +301,6 @@ export const hostFleetLifecycleCatchTotal = counter({// Outcomes partition completed creates; sum created, conflict, and error for// completed attempts. The bounded kind inventory includes the read-first Secret.export const CREATE_KINDS = [- 'Job','NetworkPolicy','Service','Deployment',diff --git a/host-context-controller/src/networkPolicyReconciler.test.ts b/host-context-controller/src/networkPolicyReconciler.test.tsindex 74992409e..b87f4b42b 100644--- a/host-context-controller/src/networkPolicyReconciler.test.ts+++ b/host-context-controller/src/networkPolicyReconciler.test.ts@@ -535,28 +535,6 @@ 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.tsindex a38749fee..01c7342de 100644--- a/host-context-controller/src/networkPolicyReconciler.ts+++ b/host-context-controller/src/networkPolicyReconciler.ts@@ -433,10 +433,7 @@ export function isPublicDnsHostname(host: string): boolean {function hccApiEgressPodSelector(namespace: string): k8s.V1LabelSelector {if (namespace === config.hostNamespace) {- return {- matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },- matchExpressions: [{ key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] }],- }+ return { matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE } }}if (namespace === config.namespace) {return { matchLabels: { app: 'mcp-proxy' } }@@ -452,10 +449,7 @@ function hccApiEgressPodSelector(namespace: string): k8s.V1LabelSelector {function k8sApiEgressPodSelector(namespace: string): k8s.V1LabelSelector {if (namespace === config.hostNamespace) {- return {- matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE },- matchExpressions: [{ key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] }],- }+ return { matchLabels: { [MANAGED_BY_LABEL]: MANAGED_BY_VALUE } }}// Runtime workload namespaces are deny-by-default for apiserver access. A@@ -729,14 +723,7 @@ export class NetworkPolicyReconciler {},},spec: {- podSelector:- namespace === config.hostNamespace- ? {- matchExpressions: [- { key: 'clerum.io/role', operator: 'NotIn', values: ['host-execution'] },- ],- }- : {},+ podSelector: {},policyTypes: ['Egress'],egress,},diff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex d74aa345a..e523568e4 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.488",+ "version": "0.1.489","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.488",+ "version": "0.1.489","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex cef9cdc9c..36bf0bf79 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.488",+ "version": "0.1.489","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/receiveInput.test.ts b/mcp-host/src/core/execution/receiveInput.test.tsdeleted file mode 100644index b61829b2f..000000000--- a/mcp-host/src/core/execution/receiveInput.test.ts+++ /dev/null@@ -1,102 +0,0 @@-import { afterEach, describe, expect, it } from 'vitest'-import { createHash } from 'node:crypto'-import { mkdtemp, readFile, readdir, rm, stat, symlink, writeFile } from 'node:fs/promises'-import { tmpdir } from 'node:os'-import { join } from 'node:path'-import { Readable } from 'node:stream'-import { EXECUTION_INPUT_MAX_BYTES, receiveExecutionInput } from './receiveInput'--const dirs: string[] = []-afterEach(async () => {- for (const dir of dirs.splice(0)) await rm(dir, { recursive: true, force: true })-})-async function root() {- const dir = await mkdtemp(join(tmpdir(), 'pr932-input-'))- dirs.push(dir)- return dir-}-function digest(bytes: Buffer) {- return createHash('sha256').update(bytes).digest('hex')-}--describe('private operation input receiver', () => {- it('streams exact arbitrary bytes into one read-only file and removes staging', async () => {- const dir = await root()- const bytes = Buffer.from([0, 255, 128, 1, 2, 3])- await receiveExecutionInput(- Readable.from([bytes.subarray(0, 2), bytes.subarray(2)]),- dir,- bytes.length,- digest(bytes),- 1000- )- expect(await readFile(join(dir, 'source'))).toEqual(bytes)- expect((await stat(join(dir, 'source'))).mode & 0o777).toBe(0o444)- expect(await readdir(dir)).toEqual(['source'])- })- it('accepts an exact empty input without inventing file content', async () => {- const dir = await root()- const bytes = Buffer.alloc(0)- await receiveExecutionInput(Readable.from([]), dir, 0, digest(bytes), 1000)- expect((await readFile(join(dir, 'source'))).length).toBe(0)- })- it.each(['short', 'long', 'wrong-digest'] as const)(- 'refuses %s input before publication and removes staging',- async mode => {- const dir = await root()- const bytes = Buffer.from('public original')- const body =- mode === 'short'- ? bytes.subarray(1)- : mode === 'long'- ? Buffer.concat([bytes, Buffer.from('x')])- : bytes- const expected =- mode === 'wrong-digest' ? digest(Buffer.from('different public original')) : digest(bytes)- await expect(- receiveExecutionInput(Readable.from([body]), dir, bytes.length, expected, 1000)- ).rejects.toThrow('mismatch')- expect(await readdir(dir)).toEqual([])- }- )- it('preserves an existing published input when the same operation is replayed', async () => {- const dir = await root()- const original = Buffer.from('published public input')- await writeFile(join(dir, 'source'), original)- const bytes = Buffer.from('replacement')- await expect(- receiveExecutionInput(Readable.from([bytes]), dir, bytes.length, digest(bytes), 1000)- ).rejects.toThrow()- expect(await readFile(join(dir, 'source'))).toEqual(original)- expect(await readdir(dir)).toEqual(['source'])- })- it('rejects a symlink root and out-of-bound contracts without creating files', async () => {- const dir = await root()- const target = await root()- await symlink(target, join(dir, 'link'))- const bytes = Buffer.from('public')- await expect(- receiveExecutionInput(- Readable.from([bytes]),- join(dir, 'link'),- bytes.length,- digest(bytes),- 1000- )- ).rejects.toThrow('directory')- for (const size of [-1, 1.5, EXECUTION_INPUT_MAX_BYTES + 1]) {- await expect(- receiveExecutionInput(Readable.from([bytes]), target, size, digest(bytes), 1000)- ).rejects.toThrow('contract')- }- expect(await readdir(target)).toEqual([])- })- it('terminates stalled input within its deadline and publishes no file', async () => {- const dir = await root()- const neverEnds = new Readable({ read() {} })- await expect(- receiveExecutionInput(neverEnds, dir, 1, digest(Buffer.from('x')), 25)- ).rejects.toThrow()- expect(await readdir(dir)).toEqual([])- })-})diff --git a/mcp-host/src/core/execution/receiveInput.ts b/mcp-host/src/core/execution/receiveInput.tsdeleted file mode 100644index 845b04828..000000000--- a/mcp-host/src/core/execution/receiveInput.ts+++ /dev/null@@ -1,119 +0,0 @@-import { createHash } from 'node:crypto'-import { constants } from 'node:fs'-import * as fs from 'node:fs/promises'-import { join } from 'node:path'-import { Readable, addAbortSignal } from 'node:stream'--export const EXECUTION_INPUT_MAX_BYTES = 11_534_336-const MAX_INPUT_TIMEOUT_MS = 1_500_000--export type InputReceiveErrorCode =- | 'invalid_input_contract'- | 'input_length_mismatch'- | 'input_digest_mismatch'- | 'input_directory_invalid'- | 'input_write_failed'--export class InputReceiveError extends Error {- constructor(readonly code: InputReceiveErrorCode) {- super(code)- this.name = 'InputReceiveError'- }-}--/**- * Trusted init-container entrypoint. The executor mounts this private volume- * read-only and cannot start until initialization succeeds. It receives no- * store path or runtime authority. This function never interprets input bytes.- */-export async function receiveExecutionInput(- input: Readable,- directory: string,- expectedBytes: number,- expectedDigest: string,- timeoutMs: number-): Promise<void> {- if (- !Number.isSafeInteger(expectedBytes) ||- expectedBytes < 0 ||- expectedBytes > EXECUTION_INPUT_MAX_BYTES ||- !/^[0-9a-f]{64}$/.test(expectedDigest) ||- !Number.isSafeInteger(timeoutMs) ||- timeoutMs <= 0 ||- timeoutMs > MAX_INPUT_TIMEOUT_MS- )- throw new InputReceiveError('invalid_input_contract')- const root = await fs.lstat(directory)- if (!root.isDirectory() || root.isSymbolicLink()) {- throw new InputReceiveError('input_directory_invalid')- }- const stage = join(directory, '.receiving')- const final = join(directory, 'source')- // The init process is the sole volume writer. Exclusive creation refuses- // interrupted or replayed input rather than replacing another operation.- const handle = await fs.open(- stage,- constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW,- 0o600- )- let closed = false- let received = 0- const hash = createHash('sha256')- const signal = AbortSignal.timeout(timeoutMs)- try {- for await (const chunk of addAbortSignal(signal, input)) {- if (!Buffer.isBuffer(chunk) || received + chunk.length > expectedBytes) {- throw new InputReceiveError('input_length_mismatch')- }- received += chunk.length- hash.update(chunk)- let offset = 0- while (offset < chunk.length) {- signal.throwIfAborted()- const { bytesWritten } = await handle.write(chunk, offset, chunk.length - offset)- if (bytesWritten <= 0) throw new InputReceiveError('input_write_failed')- offset += bytesWritten- }- }- signal.throwIfAborted()- if (received !== expectedBytes) throw new InputReceiveError('input_length_mismatch')- if (hash.digest('hex') !== expectedDigest) throw new InputReceiveError('input_digest_mismatch')- await handle.chmod(0o444)- await handle.close()- closed = true- // link publishes atomically without replacing an existing object. This- // volume is ephemeral; durability belongs to the original-file store.- await fs.link(stage, final)- } finally {- if (!closed) await handle.close()- await fs.unlink(stage)- }-}--if (require.main === module) {- const [size, digest, timeout, ...extra] = process.argv.slice(2)- if (- extra.length ||- !size ||- !digest ||- !timeout ||- !/^\d+$/.test(size) ||- !/^\d+$/.test(timeout)- ) {- process.stderr.write(JSON.stringify({ level: 'error', code: 'invalid_input_contract' }) + '\n')- process.exitCode = 1- } else {- receiveExecutionInput(process.stdin, '/input', Number(size), digest, Number(timeout))- .then(() =>- process.stdout.write(- JSON.stringify({ level: 'info', event: 'input_ready', bytes: Number(size) }) + '\n'- )- )- .catch(error => {- // Never include raw data, digest, paths, scripts or exception messages.- const code = error instanceof InputReceiveError ? error.code : 'input_receive_failed'- process.stderr.write(JSON.stringify({ level: 'error', code }) + '\n')- process.exitCode = 1- })- }-}diff --git a/mcp-host/src/core/execution/receiveSession.test.ts b/mcp-host/src/core/execution/receiveSession.test.tsdeleted file mode 100644index 6f56274cc..000000000--- a/mcp-host/src/core/execution/receiveSession.test.ts+++ /dev/null@@ -1,322 +0,0 @@-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.tsdeleted file mode 100644index 7bdd4ec75..000000000--- a/mcp-host/src/core/execution/receiveSession.ts+++ /dev/null@@ -1,225 +0,0 @@-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/runExecution.test.ts b/mcp-host/src/core/execution/runExecution.test.tsdeleted file mode 100644index 3d42803de..000000000--- a/mcp-host/src/core/execution/runExecution.test.ts+++ /dev/null@@ -1,234 +0,0 @@-import { afterEach, describe, expect, it } from 'vitest'-import { mkdtemp, rm, stat } from 'node:fs/promises'-import { tmpdir } from 'node:os'-import { join } from 'node:path'-import { MAX_CAPTURED_OUTPUT_BYTES, MAX_EXECUTION_TIMEOUT_MS, runExecution } from './runExecution'--const execPath = process.execPath-/** Fixture child: this same Node binary, never a shell or an external script. */-const fixture = (script: string, ...args: string[]) => [execPath, '-e', script, ...args]-/**- * Long-lived fixtures self-terminate, so even a deliberately broken launcher- * under mutation cannot leave a child of this suite running.- */-const WATCHDOG = 'setTimeout(() => process.exit(9), 30_000); '-const decode = (base64: string) => Buffer.from(base64, 'base64')-const text = (base64: string) => decode(base64).toString('utf8')--const tempDirs: string[] = []-afterEach(async () => {- for (const dir of tempDirs.splice(0)) await rm(dir, { recursive: true, force: true })-})--describe('isolated execution launcher', () => {- it('runs the approved argument vector literally, without a shell', async () => {- const literals = ['a b', '$HOME', '; echo pwned', '$(id)', '*']- const result = await runExecution(10_000, [- execPath,- '-e',- 'process.stdout.write(JSON.stringify(process.argv.slice(1)))',- ...literals,- ])-- expect(result).toMatchObject({- reason: 'exited',- exitCode: 0,- signal: null,- truncated: false,- })- // No expansion, splitting or quoting happened: the bytes are the literals.- expect(JSON.parse(text(result.stdout))).toEqual(literals)- expect(result.stderr).toBe('')- })-- it('passes only the fixed non-secret environment with HOME at the cwd', async () => {- process.env.PR932_LAUNCHER_ENV_LEAK = 'must-not-reach-the-child'- try {- const result = await runExecution(- 10_000,- fixture('process.stdout.write(JSON.stringify(process.env))')- )- const env = JSON.parse(text(result.stdout))- // macOS adds this CoreFoundation text-encoding variable on its own; the- // launcher itself passes exactly the fixed set below.- delete env.__CF_USER_TEXT_ENCODING- expect(env).toEqual({- PATH: '/usr/local/bin:/usr/bin:/bin',- HOME: process.cwd(),- TMPDIR: '/tmp',- LANG: 'C.UTF-8',- })- } finally {- delete process.env.PR932_LAUNCHER_ENV_LEAK- }- })-- it('does not forward or interpret stdin', async () => {- const result = await runExecution(- 10_000,- fixture(- 'let bytes = 0; process.stdin.on("data", chunk => { bytes += chunk.length }); ' +- 'setTimeout(() => process.stdout.write(String(bytes)), 150)'- )- )-- expect(text(result.stdout)).toBe('0')- })-- it('preserves arbitrary binary bytes through base64', async () => {- const bytes = Buffer.from([0, 1, 2, 0x7f, 0x80, 0xff, 0x0a, 0x0d])- const result = await runExecution(- 10_000,- fixture(`process.stdout.write(Buffer.from(${JSON.stringify([...bytes])}))`)- )-- expect(decode(result.stdout)).toEqual(bytes)- expect(result.truncated).toBe(false)- })-- it('bounds stdout and stderr together at the aggregate cap and stops the child', async () => {- const half = 40 * 1024- const result = await runExecution(- 10_000,- fixture(- WATCHDOG +- `process.stdout.write(Buffer.alloc(${half}, 65)); ` +- `process.stderr.write(Buffer.alloc(${half}, 66)); setInterval(() => {}, 1000)`- )- )-- expect(result.reason).toBe('output_limit')- expect(result.truncated).toBe(true)- expect(result.signal).toBe('SIGKILL')- const captured = decode(result.stdout).length + decode(result.stderr).length- expect(captured).toBe(MAX_CAPTURED_OUTPUT_BYTES)- expect(decode(result.stdout).length).toBeLessThanOrEqual(half)- })-- it('stops the approved command at the timeout', async () => {- const result = await runExecution(250, fixture(`${WATCHDOG}setInterval(() => {}, 1000)`))-- expect(result).toEqual({- reason: 'timeout',- exitCode: null,- signal: 'SIGKILL',- truncated: false,- stdout: '',- stderr: '',- })- })-- it('reports a spawn failure without throwing or leaking an exception', async () => {- const result = await runExecution(10_000, ['/nonexistent/pr932-execution-fixture', 'x'])-- expect(result).toEqual({- reason: 'spawn_failed',- exitCode: null,- signal: null,- truncated: false,- stdout: '',- stderr: '',- })- })-- it('keeps a huge output bounded to the cap', async () => {- const result = await runExecution(- 30_000,- fixture('process.stdout.write(Buffer.alloc(10 * 1024 * 1024, 97))')- )-- expect(result.reason).toBe('output_limit')- expect(result.truncated).toBe(true)- expect(decode(result.stdout).length).toBeLessThanOrEqual(MAX_CAPTURED_OUTPUT_BYTES)- expect(Buffer.byteLength(JSON.stringify(result))).toBeLessThan(MAX_CAPTURED_OUTPUT_BYTES * 2)- })-- it('reports exit codes and signals separately from the reason', async () => {- const exited = await runExecution(10_000, fixture('process.exit(7)'))- expect(exited).toMatchObject({- reason: 'exited',- exitCode: 7,- signal: null,- truncated: false,- })-- const signalled = await runExecution(10_000, fixture('process.kill(process.pid, "SIGTERM")'))- expect(signalled).toMatchObject({- reason: 'exited',- exitCode: null,- signal: 'SIGTERM',- truncated: false,- })- })-- it('rejects an invalid launcher contract without spawning anything', async () => {- const invalid: Array<[number, string[]]> = [- [MAX_EXECUTION_TIMEOUT_MS + 1, [execPath]],- [0, [execPath]],- [-1, [execPath]],- [1.5, [execPath]],- [Number.NaN, [execPath]],- [10_000, []],- [10_000, ['']],- [10_000, ['x\0y']],- ]- for (const [timeoutMs, argv] of invalid) {- await expect(runExecution(timeoutMs, argv)).resolves.toEqual({- reason: 'invalid_contract',- exitCode: null,- signal: null,- truncated: false,- stdout: '',- stderr: '',- })- }- // The maximum accepted timeout still runs.- await expect(- runExecution(MAX_EXECUTION_TIMEOUT_MS, fixture('process.exit(0)'))- ).resolves.toMatchObject({ reason: 'exited', exitCode: 0 })- })-- it('never writes child content or raw errors 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 result = await runExecution(- 10_000,- fixture("process.stdout.write('hidden-out'); process.stderr.write('hidden-err')")- )- expect(text(result.stdout)).toBe('hidden-out')- expect(text(result.stderr)).toBe('hidden-err')- } finally {- process.stdout.write = originalOut- process.stderr.write = originalErr- }- expect(writes).toEqual([])- })-- it('stops descendants through the process group, not only the direct child', async () => {- const dir = await mkdtemp(join(tmpdir(), 'pr932-exec-group-'))- tempDirs.push(dir)- const marker = join(dir, 'descendant-ran')- const grandchild =- "setTimeout(() => { require('fs').writeFileSync(process.argv[1], 'late') }, 600)"- const child =- WATCHDOG +- `require('child_process').spawn(process.execPath, ['-e', ` +- `${JSON.stringify(grandchild)}, ${JSON.stringify(marker)}], { stdio: 'ignore' }); ` +- 'setInterval(() => {}, 1000)'-- const result = await runExecution(250, [execPath, '-e', child])- expect(result.reason).toBe('timeout')-- await new Promise(resolve => setTimeout(resolve, 900))- await expect(stat(marker)).rejects.toThrow()- })-})diff --git a/mcp-host/src/core/execution/runExecution.ts b/mcp-host/src/core/execution/runExecution.tsdeleted file mode 100644index 2405428bc..000000000--- a/mcp-host/src/core/execution/runExecution.ts+++ /dev/null@@ -1,179 +0,0 @@-import { type ChildProcess, spawn } from 'node:child_process'--/** Hard ceiling for one approved operation, shared with the input receiver. */-export const MAX_EXECUTION_TIMEOUT_MS = 1_500_000-/** Aggregate bound on captured stdout + stderr, binary bytes included. */-export const MAX_CAPTURED_OUTPUT_BYTES = 65_536--const EXECUTION_PATH = '/usr/local/bin:/usr/bin:/bin'-const EXECUTION_TMPDIR = '/tmp'-const EXECUTION_LANG = 'C.UTF-8'--export type ExecutionResultReason =- | 'exited'- | 'timeout'- | 'output_limit'- | 'spawn_failed'- | 'invalid_contract'--/**- * One bounded result. `stdout`/`stderr` are base64 because the captured bytes- * are arbitrary; `truncated` is true only when the aggregate cap cut them.- */-export interface ExecutionResult {- reason: ExecutionResultReason- exitCode: number | null- signal: string | null- truncated: boolean- stdout: string- stderr: string-}--/** Fixed, non-secret environment; nothing else from the launcher is passed. */-export function executionEnvironment(cwd: string): Record<string, string> {- return {- PATH: EXECUTION_PATH,- HOME: cwd,- TMPDIR: EXECUTION_TMPDIR,- LANG: EXECUTION_LANG,- }-}--function emptyResult(reason: ExecutionResultReason): ExecutionResult {- return { reason, exitCode: null, signal: null, truncated: false, stdout: '', stderr: '' }-}--function invalidContract(timeoutMs: number, argv: string[]): boolean {- return (- !Number.isSafeInteger(timeoutMs) ||- timeoutMs <= 0 ||- timeoutMs > MAX_EXECUTION_TIMEOUT_MS ||- !Array.isArray(argv) ||- argv.length === 0 ||- typeof argv[0] !== 'string' ||- argv[0].length === 0 ||- argv.some(argument => typeof argument !== 'string' || argument.includes('\0'))- )-}--/**- * Best-effort stop for the child's own process group. This launcher is PID 1- * inside a private Job Pod: a signal covers the approved command's descendants- * that still share the group. Verified runtime termination of the private Pod- * is the physical cleanup boundary; API deletion or a signal alone is not- * proof that no descendant survives.- */-function stopProcessGroup(child: ChildProcess): void {- if (typeof child.pid !== 'number') return- try {- process.kill(-child.pid, 'SIGKILL')- } catch {- // A missing group or failed signal does not prove cleanup. The bounded- // workload lifecycle must separately terminate and verify the private Pod.- }-}--/**- * Runs one already-approved argument vector, literally and without a shell.- * The vector is never parsed, quoted or re-interpreted, stdin is not forwarded,- * and no child output is written to the launcher's own streams.- */-export function runExecution(timeoutMs: number, argv: string[]): Promise<ExecutionResult> {- if (invalidContract(timeoutMs, argv)) {- return Promise.resolve(emptyResult('invalid_contract'))- }- const cwd = process.cwd()-- return new Promise(resolve => {- let settled = false- let reason: ExecutionResultReason = 'exited'- let truncated = false- let timer: NodeJS.Timeout | undefined- const captured = {- stdout: { chunks: [] as Buffer[], bytes: 0 },- stderr: { chunks: [] as Buffer[], bytes: 0 },- }-- const settle = (result: ExecutionResult): void => {- if (settled) return- settled = true- if (timer) clearTimeout(timer)- resolve(result)- }-- const stop = (next: ExecutionResultReason): void => {- if (reason === 'exited') reason = next- stopProcessGroup(child)- }-- const absorb = (name: 'stdout' | 'stderr', chunk: Buffer): void => {- const bucket = captured[name]- const remaining = MAX_CAPTURED_OUTPUT_BYTES - captured.stdout.bytes - captured.stderr.bytes- if (remaining <= 0) {- truncated = true- stop('output_limit')- return- }- const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk- bucket.chunks.push(slice)- bucket.bytes += slice.length- if (slice.length < chunk.length) {- truncated = true- stop('output_limit')- }- }-- let child: ChildProcess- try {- child = spawn(argv[0], argv.slice(1), {- cwd,- env: executionEnvironment(cwd),- stdio: ['ignore', 'pipe', 'pipe'],- // The approved command leads its own process group so a timeout or the- // output cap can stop the tree it started, not just the direct child.- detached: true,- })- } catch {- // Node can reject an unusable spawn synchronously; the caller still gets- // one bounded result instead of an exception.- resolve(emptyResult('spawn_failed'))- return- }-- child.stdout?.on('data', (chunk: Buffer) => absorb('stdout', chunk))- child.stderr?.on('data', (chunk: Buffer) => absorb('stderr', chunk))- child.on('error', () => settle(emptyResult('spawn_failed')))- child.on('close', (code, signal) =>- settle({- reason,- exitCode: typeof code === 'number' ? code : null,- signal: signal ?? null,- truncated,- stdout: Buffer.concat(captured.stdout.chunks).toString('base64'),- stderr: Buffer.concat(captured.stderr.chunks).toString('base64'),- })- )- timer = setTimeout(() => stop('timeout'), timeoutMs)- })-}--if (require.main === module) {- // CLI: <timeoutMs> <exe> [...args]. The approved vector is passed through as- // process arguments on purpose: no JSON re-encoding and no shell.- const [rawTimeoutMs, ...approvedArgv] = process.argv.slice(2)- const timeoutMs = Number(rawTimeoutMs)- const run = /^\d+$/.test(rawTimeoutMs ?? '')- ? runExecution(timeoutMs, approvedArgv)- : Promise.resolve(emptyResult('invalid_contract'))- run- .then(result => {- // Exactly one bounded JSON line; the child's bytes only travel inside it.- process.stdout.write(`${JSON.stringify(result)}\n`)- process.exitCode = result.reason === 'invalid_contract' ? 1 : 0- })- .catch(() => {- // Never log raw exceptions or captured content.- process.stdout.write(`${JSON.stringify(emptyResult('spawn_failed'))}\n`)- process.exitCode = 0- })-}diff --git a/mcp-host/src/core/execution/runSession.test.ts b/mcp-host/src/core/execution/runSession.test.tsdeleted file mode 100644index 6a885678c..000000000--- a/mcp-host/src/core/execution/runSession.test.ts+++ /dev/null@@ -1,310 +0,0 @@-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.tsdeleted file mode 100644index e026de3d1..000000000--- a/mcp-host/src/core/execution/runSession.ts+++ /dev/null@@ -1,221 +0,0 @@-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))-}diff --git a/scripts/security/check-np08-mcp-host-networkpolicy.rb b/scripts/security/check-np08-mcp-host-networkpolicy.rbindex fe39a6565..30c6c25f9 100755--- a/scripts/security/check-np08-mcp-host-networkpolicy.rb+++ b/scripts/security/check-np08-mcp-host-networkpolicy.rb@@ -75,110 +75,25 @@ policy_types_include_egress = lambda do |policy|Array(policy.dig("spec", "policyTypes")).include?("Egress")end-# HCC also labels execution Pods clerum.io/managed-by=host-context-controller.-# NetworkPolicies are additive, so every static Host grant excludes them with-# exactly this expression; any other narrowing of the Host selector fails.-EXECUTION_ROLE_LABEL = "clerum.io/role"-EXECUTION_ROLE_VALUE = "host-execution"-HOST_EXECUTION_EXCLUSION = [- { "key" => EXECUTION_ROLE_LABEL, "operator" => "NotIn", "values" => [EXECUTION_ROLE_VALUE] },-].freeze-EXPECTED_EXECUTION_SPEC = {- "podSelector" => {- "matchLabels" => {- "clerum.io/managed-by" => "host-context-controller",- EXECUTION_ROLE_LABEL => EXECUTION_ROLE_VALUE,- },- },- "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" => [],-}.freeze--static_host_pod_selector = lambda do |policy|+exact_pod_selector = lambda do |policy, expected_labels|selector = policy.dig("spec", "podSelector")- selector.is_a?(Hash) && selector.keys.sort == ["matchExpressions", "matchLabels"] &&- selector["matchLabels"] == { "clerum.io/managed-by" => "host-context-controller" } &&- selector["matchExpressions"] == HOST_EXECUTION_EXCLUSION+ selector.is_a?(Hash) && selector.keys.sort == ["matchLabels"] &&+ selector["matchLabels"] == expected_labels && Array(selector["matchExpressions"]).empty?enddefault_deny = policies.find { |policy| policy.dig("metadata", "name") == "deny-all-mcp-host" }managed_host_policy = policies.find { |policy| policy.dig("metadata", "name") == "mcp-host" }-static_host_grants = %w[mcp-host allow-dns-egress-mcp-host allow-k8s-api-egress-mcp-host].map do |name|- policies.find { |policy| policy.dig("metadata", "name") == name }-end-execution_policy = policies.find { |policy| policy.dig("metadata", "name") == "host-execution-private" }context_allow_policies = policies.select do |policy|policy.dig("metadata", "labels", "clerum.io/policy-type") == "context-allow"end-# Any other mcp-host policy that grants traffic must not be able to select an-# execution Pod. Operation and Host UID label values are per Pod, so a selector-# keyed on them is treated as possibly matching; an unknown operator matches.-EXECUTION_STATIC_LABELS = {- "clerum.io/managed-by" => "host-context-controller",- EXECUTION_ROLE_LABEL => EXECUTION_ROLE_VALUE,-}.freeze-EXECUTION_DYNAMIC_LABELS = %w[clerum.io/operation clerum.io/host-uid].freeze-selects_execution_pod = lambda do |selector|- next true unless selector.is_a?(Hash)-- labels_match = (selector["matchLabels"] || {}).all? do |key, value|- EXECUTION_DYNAMIC_LABELS.include?(key) || EXECUTION_STATIC_LABELS[key] == value- end- expressions_match = Array(selector["matchExpressions"]).all? do |expression|- next true unless expression.is_a?(Hash)-- key = expression["key"]- values = Array(expression["values"])- if EXECUTION_DYNAMIC_LABELS.include?(key)- expression["operator"] != "DoesNotExist"- else- present = EXECUTION_STATIC_LABELS.key?(key)- case expression["operator"]- when "In" then present && values.include?(EXECUTION_STATIC_LABELS[key])- when "NotIn" then !present || !values.include?(EXECUTION_STATIC_LABELS[key])- when "Exists" then present- when "DoesNotExist" then !present- else true- end- end- end- labels_match && expressions_match-end-policy_grants_traffic = lambda do |policy|- !Array(policy.dig("spec", "ingress")).empty? || !Array(policy.dig("spec", "egress")).empty?-end-execution_grants = policies.select do |policy|- policy.dig("metadata", "name") != "host-execution-private" &&- policy_grants_traffic.call(policy) &&- selects_execution_pod.call(policy.dig("spec", "podSelector"))-end-selector_contract_ok =default_deny.is_a?(Hash) &&default_deny.dig("spec", "podSelector") == {} &&policy_types_include_egress.call(default_deny) &&managed_host_policy.is_a?(Hash) &&- static_host_grants.all? do |policy|- policy.is_a?(Hash) && static_host_pod_selector.call(policy) && policy_types_include_egress.call(policy)- end &&- execution_policy.is_a?(Hash) &&- # The API server omits an empty egress list, so a live object and a render- # compare equal only after restoring it.- execution_policy["spec"].is_a?(Hash) &&- execution_policy["spec"].merge("egress" => Array(execution_policy["spec"]["egress"])) == EXPECTED_EXECUTION_SPEC &&- execution_grants.empty? &&+ exact_pod_selector.call(managed_host_policy, { "clerum.io/managed-by" => "host-context-controller" }) &&+ policy_types_include_egress.call(managed_host_policy) &&context_allow_policies.all? do |policy|labels = policy.dig("spec", "podSelector", "matchLabels")context = policy.dig("metadata", "labels", "clerum.io/context")@@ -190,14 +105,9 @@ selector_contract_ok =endif host_pods- managed_pods = Array(host_pods.fetch("items", [])).select do |pod|+ managed_host_pods = Array(host_pods.fetch("items", [])).select do |pod|pod.dig("metadata", "labels", "clerum.io/managed-by") == "host-context-controller"end- execution_pods, managed_host_pods = managed_pods.partition do |pod|- pod.dig("metadata", "labels", EXECUTION_ROLE_LABEL) == EXECUTION_ROLE_VALUE- end- # Every Host pod has an egress grant; every execution Pod is selected by no- # granting policy other than its private one.selector_contract_ok &&= !managed_host_pods.empty? && managed_host_pods.all? do |pod|labels = pod.dig("metadata", "labels") || {}policies.any? do |policy|@@ -206,14 +116,6 @@ if host_podsselector_matches.call(policy.dig("spec", "podSelector"), labels)endend- selector_contract_ok &&= execution_pods.all? do |pod|- labels = pod.dig("metadata", "labels") || {}- policies.none? do |policy|- policy.dig("metadata", "name") != "host-execution-private" &&- policy_grants_traffic.call(policy) &&- selector_matches.call(policy.dig("spec", "podSelector"), labels)- end- endendport_is_numeric = lambda do |port|@@ -355,7 +257,7 @@ egress_contract_ok &&= gfs_contract_okhcc_lane = policy_rules.any? do |_policy, rule|policy = _policypolicy_types_include_egress.call(policy) &&- static_host_pod_selector.call(policy) &&+ exact_pod_selector.call(policy, { "clerum.io/managed-by" => "host-context-controller" }) &&allows_tcp_port.call(rule, 8081) &&Array(rule["to"]).any? do |peer|peer.dig("namespaceSelector", "matchLabels", "kubernetes.io/metadata.name") == "control-plane" &&diff --git a/scripts/tests/test-np08-live-networkpolicy-contract.sh b/scripts/tests/test-np08-live-networkpolicy-contract.shindex 58a878167..635de7078 100755--- a/scripts/tests/test-np08-live-networkpolicy-contract.sh+++ b/scripts/tests/test-np08-live-networkpolicy-contract.sh@@ -20,13 +20,8 @@ RUBYOPT=--disable=gems ruby -ryaml -rjson -e 'assert_result() {local fixture="$1"local expected="$2"- local pods="${3:-}"local actual- if [[ -n "${pods}" ]]; then- actual="$(RUBYOPT=--disable=gems ruby "$helper" --host-pods "${pods}" <"${fixture}")"- else- actual="$(RUBYOPT=--disable=gems ruby "$helper" <"${fixture}")"- fi+ actual="$(RUBYOPT=--disable=gems ruby "$helper" <"${fixture}")"if ! ruby -rjson -e 'expected = JSON.parse(ARGV.fetch(0))actual = JSON.parse(STDIN.read)@@ -103,69 +98,3 @@ echo "PASS: live policy helper rejects ineffective Host selectors"missing_egress_type="$(mutate missing-egress-type 'data["items"].find { |d| d["metadata"]["name"] == "mcp-host" }["spec"]["policyTypes"] = ["Ingress"]')"assert_result "${missing_egress_type}" '{"selector_contract_ok":false,"hcc_lane":false}'echo "PASS: live policy helper rejects a Host policy without Egress policy type"--dns_without_exclusion="$(mutate dns-without-exclusion 'data["items"].find { |d| d["metadata"]["name"] == "allow-dns-egress-mcp-host" }["spec"]["podSelector"].delete("matchExpressions")')"-assert_result "${dns_without_exclusion}" '{"selector_contract_ok":false,"hcc_lane":true}'-echo "PASS: live policy helper rejects a DNS grant that execution Pods inherit"--wrong_exclusion="$(mutate wrong-exclusion 'data["items"].find { |d| d["metadata"]["name"] == "mcp-host" }["spec"]["podSelector"]["matchExpressions"].first["operator"] = "In"')"-assert_result "${wrong_exclusion}" '{"selector_contract_ok":false,"hcc_lane":false}'-echo "PASS: live policy helper rejects a Host selector narrowed by anything but the execution exclusion"--execution_egress="$(mutate execution-egress 'data["items"].find { |d| d["metadata"]["name"] == "host-execution-private" }["spec"]["egress"] = [{ "to" => [{ "ipBlock" => { "cidr" => "0.0.0.0/0" } }] }]')"-assert_result "${execution_egress}" '{"selector_contract_ok":false,"hcc_lane":true}'-echo "PASS: live policy helper rejects egress on the execution policy"--execution_live_shape="$(mutate execution-live-shape 'data["items"].find { |d| d["metadata"]["name"] == "host-execution-private" }["spec"].delete("egress")')"-assert_result "${execution_live_shape}" '{"selector_contract_ok":true,"hcc_lane":true}'-echo "PASS: live policy helper accepts the execution policy as the API server returns it"--execution_ingress="$(mutate execution-ingress 'data["items"].find { |d| d["metadata"]["name"] == "host-execution-private" }["spec"]["ingress"].first["from"] = [{ "namespaceSelector" => {} }]')"-assert_result "${execution_ingress}" '{"selector_contract_ok":false,"hcc_lane":true}'-echo "PASS: live policy helper rejects a widened execution ingress"--missing_execution="$(mutate missing-execution 'data["items"].reject! { |d| d["metadata"]["name"] == "host-execution-private" }')"-assert_result "${missing_execution}" '{"selector_contract_ok":false,"hcc_lane":true}'-echo "PASS: live policy helper rejects a missing execution policy"--execution_grant() {- local name="$1"- local selector="$2"- mutate "${name}" "data[\"items\"] << { \"apiVersion\" => \"networking.k8s.io/v1\", \"kind\" => \"NetworkPolicy\", \"metadata\" => { \"name\" => \"fixture-${name}\", \"namespace\" => \"mcp-host\" }, \"spec\" => { \"podSelector\" => ${selector}, \"policyTypes\" => [\"Ingress\"], \"ingress\" => [{ \"from\" => [{ \"namespaceSelector\" => { \"matchLabels\" => { \"kubernetes.io/metadata.name\" => \"mcp-server\" } } }], \"ports\" => [{ \"port\" => 9300, \"protocol\" => \"TCP\" }] }] } }"-}--grant_by_role="$(execution_grant grant-by-role '{ "matchLabels" => { "clerum.io/role" => "host-execution" } }')"-assert_result "${grant_by_role}" '{"selector_contract_ok":false,"hcc_lane":true}'-echo "PASS: live policy helper rejects a grant selecting execution Pods by role"--grant_by_operation="$(execution_grant grant-by-operation '{ "matchExpressions" => [{ "key" => "clerum.io/operation", "operator" => "Exists" }] }')"-assert_result "${grant_by_operation}" '{"selector_contract_ok":false,"hcc_lane":true}'-echo "PASS: live policy helper rejects a grant selecting execution Pods by operation"--grant_elsewhere="$(execution_grant grant-elsewhere '{ "matchLabels" => { "app" => "unrelated" } }')"-assert_result "${grant_elsewhere}" '{"selector_contract_ok":true,"hcc_lane":true}'-echo "PASS: live policy helper accepts a grant that cannot select execution Pods"--host_pod='{ "metadata": { "name": "host-a", "labels": { "clerum.io/managed-by": "host-context-controller", "clerum.io/context": "context-a" } } }'-execution_pod='{ "metadata": { "name": "exec-a", "labels": { "clerum.io/managed-by": "host-context-controller", "clerum.io/role": "host-execution", "clerum.io/operation": "op-1", "clerum.io/host-uid": "uid-1" } } }'-printf '{ "items": [%s, %s] }' "${host_pod}" "${execution_pod}" >"${tmp_dir}/pods-both.json"-printf '{ "items": [%s] }' "${execution_pod}" >"${tmp_dir}/pods-execution-only.json"-printf '{ "items": [%s] }' "${host_pod}" >"${tmp_dir}/pods-host-only.json"--assert_result "${tmp_dir}/valid.json" '{"selector_contract_ok":true,"hcc_lane":true}' "${tmp_dir}/pods-both.json"-echo "PASS: live pod check accepts a Host pod with egress next to an execution Pod without it"--assert_result "${tmp_dir}/valid.json" '{"selector_contract_ok":false}' "${tmp_dir}/pods-execution-only.json"-echo "PASS: live pod check rejects a namespace with no Host pod"--# The GFS lane selects app=mcp-host, a label execution Pods are not created with,-# so only the pod check can see an execution Pod that carries it.-labelled_execution_pod='{ "metadata": { "name": "exec-b", "labels": { "clerum.io/managed-by": "host-context-controller", "clerum.io/role": "host-execution", "app": "mcp-host" } } }'-printf '{ "items": [%s, %s] }' "${host_pod}" "${labelled_execution_pod}" >"${tmp_dir}/pods-labelled-execution.json"-assert_result "${gfs}" '{"selector_contract_ok":true}' "${tmp_dir}/pods-both.json"-assert_result "${gfs}" '{"selector_contract_ok":false}' "${tmp_dir}/pods-labelled-execution.json"-echo "PASS: live pod check rejects an execution Pod selected by a Host grant through its live labels"--no_host_egress="$(mutate no-host-egress 'data["items"].each { |d| d["spec"]["egress"] = [] if %w[mcp-host allow-dns-egress-mcp-host allow-k8s-api-egress-mcp-host].include?(d["metadata"]["name"]) }')"-assert_result "${no_host_egress}" '{"selector_contract_ok":false}' "${tmp_dir}/pods-host-only.json"-echo "PASS: live pod check rejects a Host pod with no egress grant"diff --git a/scripts/tests/test-np08-render-contract-fixtures.sh b/scripts/tests/test-np08-render-contract-fixtures.shindex 8d8efe2db..5068ddd46 100755--- a/scripts/tests/test-np08-render-contract-fixtures.sh+++ b/scripts/tests/test-np08-render-contract-fixtures.sh@@ -185,54 +185,6 @@ when 'host-secret-authenticated-group-grant'},'subjects' => [{ 'kind' => 'Group', 'name' => 'system:authenticated' }],}-when 'dns-without-execution-exclusion', 'k8s-api-wrong-execution-exclusion',- 'execution-egress', 'execution-ingress-widened'- name = {- 'dns-without-execution-exclusion' => 'allow-dns-egress-mcp-host',- 'k8s-api-wrong-execution-exclusion' => 'allow-k8s-api-egress-mcp-host',- 'execution-egress' => 'host-execution-private',- 'execution-ingress-widened' => 'host-execution-private',- }.fetch(mutation)- policy = documents.find do |document|- document['kind'] == 'NetworkPolicy' &&- document.dig('metadata', 'namespace') == 'mcp-host' &&- document.dig('metadata', 'name') == name- end- abort("fixture source is missing mcp-host NetworkPolicy #{name}") unless policy- case mutation- when 'dns-without-execution-exclusion'- policy['spec']['podSelector'].delete('matchExpressions')- when 'k8s-api-wrong-execution-exclusion'- policy['spec']['podSelector']['matchExpressions'][0]['values'] = ['other']- when 'execution-egress'- policy['spec']['egress'] = [{- 'to' => [{ 'namespaceSelector' => { 'matchLabels' => { 'kubernetes.io/metadata.name' => 'kube-system' } } }],- 'ports' => [{ 'port' => 53, 'protocol' => 'UDP' }],- }]- when 'execution-ingress-widened'- policy['spec']['ingress'][0]['from'] << {- 'namespaceSelector' => { 'matchLabels' => { 'kubernetes.io/metadata.name' => 'mcp-server' } },- }- end-when 'execution-grant-by-role', 'execution-grant-by-operation'- pod_selector = if mutation == 'execution-grant-by-role'- { 'matchExpressions' => [{ 'key' => 'clerum.io/role', 'operator' => 'In', 'values' => ['host-execution'] }] }- else- { 'matchLabels' => { 'clerum.io/operation' => 'fixture-operation' } }- end- documents << {- 'apiVersion' => 'networking.k8s.io/v1',- 'kind' => 'NetworkPolicy',- 'metadata' => { 'name' => "fixture-#{mutation}", 'namespace' => 'mcp-host' },- 'spec' => {- 'podSelector' => pod_selector,- 'policyTypes' => ['Ingress'],- 'ingress' => [{- 'from' => [{ 'namespaceSelector' => { 'matchLabels' => { 'kubernetes.io/metadata.name' => 'mcp-server' } } }],- 'ports' => [{ 'port' => 9300, 'protocol' => 'TCP' }],- }],- },- }elseabort("unknown fixture mutation: #{mutation}")end@@ -330,35 +282,3 @@ assert_rejected \"${host_secret_authenticated_group}" \'mcp-host identities must not receive MCP Secret read grants' \'mcp-host MCP Secret system:authenticated grant'--dns_without_execution_exclusion="${tmpdir}/dns-without-execution-exclusion.yaml"-mutate_render dns-without-execution-exclusion "${dns_without_execution_exclusion}"-assert_rejected \- "${dns_without_execution_exclusion}" \- 'allow-dns-egress-mcp-host must select HCC-managed Host pods except execution Pods and enforce Egress' \- 'DNS egress inherited by execution Pods'--k8s_api_wrong_execution_exclusion="${tmpdir}/k8s-api-wrong-execution-exclusion.yaml"-mutate_render k8s-api-wrong-execution-exclusion "${k8s_api_wrong_execution_exclusion}"-assert_rejected \- "${k8s_api_wrong_execution_exclusion}" \- 'allow-k8s-api-egress-mcp-host must select HCC-managed Host pods except execution Pods and enforce Egress' \- 'k8s API egress exclusion naming another role'--for execution_change in execution-egress execution-ingress-widened; do- execution_private="${tmpdir}/${execution_change}.yaml"- mutate_render "${execution_change}" "${execution_private}"- assert_rejected \- "${execution_private}" \- 'host-execution-private must admit only HCC on 9300/9301 and grant no egress' \- "private execution policy with ${execution_change}"-done--for execution_selector in role operation; do- execution_grant="${tmpdir}/execution-grant-by-${execution_selector}.yaml"- mutate_render "execution-grant-by-${execution_selector}" "${execution_grant}"- assert_rejected \- "${execution_grant}" \- "execution Pods must not inherit mcp-host grants: fixture-execution-grant-by-${execution_selector}" \- "mcp-host grant selecting execution Pods by ${execution_selector}"-donediff --git a/scripts/tests/test-np08-render-contract.sh b/scripts/tests/test-np08-render-contract.shindex 2cca2f3d2..a14487509 100755--- a/scripts/tests/test-np08-render-contract.sh+++ b/scripts/tests/test-np08-render-contract.sh@@ -114,94 +114,18 @@ for rendered in "$@"; dopolicy_types_include_egress = lambda do |policy|Array(policy.dig("spec", "policyTypes")).include?("Egress")end- # HCC also labels execution Pods clerum.io/managed-by=host-context-controller.- # NetworkPolicies are additive, so every static Host grant must exclude them- # with exactly this expression; any other narrowing of the Host selector fails.- host_execution_exclusion = [- { "key" => "clerum.io/role", "operator" => "NotIn", "values" => ["host-execution"] }- ]- static_host_pod_selector = lambda do |policy|+ exact_pod_selector = lambda do |policy, expected_labels|selector = policy.dig("spec", "podSelector")- selector.is_a?(Hash) && selector.keys.sort == ["matchExpressions", "matchLabels"] &&- selector["matchLabels"] == { "clerum.io/managed-by" => "host-context-controller" } &&- selector["matchExpressions"] == host_execution_exclusion+ selector.is_a?(Hash) && selector.keys.sort == ["matchLabels"] &&+ selector["matchLabels"] == expected_labels && Array(selector["matchExpressions"]).empty?enddefault_deny = policies.find { |policy| policy.dig("metadata", "name") == "deny-all-mcp-host" }abort("mcp-host default-deny must select every pod and enforce Egress") unlessdefault_deny && default_deny.dig("spec", "podSelector") == {} && policy_types_include_egress.call(default_deny)managed_host_policy = policies.find { |policy| policy.dig("metadata", "name") == "mcp-host" }abort("mcp-host allow policy must select HCC-managed Host pods and enforce Egress") unless- managed_host_policy && static_host_pod_selector.call(managed_host_policy) &&+ managed_host_policy && exact_pod_selector.call(managed_host_policy, { "clerum.io/managed-by" => "host-context-controller" }) &&policy_types_include_egress.call(managed_host_policy)- %w[allow-dns-egress-mcp-host allow-k8s-api-egress-mcp-host].each do |name|- policy = policies.find { |candidate| candidate.dig("metadata", "name") == name }- abort("#{name} must select HCC-managed Host pods except execution Pods and enforce Egress") unless- policy && static_host_pod_selector.call(policy) && policy_types_include_egress.call(policy)- end-- execution_policy = policies.find { |policy| policy.dig("metadata", "name") == "host-execution-private" }- expected_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" => []- }- abort("host-execution-private must admit only HCC on 9300/9301 and grant no egress") unless- execution_policy && execution_policy["spec"] == expected_execution_spec-- # Any other mcp-host policy that grants traffic must not be able to select an- # execution Pod. Operation and Host UID label values are per Pod, so a selector- # keyed on them is treated as possibly matching.- execution_static_labels = {- "clerum.io/managed-by" => "host-context-controller",- "clerum.io/role" => "host-execution"- }- execution_dynamic_labels = %w[clerum.io/operation clerum.io/host-uid]- selects_execution_pod = lambda do |selector|- next false unless selector.is_a?(Hash)- labels_match = (selector["matchLabels"] || {}).all? do |key, value|- execution_dynamic_labels.include?(key) || execution_static_labels[key] == value- end- expressions_match = Array(selector["matchExpressions"]).all? do |expression|- key = expression["key"]- values = Array(expression["values"])- if execution_dynamic_labels.include?(key)- expression["operator"] != "DoesNotExist"- else- present = execution_static_labels.key?(key)- case expression["operator"]- when "In" then present && values.include?(execution_static_labels[key])- when "NotIn" then !present || !values.include?(execution_static_labels[key])- when "Exists" then present- when "DoesNotExist" then !present- else abort("mcp-host policy uses an unknown selector operator")- end- end- end- labels_match && expressions_match- end- execution_grants = policies.select do |policy|- next false if policy.dig("metadata", "name") == "host-execution-private"- grants = !Array(policy.dig("spec", "ingress")).empty? || !Array(policy.dig("spec", "egress")).empty?- grants && selects_execution_pod.call(policy.dig("spec", "podSelector"))- end- abort("execution Pods must not inherit mcp-host grants: #{execution_grants.map { |policy| policy.dig("metadata", "name") }.join(",")}") unless- execution_grants.empty?context_allow_policies = policies.select do |policy|policy.dig("metadata", "labels", "clerum.io/policy-type") == "context-allow"end@@ -350,7 +274,7 @@ for rendered in "$@"; dohcc_lane = policies.any? do |policy|next false unless policy_types_include_egress.call(policy) &&- static_host_pod_selector.call(policy)+ exact_pod_selector.call(policy, { "clerum.io/managed-by" => "host-context-controller" })Array(policy.dig("spec", "egress")).any? do |rule|ports = Array(rule["ports"])peers = Array(rule["to"])