Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
feat: add bounded Host execution groundwork
Alfredo Lopez445925c6956c
diff --git a/control-api/package-lock.json b/control-api/package-lock.jsonindex 7d6bad938..ff69417b7 100644--- a/control-api/package-lock.json+++ b/control-api/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-control-api",- "version": "0.1.711",+ "version": "0.1.712","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-control-api",- "version": "0.1.711",+ "version": "0.1.712","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 0882b95ab..7488e270c 100644--- a/control-api/package.json+++ b/control-api/package.json@@ -1,6 +1,6 @@{"name": "clerum-control-api",- "version": "0.1.711",+ "version": "0.1.712","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 052460ee1..168c55c77 100644--- a/control-api/src/utils/auth/mcpHostJwtToken.ts+++ b/control-api/src/utils/auth/mcpHostJwtToken.ts@@ -182,6 +182,9 @@ 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/host-context-controller/package-lock.json b/host-context-controller/package-lock.jsonindex bb3c7fe0c..db02055f0 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.375",+ "version": "0.1.376","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-host-context-controller",- "version": "0.1.375",+ "version": "0.1.376","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 dde8a1bec..eb45e90ac 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.375",+ "version": "0.1.376","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 ba8a5464a..777769db3 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(24)+ expect(kinds).toHaveLength(25)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 c71df72ba..65ccd6a63 100644--- a/host-context-controller/src/existenceReadMetrics.test.ts+++ b/host-context-controller/src/existenceReadMetrics.test.ts@@ -28,6 +28,14 @@ it('initializes the real read registry before any test seeding', async () => {// Review each exclusion when its enclosing operation changes. Counts describe// expressions, not executions; a newly added direct read must be classified.const readExclusions: Record<string, readonly [number, string]> = {+ 'hostExecution/operations.ts::inspect::readNamespacedPod': [+ 1,+ 'Exact Pod UID revalidation after private output retrieval',+ ],+ 'hostExecution/operations.ts::inspect::readNamespacedPodLog': [+ 1,+ 'Bounded execution result retrieval, not a resource existence decision',+ ],'hostReconciler.ts::readHostDeploymentOrNull::readNamespacedDeployment': [1,'Input to runtime binding and refresh decisions',@@ -185,6 +193,7 @@ 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,@@ -254,8 +263,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(26)- expect(Object.values(excluded).reduce((sum, count) => sum + count, 0)).toBe(44)+ expect(Object.values(wrapped).reduce((sum, count) => sum + count, 0)).toBe(27)+ expect(Object.values(excluded).reduce((sum, count) => sum + count, 0)).toBe(46)}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.tsnew file mode 100644index 000000000..bbd0e31f2--- /dev/null+++ b/host-context-controller/src/hostExecution/authorization.test.ts@@ -0,0 +1,422 @@+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.tsnew file mode 100644index 000000000..5b162db0d--- /dev/null+++ b/host-context-controller/src/hostExecution/authorization.ts@@ -0,0 +1,172 @@+/**+ * 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/jobFactory.test.ts b/host-context-controller/src/hostExecution/jobFactory.test.tsnew file mode 100644index 000000000..465fbefbb--- /dev/null+++ b/host-context-controller/src/hostExecution/jobFactory.test.ts@@ -0,0 +1,858 @@+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_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('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(60)+ 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([+ '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 },+ ])+ })++ 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 },+ ])+ 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).toBe(true)+ expect(receiver.stdinOnce).toBe(true)+ expect(receiver.tty).toBe(false)+ expect(receiver.env).toBeUndefined()+ 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(1)+ expect(at(90_001)).toBe(91)+ expect(at(EXECUTION_TIMEOUT_MAX_MS)).toBe(1_500)+ 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(3)+ ).toEqual(['/bin/sh', '-c', ''])+ expect(+ podSpec(+ buildHostExecutionJob(identity, { ...workspaceRequest, argv: ['node', '', ''] })+ ).containers![0].command!.slice(3)+ ).toEqual(['node', '', ''])++ // No wrapper shell is inserted and the caller's array is not aliased.+ const argv = ['/usr/bin/git', 'status']+ const job = buildHostExecutionJob(identity, { ...workspaceRequest, argv })+ argv.push('--porcelain')+ expect(podSpec(job).containers![0].command!.slice(3)).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(3)+ ).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.tsnew file mode 100644index 000000000..251a1d317--- /dev/null+++ b/host-context-controller/src/hostExecution/jobFactory.ts@@ -0,0 +1,705 @@+/**+ * 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/receiveInput.js'+/** PID 1 captures aggregate output before it reaches the node's container log. */+export const EXECUTION_RUN_ENTRYPOINT = '/app/mcp-host/dist/core/execution/runExecution.js'+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),+ ],+ // The caller attaches to this init container to stream the payload;+ // stdinOnce closes the stream after the single input.+ stdin: true,+ stdinOnce: true,+ tty: false,+ 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 launcher passes the approved vector literally to spawn, with+ // no added shell. It bounds stdout/stderr at the producer, not just at the+ // eventual API response. Separate arguments avoid JSON escape inflation.+ command: ['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 },+ ],+ 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,+ activeDeadlineSeconds: Math.ceil(approved.timeoutMs / 1000),+ 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/operations.test.ts b/host-context-controller/src/hostExecution/operations.test.tsnew file mode 100644index 000000000..c4b74db84--- /dev/null+++ b/host-context-controller/src/hostExecution/operations.test.ts@@ -0,0 +1,293 @@+import { describe, expect, it, vi } from 'vitest'+import type * as k8s from '@kubernetes/client-node'+import type { VerifiedMcpHostPrincipal } from '../mcpApiAuthentication'+import { HostExecutionAuthorization, type HostExecutionHostRecord } from './authorization'+import { 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() {+ let host: HostExecutionHostRecord | null = {+ name: identity.hostName,+ namespace: identity.namespace,+ uid: identity.hostUid,+ generation: identity.hostGeneration,+ }+ let job: k8s.V1Job | null = buildHostExecutionJob(identity, request)+ 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: {+ containerStatuses: [+ {+ name: 'executor',+ image: identity.image,+ imageID: 'unit-image',+ ready: false,+ restartCount: 0,+ state: { terminated: { exitCode: 0 } },+ },+ ],+ },+ }+ 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),+ readNamespacedPodLog: vi.fn(async (_request: unknown) => JSON.stringify(capturedResult)),+ }+ 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+ )+ return {+ operations,+ batch,+ core,+ 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.core.readNamespacedPodLog).toHaveBeenCalledWith(+ expect.objectContaining({+ container: 'executor',+ follow: false,+ limitBytes: 98_305,+ })+ )+ expect(f.batch.createNamespacedJob).toHaveBeenCalledTimes(1)+ })++ it('does not publish output if generation changes during its retrieval', async () => {+ const f = fixture()+ const handle = await f.operations.start(principal, identity, request)+ f.core.readNamespacedPodLog.mockImplementationOnce(async () => {+ f.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.core.readNamespacedPodLog).not.toHaveBeenCalled()+ }+ })++ it('reports queued or running without fetching logs', 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: {} }+ await expect(f.operations.inspect(principal, handle)).resolves.toEqual({+ state: 'running',+ podUid,+ })+ expect(f.core.readNamespacedPodLog).not.toHaveBeenCalled()+ })++ it('refuses an oversized producer frame rather than publishing a partial result', async () => {+ const f = fixture()+ const handle = await f.operations.start(principal, identity, request)+ f.core.readNamespacedPodLog.mockResolvedValueOnce('x'.repeat(100_000))+ 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 logs when the Pod is replaced while log retrieval is pending', async () => {+ const f = fixture()+ const handle = await f.operations.start(principal, identity, request)+ f.core.readNamespacedPodLog.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'+ )+ })+})diff --git a/host-context-controller/src/hostExecution/operations.ts b/host-context-controller/src/hostExecution/operations.tsnew file mode 100644index 000000000..e0ac77480--- /dev/null+++ b/host-context-controller/src/hostExecution/operations.ts@@ -0,0 +1,232 @@+import type * as k8s from '@kubernetes/client-node'+import type { VerifiedMcpHostPrincipal } from '../mcpApiAuthentication'+import { getErrorCode, observeCreate, observeExistenceRead } from '../utils'+import { HostExecutionAuthorization, type HostExecutionBinding } from './authorization'+import {+ type ApprovedExecutionRequest,+ EXECUTION_EXECUTOR_CONTAINER_NAME,+ EXECUTION_INPUT_RECEIVER_CONTAINER_NAME,+ type TrustedHostExecutionIdentity,+ buildHostExecutionJob,+ hostExecutionJobName,+ validateHostExecutionJob,+ validateHostExecutionPod,+} from './jobFactory'+import {+ EXECUTION_RESULT_MAX_BYTES,+ type HostExecutionResult,+ parseHostExecutionResult,+} from './result'++type BatchApi = Pick<+ k8s.BatchV1Api,+ 'createNamespacedJob' | 'readNamespacedJob' | 'deleteNamespacedJob'+>+type CoreApi = Pick<+ k8s.CoreV1Api,+ 'listNamespacedPod' | 'readNamespacedPod' | 'readNamespacedPodLog'+>++/** 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' }+ | { 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+ ) {}++ 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+ }++ 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?.terminated) {+ 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' }+ }+ return {+ state:+ handle.request.kind === 'attachment' && !executor?.state?.running+ ? 'waiting_for_input'+ : 'running',+ podUid,+ }+ }+ const podName = pod.metadata!.name!+ const output = await this.core.readNamespacedPodLog({+ namespace: handle.identity.namespace,+ name: podName,+ container: EXECUTION_EXECUTOR_CONTAINER_NAME,+ follow: false,+ limitBytes: EXECUTION_RESULT_MAX_BYTES + 1,+ })+ // A replaced Job cannot supply a result for the saved operation even if+ // it uses the same name. Check again after retrieving private output.+ const currentJob = await this.readJob(handle)+ if (!currentJob) throw new Error('execution_not_found')+ const currentPod = await this.core.readNamespacedPod({+ namespace: handle.identity.namespace,+ name: podName,+ })+ validateHostExecutionPod(currentPod, currentJob, handle.identity, handle.request, podUid)+ await this.authorization.revalidate(principal, binding)+ 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.tsnew file mode 100644index 000000000..4672bb50c--- /dev/null+++ b/host-context-controller/src/hostExecution/result.test.ts@@ -0,0 +1,54 @@+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.tsnew file mode 100644index 000000000..fd48d9f7a--- /dev/null+++ b/host-context-controller/src/hostExecution/result.ts@@ -0,0 +1,57 @@+/** 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/mcpApiAuthentication.test.ts b/host-context-controller/src/mcpApiAuthentication.test.tsindex e6f306364..0f1cebd2f 100644--- a/host-context-controller/src/mcpApiAuthentication.test.ts+++ b/host-context-controller/src/mcpApiAuthentication.test.ts@@ -71,6 +71,31 @@ 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 d069b5f67..c4afaca92 100644--- a/host-context-controller/src/mcpApiAuthentication.ts+++ b/host-context-controller/src/mcpApiAuthentication.ts@@ -4,6 +4,8 @@ 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])?$/@@ -17,6 +19,8 @@ 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 {@@ -67,6 +71,17 @@ 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) {@@ -186,6 +201,9 @@ 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 4be4dfa82..ac027416b 100644--- a/host-context-controller/src/metrics.ts+++ b/host-context-controller/src/metrics.ts@@ -301,6 +301,7 @@ 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/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 61b455759..7a702113a 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.485",+ "version": "0.1.486","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.485",+ "version": "0.1.486","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex b8971bd14..668c9959f 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.485",+ "version": "0.1.486","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.tsnew file mode 100644index 000000000..b61829b2f--- /dev/null+++ b/mcp-host/src/core/execution/receiveInput.test.ts@@ -0,0 +1,102 @@+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.tsnew file mode 100644index 000000000..845b04828--- /dev/null+++ b/mcp-host/src/core/execution/receiveInput.ts@@ -0,0 +1,119 @@+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/runExecution.test.ts b/mcp-host/src/core/execution/runExecution.test.tsnew file mode 100644index 000000000..3d42803de--- /dev/null+++ b/mcp-host/src/core/execution/runExecution.test.ts@@ -0,0 +1,234 @@+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.tsnew file mode 100644index 000000000..2405428bc--- /dev/null+++ b/mcp-host/src/core/execution/runExecution.ts@@ -0,0 +1,179 @@+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+ })+}