Skip to content

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

TypeScript

test(llm): checkpoint isolated runtime validation sources

Alfredo Lopez9cbd25b03d1e
diff --git a/Makefile b/Makefile
index 644c872bc..8970e6566 100644
--- a/Makefile
+++ b/Makefile
@@ -1553,3 +1553,23 @@ minikube-build-627-github: ## Build the reviewed GitHub MCP locally for the owne
@T2_PROJECT_DIR="$(CURDIR)" T2_PROFILE="$(MINIKUBE_PROFILE)" T2_CONTEXT="$(MINIKUBE_PROFILE)" \
T2_SKIP_LOCK="$(T2_SKIP_LOCK)" T2_LOCK_TOKEN="$(T2_LOCK_TOKEN)" \
bash scripts/minikube/with-t2-mutation-lock.sh -- bash scripts/e2e/build-627-github.sh
+
+# Experimental Control API calibration owns temporary NODE_OPTIONS and restores it
+# under the same branch-profile mutation lease. It produces no T2 verdict.
+export CONTROL_API_MEMORY_CONFIG CONTROL_API_MEMORY_READ_ONLY
+.PHONY: minikube-control-api-authorize-memory minikube-control-api-authorize-memory-body
+minikube-control-api-authorize-memory:
+ @test -n "$${CONTROL_API_MEMORY_CONFIG:-}" || { echo "CONTROL_API_MEMORY_CONFIG required"; exit 1; }
+ @if [ "$${CONTROL_API_MEMORY_READ_ONLY:-false}" = "true" ]; then \
+ node scripts/tests/measure-control-api-authorize-memory.mjs --config "$$CONTROL_API_MEMORY_CONFIG" --inspect-plan; \
+ else \
+ T2_PROJECT_DIR="$(CURDIR)" T2_PROFILE="$(MINIKUBE_PROFILE)" T2_CONTEXT="$(CONTROL_API_REAL_PG_CONTEXT)" \
+ T2_SKIP_LOCK="$(T2_SKIP_LOCK)" T2_LOCK_TOKEN="$(T2_LOCK_TOKEN)" \
+ bash scripts/minikube/with-t2-mutation-lock.sh -- \
+ $(MAKE) --no-print-directory minikube-control-api-authorize-memory-body; \
+ fi
+minikube-control-api-authorize-memory-body:
+ @T2_PROJECT_DIR="$(CURDIR)" T2_PROFILE="$(MINIKUBE_PROFILE)" T2_CONTEXT="$(CONTROL_API_REAL_PG_CONTEXT)" \
+ T2_SKIP_LOCK=true T2_LOCK_TOKEN="$(T2_LOCK_TOKEN)" \
+ bash scripts/minikube/require-t2-mutation-lock.sh
+ @T2_SKIP_LOCK=true node scripts/tests/measure-control-api-authorize-memory.mjs --config "$$CONTROL_API_MEMORY_CONFIG"
diff --git a/control-api/package-lock.json b/control-api/package-lock.json
index b87a81497..dca27f6bb 100644
--- a/control-api/package-lock.json
+++ b/control-api/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "clerum-control-api",
- "version": "0.1.706",
+ "version": "0.1.707",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "clerum-control-api",
- "version": "0.1.706",
+ "version": "0.1.707",
"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.json
index ff1079edf..bc6abe978 100644
--- a/control-api/package.json
+++ b/control-api/package.json
@@ -1,6 +1,6 @@
{
"name": "clerum-control-api",
- "version": "0.1.706",
+ "version": "0.1.707",
"description": "Internal Clerum control plane REST API + UI for managing CRDs and secrets",
"main": "dist/main.js",
"engines": {
diff --git a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
index 79dcec580..e25e9b1c0 100644
--- a/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
+++ b/control-api/src/routes/mcp-host/llmProviderAttempts.routes.ts
@@ -41,10 +41,11 @@ const authorizeBodyAdmission = new AuthorizeBodyAdmission(LLM_PROVIDER_ATTEMPT_A
// JSON.parse allocates one heap object per container, so a body under
// the byte limit can exhaust the heap before either authorizer runs. The
-// parser scans the raw bytes first. Every bound below is derived key-by-key
-// from both contracts at the larger of the two values, so the scan refuses no
-// body an authorizer accepts and a bound either contract adds is never
-// silently dropped here.
+// parser scans the raw bytes first. The five supported scan bounds below are
+// merged key-by-key at the larger contract value, so the scan refuses no body
+// either authorizer accepts. Adding a contract bound also requires updating
+// the raw scanners and their supported-key guard; merging a value alone does
+// not implement its enforcement.
type MergedBodyStructureLimits = Readonly<
Record<keyof typeof BODY_STRUCTURE_LIMITS | keyof typeof GROK_BODY_STRUCTURE_LIMITS, number>
>
diff --git a/desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts b/desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts
index a1cfaf3cc..80b30fbde 100644
--- a/desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts
+++ b/desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts
@@ -13,14 +13,25 @@ import {
_electron as electron,
expect,
} from '@playwright/test'
-import { execFileSync } from 'node:child_process'
import { createHash } from 'node:crypto'
import fs from 'node:fs'
-import os from 'node:os'
import path from 'node:path'
import { isDeepStrictEqual } from 'node:util'
+import {
+ MAIN_RECEIPT_FILES,
+ observeLinuxRunner,
+ observePrivateIsolation,
+ readMainRecord as readMainAdmission,
+ refusePlaintextSessionFiles,
+ verifyEncryptedKeyringFiles,
+ verifyMainAdmission,
+ verifyMountIsolation,
+ verifyNativePrivateKeychain,
+ verifySourceManifest,
+} from '../../../scripts/tests/lib/subscription-image-runner-contract.mjs'
import { requirePixelRenderer } from './subscriptionImageChallenge.js'
import {
+ type PrivateIsolationObservation,
type ProviderBinding,
type RunnerObservation,
type SubscriptionImageRun,
@@ -44,7 +55,7 @@ function readPrivateJson(filename: string, maxBytes: number): unknown {
!stat.isFile() ||
stat.nlink !== 1 ||
stat.uid !== process.getuid?.() ||
- (stat.mode & 0o077) !== 0 ||
+ (stat.mode & 0o777) !== 0o600 ||
stat.size > maxBytes
) {
throw new Error('Runner evidence must be bounded, private and owned')
@@ -55,18 +66,7 @@ function readPrivateJson(filename: string, maxBytes: number): unknown {
}
}
function observeRunner(): RunnerObservation {
- if (process.platform !== 'linux' || !process.getuid || !process.getgid)
- throw new Error('Inspected non-root Linux runner required before Electron')
- return {
- platform: process.platform,
- uid: process.getuid(),
- gid: process.getgid(),
- home: fs.realpathSync(os.userInfo().homedir),
- mountNamespace: fs.readlinkSync('/proc/self/ns/mnt'),
- pidNamespace: fs.readlinkSync('/proc/self/ns/pid'),
- userNamespace: fs.readlinkSync('/proc/self/ns/user'),
- mountInfoSha256: sha256(fs.readFileSync('/proc/self/mountinfo')),
- }
+ return observeLinuxRunner().observation
}
export function verifyPhysicalRunner(run: SubscriptionImageRun): void {
const observed = observeRunner()
@@ -75,32 +75,97 @@ export function verifyPhysicalRunner(run: SubscriptionImageRun): void {
runId?: string
repoRoot?: string
gitHead?: string
+ gitTree?: string
+ inputManifestSha256?: string
profile?: string
context?: string
restUrl?: string
rpcUrl?: string
bindings?: ProviderBinding[]
observation?: RunnerObservation
+ isolation?: PrivateIsolationObservation
+ mainAdmissionFile?: string
+ mainAdmissionSha256?: string
+ sourceManifestSha256?: string
+ admittedAt?: string
}
- const gitHead = execFileSync('git', ['-C', repoRoot, 'rev-parse', 'HEAD'], {
- encoding: 'utf8',
- timeout: 5_000,
- }).trim()
+ const sourceBytes = fs.readFileSync(path.join(repoRoot, 'subscription-image-source.json'))
+ const source = JSON.parse(sourceBytes.toString('utf8'))
+ verifySourceManifest(source, repoRoot)
if (
- receipt.kind !== 'evenfire-subscription-image-runner-v1' ||
+ receipt.kind !== 'evenfire-subscription-image-runner-v2' ||
receipt.runId !== run.runId ||
receipt.repoRoot !== fs.realpathSync(repoRoot) ||
- receipt.gitHead !== gitHead ||
+ receipt.gitHead !== source.gitHead ||
+ receipt.gitTree !== source.gitTree ||
+ receipt.inputManifestSha256 !== source.inputManifestSha256 ||
receipt.profile !== run.profile ||
receipt.context !== run.context ||
receipt.restUrl !== run.restUrl ||
receipt.rpcUrl !== run.rpcUrl ||
!isDeepStrictEqual(receipt.bindings, run.bindings) ||
- !receipt.observation
+ !receipt.observation ||
+ !receipt.isolation ||
+ !receipt.mainAdmissionFile ||
+ !receipt.sourceManifestSha256 ||
+ path.dirname(receipt.mainAdmissionFile) !== '/runner-admission'
) {
throw new Error('Physical runner receipt does not bind this run/source/stack/targets')
}
- verifyRunnerObservation(receipt.observation, observed, process.env)
+ const physical = observeLinuxRunner()
+ const mountIds = verifyMountIsolation(
+ physical.mounts,
+ observed.home,
+ '/run/evenfire-e2e',
+ '/runner-admission'
+ )
+ const actualIsolation = observePrivateIsolation(
+ receipt.isolation,
+ observed,
+ process.env,
+ run.runRoot,
+ mountIds
+ )
+ verifyRunnerObservation(
+ receipt.observation,
+ observed,
+ process.env,
+ receipt.isolation,
+ actualIsolation
+ )
+ const mainRecord = readMainAdmission(receipt.mainAdmissionFile)
+ const receipts = {
+ inspect: readMainAdmission(`/runner-admission/${MAIN_RECEIPT_FILES.inspect}`),
+ stack: readMainAdmission(`/runner-admission/${MAIN_RECEIPT_FILES.stack}`),
+ portForwards: readMainAdmission(`/runner-admission/${MAIN_RECEIPT_FILES.portForwards}`),
+ }
+ if (
+ receipt.sourceManifestSha256 !== sha256(sourceBytes) ||
+ receipt.mainAdmissionSha256 !== mainRecord.sha256
+ )
+ throw new Error('Sealed source/main admission changed')
+ const mainAdmission = mainRecord.value
+ if (
+ !receipt.admittedAt ||
+ !Number.isFinite(Date.parse(receipt.admittedAt)) ||
+ Date.parse(receipt.admittedAt) < Date.parse(mainAdmission.runtime.createdAt) ||
+ Date.parse(receipt.admittedAt) - Date.parse(mainAdmission.runtime.createdAt) > 600_000
+ )
+ throw new Error('Runner was not admitted from a fresh container')
+ verifyMainAdmission(
+ mainAdmission,
+ physical,
+ {
+ gitHead: source.gitHead,
+ gitTree: source.gitTree,
+ inputManifestSha256: source.inputManifestSha256,
+ manifestSha256: receipt.sourceManifestSha256,
+ },
+ repoRoot,
+ process.env,
+ 'verify',
+ receipts
+ )
const root = fs.lstatSync(run.runRoot)
if (
!root.isDirectory() ||
@@ -126,6 +191,7 @@ export function verifyPhysicalRunner(run: SubscriptionImageRun): void {
throw new Error('Node24 and actual built Desktop are prerequisites')
requirePixelRenderer()
}
+
export type VendorAttempt = {
sequence: number
provider: string
@@ -187,6 +253,7 @@ export const test = base.extend<Fixtures>({
},
electronApp: async ({ subscriptionRun: run }, use, testInfo) => {
verifyPhysicalRunner(run)
+ verifyNativePrivateKeychain(repoRoot, process.env)
const launchRoot = fs.mkdtempSync(path.join(run.runRoot, 'desktop-'))
fs.chmodSync(launchRoot, 0o700)
const userData = path.join(launchRoot, 'user-data')
@@ -201,6 +268,7 @@ export const test = base.extend<Fixtures>({
'LANG',
'LC_ALL',
'DISPLAY',
+ 'DBUS_SESSION_BUS_ADDRESS',
'XDG_RUNTIME_DIR',
'XAUTHORITY',
'XDG_CONFIG_HOME',
@@ -226,7 +294,10 @@ export const test = base.extend<Fixtures>({
args: [`--user-data-dir=${userData}`, mainEntry],
env: launchEnv,
timeout: 30_000,
- recordVideo: { dir: testInfo.outputPath('video'), size: { width: 1280, height: 720 } },
+ recordVideo: {
+ dir: testInfo.outputPath('video'),
+ size: { width: 1280, height: 720 },
+ },
})
try {
const actual = await app.evaluate(({ app: desktopApp }) => ({
@@ -270,17 +341,30 @@ export const test = base.extend<Fixtures>({
await page.locator('#password-input').fill(process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_PASSWORD!)
await page.getByRole('button', { name: 'Sign in', exact: true }).click()
await expect(loginEmail).toHaveCount(0)
- await expect(page.getByTestId('nav-settings-menu')).toBeVisible({ timeout: 30_000 })
+ await expect(page.getByTestId('nav-settings-menu')).toBeVisible({
+ timeout: 30_000,
+ })
+ verifyPhysicalRunner(run)
+ verifyEncryptedKeyringFiles(process.env, process.getuid!())
+ refusePlaintextSessionFiles([actualUserData, path.join(process.env.HOME!, '.evenfire')])
try {
await use(page)
} finally {
- // End only the owned test session through UI; no shared session reset.
- if (!page.isClosed()) {
- const settings = page.getByTestId('nav-settings-menu')
- if ((await settings.getAttribute('aria-expanded')) !== 'true') await settings.click()
- await expect(settings).toHaveAttribute('aria-expanded', 'true')
- await page.getByTestId('logout-btn').click()
- await expect(page.locator('#email-input')).toBeVisible({ timeout: 20_000 })
+ try {
+ verifyPhysicalRunner(run)
+ verifyEncryptedKeyringFiles(process.env, process.getuid!())
+ refusePlaintextSessionFiles([actualUserData, path.join(process.env.HOME!, '.evenfire')])
+ } finally {
+ // End only the owned test session through UI; no shared session reset.
+ if (!page.isClosed()) {
+ const settings = page.getByTestId('nav-settings-menu')
+ if ((await settings.getAttribute('aria-expanded')) !== 'true') await settings.click()
+ await expect(settings).toHaveAttribute('aria-expanded', 'true')
+ await page.getByTestId('logout-btn').click()
+ await expect(page.locator('#email-input')).toBeVisible({
+ timeout: 20_000,
+ })
+ }
}
}
},
diff --git a/desktop-app/test/e2e-playwright/subscriptionImageRunContract.ts b/desktop-app/test/e2e-playwright/subscriptionImageRunContract.ts
index e18ef6481..5eb4296b8 100644
--- a/desktop-app/test/e2e-playwright/subscriptionImageRunContract.ts
+++ b/desktop-app/test/e2e-playwright/subscriptionImageRunContract.ts
@@ -1,5 +1,6 @@
// E2E_GUARDIAN_IPC_FLOW: pure run admission; no environment files, login, launch, or network at module load.
import path from 'node:path'
+import { verifyPrivateIsolation } from '../../../scripts/tests/lib/subscription-image-runner-contract.mjs'
export type SubscriptionImageProvider = 'grok-subscription' | 'codex-subscription'
export type ProviderBinding = {
@@ -147,11 +148,38 @@ export type RunnerObservation = {
mountInfoSha256: string
}
+export type PrivateProcessObservation = {
+ pid: number
+ uid: number
+ startTime: string
+ executable: string
+ executablePath: string
+ argvSha256: string
+ mountNamespace: string
+ pidNamespace: string
+ userNamespace: string
+}
+export type PrivateSocketObservation = PrivateProcessObservation & {
+ socketPath: string
+ socketInode: string
+}
+export type PrivateIsolationObservation = {
+ homeMountId: string
+ runMountId: string
+ tmpMountId: string
+ admissionMountId: string
+ sessionBus: PrivateSocketObservation & { address: string }
+ display: PrivateSocketObservation & { value: string; xauthorityPath: string }
+ keyring: PrivateProcessObservation
+}
+
/** The main runner inspects physical mounts/namespaces first and seals these observations in its receipt. */
export function verifyRunnerObservation(
expected: RunnerObservation,
actual: RunnerObservation,
- env: NodeJS.ProcessEnv
+ env: NodeJS.ProcessEnv,
+ expectedIsolation?: PrivateIsolationObservation,
+ actualIsolation?: PrivateIsolationObservation
): void {
if (
actual.platform !== 'linux' ||
@@ -185,6 +213,19 @@ export function verifyRunnerObservation(
}
if (!path.isAbsolute(actual.home) || env.HOME !== actual.home)
throw new Error('Runner HOME does not match the OS account')
- if (env.DBUS_SESSION_BUS_ADDRESS || env.SSH_AUTH_SOCK)
+ if (
+ env.SSH_AUTH_SOCK ||
+ (env.DBUS_SESSION_BUS_ADDRESS && (!expectedIsolation || !actualIsolation))
+ )
throw new Error('Inherited DBus/SSH socket is forbidden in the isolated runner')
+ if (expectedIsolation || actualIsolation) {
+ if (!env.SUBSCRIPTION_IMAGE_RUN_ROOT) throw new Error('Private runtime root is required')
+ verifyPrivateIsolation(
+ expectedIsolation,
+ actualIsolation,
+ actual,
+ env,
+ env.SUBSCRIPTION_IMAGE_RUN_ROOT
+ )
+ }
}
diff --git a/desktop-app/test/subscriptionImageRunContract.test.ts b/desktop-app/test/subscriptionImageRunContract.test.ts
index 7f829ee7c..1c7cf4d0a 100644
--- a/desktop-app/test/subscriptionImageRunContract.test.ts
+++ b/desktop-app/test/subscriptionImageRunContract.test.ts
@@ -53,14 +53,20 @@ describe('subscription image load admission', () => {
})
it('requires both real-provider authorizations without downgrading malformed mode', () => {
- const input: NodeJS.ProcessEnv = { ...env(), E2E_SUBSCRIPTION_IMAGE_MODE: 'real' }
+ const input: NodeJS.ProcessEnv = {
+ ...env(),
+ E2E_SUBSCRIPTION_IMAGE_MODE: 'real',
+ }
expect(() => requireSubscriptionImageRun(input)).toThrow(/GROK_REAL_UPSTREAM_CONFIRM/)
input.GROK_REAL_UPSTREAM_CONFIRM = '1'
expect(() => requireSubscriptionImageRun(input)).toThrow(/CODEX_REAL_UPSTREAM_CONFIRM/)
input.CODEX_REAL_UPSTREAM_CONFIRM = '1'
expect(requireSubscriptionImageRun(input).mode).toBe('real')
expect(() =>
- requireSubscriptionImageRun({ ...env(), E2E_SUBSCRIPTION_IMAGE_MODE: 'invalid' })
+ requireSubscriptionImageRun({
+ ...env(),
+ E2E_SUBSCRIPTION_IMAGE_MODE: 'invalid',
+ })
).toThrow(/MODE/)
})
@@ -101,7 +107,10 @@ describe('subscription image load admission', () => {
expect(() =>
verifyRunnerObservation(
observed,
- { ...observed, [field]: typeof observed[field] === 'number' ? 1001 : 'different' },
+ {
+ ...observed,
+ [field]: typeof observed[field] === 'number' ? 1001 : 'different',
+ },
{ HOME: observed.home }
)
).toThrow(/runner|isolation/i)
@@ -113,7 +122,10 @@ describe('subscription image load admission', () => {
verifyRunnerObservation(
observed,
{ ...observed },
- { HOME: observed.home, DBUS_SESSION_BUS_ADDRESS: 'unix:path=/outside/bus' }
+ {
+ HOME: observed.home,
+ DBUS_SESSION_BUS_ADDRESS: 'unix:path=/outside/bus',
+ }
)
).toThrow(/socket/i)
expect(() => verifyRunnerObservation(observed, { ...observed }, { HOME: '/outside' })).toThrow(
@@ -134,4 +146,90 @@ describe('subscription image load admission', () => {
expect(dedicated).not.toMatch(/global-setup|from ['"].*playwright\.config|\.env/)
expect(dedicated).toContain('subscription-image-input.spec.ts')
})
+
+ it('permits only a sealed private bus with matching process, socket and namespace observations', () => {
+ // Metadata-only unit fixtures cannot launch Electron or stand in for the
+ // actual /proc, mount, live FD and encrypted-keyring admission checks.
+ const observed = {
+ platform: 'linux',
+ uid: 1000,
+ gid: 1000,
+ home: '/home/runner',
+ mountNamespace: 'mnt:[123]',
+ pidNamespace: 'pid:[234]',
+ userNamespace: 'user:[345]',
+ mountInfoSha256: 'a'.repeat(64),
+ }
+ const process = (pid: number, executable: string) => ({
+ pid,
+ uid: 1000,
+ startTime: '234',
+ executable,
+ executablePath: `/usr/bin/${executable}`,
+ argvSha256: 'b'.repeat(64),
+ mountNamespace: observed.mountNamespace,
+ pidNamespace: observed.pidNamespace,
+ userNamespace: observed.userNamespace,
+ })
+ const isolation = {
+ homeMountId: '1',
+ runMountId: '2',
+ tmpMountId: '3',
+ admissionMountId: '4',
+ sessionBus: {
+ ...process(101, 'dbus-daemon'),
+ address: 'unix:path=/home/runner/runtime/bus',
+ socketPath: '/home/runner/runtime/bus',
+ socketInode: '700',
+ },
+ display: {
+ ...process(102, 'Xvfb'),
+ value: ':17',
+ socketPath: '/tmp/.X11-unix/X17',
+ socketInode: '701',
+ xauthorityPath: '/home/runner/.Xauthority',
+ },
+ keyring: process(103, 'gnome-keyring-daemon'),
+ }
+ const input = {
+ HOME: observed.home,
+ DISPLAY: isolation.display.value,
+ XAUTHORITY: isolation.display.xauthorityPath,
+ DBUS_SESSION_BUS_ADDRESS: isolation.sessionBus.address,
+ SUBSCRIPTION_IMAGE_RUN_ROOT: '/tmp/unit-root',
+ }
+ expect(() =>
+ verifyRunnerObservation(observed, observed, input, isolation, structuredClone(isolation))
+ ).not.toThrow()
+ expect(() => verifyRunnerObservation(observed, observed, input)).toThrow(/Inherited/)
+ for (const patch of [
+ { pid: 104 },
+ { startTime: 'changed' },
+ { uid: 1001 },
+ { socketInode: 'changed' },
+ { userNamespace: 'user:[different]' },
+ ]) {
+ const changed = structuredClone(isolation)
+ Object.assign(changed.sessionBus, patch)
+ expect(() => verifyRunnerObservation(observed, observed, input, isolation, changed)).toThrow()
+ }
+ expect(() =>
+ verifyRunnerObservation(
+ observed,
+ observed,
+ { ...input, DBUS_SESSION_BUS_ADDRESS: 'unix:path=/outside/bus' },
+ isolation,
+ isolation
+ )
+ ).toThrow()
+ expect(() =>
+ verifyRunnerObservation(
+ observed,
+ observed,
+ { ...input, SSH_AUTH_SOCK: '/outside/agent' },
+ isolation,
+ isolation
+ )
+ ).toThrow()
+ })
})
diff --git a/scripts/e2e/fixtures/subscription-image-admission-pressure.mjs b/scripts/e2e/fixtures/subscription-image-admission-pressure.mjs
new file mode 100644
index 000000000..9a9a79863
--- /dev/null
+++ b/scripts/e2e/fixtures/subscription-image-admission-pressure.mjs
@@ -0,0 +1,222 @@
+// Frozen client surface for the private admission-pressure companion.
+//
+// openAdmissionPressure({ receiptFile, socketPath, deadlineMs }) -> {
+// hold({ maxInFlight }) -> PressureObservation
+// owners() -> PressureObservation
+// release() -> PressureObservation
+// close() -> void
+// }
+//
+// PressureObservation = {
+// pressureRunId: string,
+// maxInFlight: number,
+// owners: { baseline: number, held: number, drained: number },
+// counts: { sameRunAttempts: number, sameRunTickets: number, reservations: number },
+// pids: number[],
+// inspector: { pid: number, startTime: string }
+// }
+//
+// The main-sealed receipt (readMainRecord, uid != container, mode 0600) carries:
+// { kind: 'evenfire-subscription-image-pressure-metadata-v1',
+// profile, context, worktreeId, sourceManifestSha256, podUid,
+// imageId: 'sha256:<64>', pressureRunId, hostRefs: [string, string],
+// maxInFlight: number, socketPath: '/abs/path/pressure.sock' }
+// No credentials travel over this channel. Commands are newline-delimited JSON:
+// { command: 'hello'|'hold'|'owners'|'release'|'close', pressureRunId, maxInFlight? }
+// Replies: { ok: true, ... } or { ok: false, code }.
+// Main owns making socketPath reachable inside the runner and proving the relay
+// under the branch Make lease; this client never invents an endpoint.
+import fs from 'node:fs'
+import net from 'node:net'
+import path from 'node:path'
+import {
+ RunnerAdmissionError,
+ readMainRecord,
+} from '../../tests/lib/subscription-image-runner-contract.mjs'
+
+const refuse = code => {
+ throw new RunnerAdmissionError(code)
+}
+const MAX_FRAME_BYTES = 64 * 1024
+
+export function verifyPressureMetadata(metadata) {
+ if (
+ metadata?.kind !== 'evenfire-subscription-image-pressure-metadata-v1' ||
+ typeof metadata.profile !== 'string' ||
+ metadata.context !== metadata.profile ||
+ !/^[a-f0-9]{40}$/.test(metadata.worktreeId ?? '') ||
+ !/^[a-f0-9]{64}$/.test(metadata.sourceManifestSha256 ?? '') ||
+ typeof metadata.podUid !== 'string' ||
+ !metadata.podUid ||
+ !/^sha256:[a-f0-9]{64}$/.test(metadata.imageId ?? '') ||
+ !/^subscription-image-pressure-[a-f0-9]{12}$/.test(metadata.pressureRunId ?? '') ||
+ !Array.isArray(metadata.hostRefs) ||
+ metadata.hostRefs.length !== 2 ||
+ new Set(metadata.hostRefs).size !== 2 ||
+ metadata.hostRefs.some(value => typeof value !== 'string' || !value) ||
+ !Number.isSafeInteger(metadata.maxInFlight) ||
+ metadata.maxInFlight < 1 ||
+ typeof metadata.socketPath !== 'string' ||
+ !path.isAbsolute(metadata.socketPath)
+ )
+ refuse('ADMISSION_PRESSURE_METADATA_INVALID')
+ return metadata
+}
+
+export function verifyPressureObservation(value, expectation = {}, metadata) {
+ const owners = value?.owners,
+ counts = value?.counts
+ if (
+ value?.ok !== true ||
+ (metadata !== undefined &&
+ (value.pressureRunId !== metadata.pressureRunId ||
+ value.maxInFlight !== metadata.maxInFlight)) ||
+ owners?.baseline !== 0 ||
+ !Number.isSafeInteger(owners?.held) ||
+ owners.held < 0 ||
+ !Number.isSafeInteger(owners?.drained) ||
+ owners.drained < 0 ||
+ counts?.sameRunAttempts !== 0 ||
+ counts?.sameRunTickets !== 0 ||
+ counts?.reservations !== 0 ||
+ !Array.isArray(value?.pids) ||
+ !value.pids.length ||
+ value.pids.some(pid => !Number.isSafeInteger(pid) || pid <= 0) ||
+ !Number.isSafeInteger(value?.inspector?.pid) ||
+ !value.pids.includes(value.inspector.pid) ||
+ typeof value?.inspector?.startTime !== 'string' ||
+ !value.inspector.startTime
+ )
+ refuse('ADMISSION_PRESSURE_OBSERVATION_INVALID')
+ if (expectation.held !== undefined && owners.held !== expectation.held)
+ refuse('ADMISSION_PRESSURE_HELD_MISMATCH')
+ if (expectation.drained !== undefined && owners.drained !== expectation.drained)
+ refuse('ADMISSION_PRESSURE_DRAINED_MISMATCH')
+ return {
+ pressureRunId: value.pressureRunId,
+ maxInFlight: value.maxInFlight,
+ owners: { baseline: 0, held: owners.held, drained: owners.drained },
+ counts: { sameRunAttempts: 0, sameRunTickets: 0, reservations: 0 },
+ pids: [...value.pids],
+ inspector: { pid: value.inspector.pid, startTime: value.inspector.startTime },
+ }
+}
+
+/**
+ * @param {{ receiptFile?: string, deadlineMs?: number }} options
+ */
+export async function openAdmissionPressure({ receiptFile, deadlineMs = 30_000 } = {}) {
+ if (typeof receiptFile !== 'string' || !path.isAbsolute(receiptFile))
+ refuse('ADMISSION_PRESSURE_RECEIPT_REQUIRED')
+ const metadata = verifyPressureMetadata(readMainRecord(receiptFile).value)
+ if (!fs.existsSync(metadata.socketPath)) refuse('ADMISSION_PRESSURE_SOCKET_MISSING')
+ const socket = await new Promise((resolve, reject) => {
+ const candidate = net.connect({ path: metadata.socketPath })
+ const timer = setTimeout(() => {
+ candidate.destroy()
+ reject(new RunnerAdmissionError('ADMISSION_PRESSURE_SOCKET_TIMEOUT'))
+ }, deadlineMs)
+ candidate.once('connect', () => {
+ clearTimeout(timer)
+ resolve(candidate)
+ })
+ candidate.once('error', () => {
+ clearTimeout(timer)
+ reject(new RunnerAdmissionError('ADMISSION_PRESSURE_SOCKET_FAILED'))
+ })
+ })
+ const request = command => {
+ const body = `${JSON.stringify({ ...command, pressureRunId: metadata.pressureRunId })}\n`
+ return new Promise((resolve, reject) => {
+ let buffered = ''
+ const onData = chunk => {
+ buffered += chunk.toString('utf8')
+ if (Buffer.byteLength(buffered, 'utf8') > MAX_FRAME_BYTES) {
+ cleanup()
+ socket.destroy()
+ reject(new RunnerAdmissionError('ADMISSION_PRESSURE_FRAME_BOUND'))
+ return
+ }
+ const end = buffered.indexOf('\n')
+ if (end < 0) return
+ const line = buffered.slice(0, end)
+ cleanup()
+ try {
+ resolve(JSON.parse(line))
+ } catch {
+ reject(new RunnerAdmissionError('ADMISSION_PRESSURE_REPLY_INVALID'))
+ }
+ }
+ const onError = () => {
+ cleanup()
+ socket.destroy()
+ reject(new RunnerAdmissionError('ADMISSION_PRESSURE_SOCKET_FAILED'))
+ }
+ const onClose = () => {
+ cleanup()
+ reject(new RunnerAdmissionError('ADMISSION_PRESSURE_SOCKET_CLOSED'))
+ }
+ const timer = setTimeout(() => {
+ cleanup()
+ socket.destroy()
+ reject(new RunnerAdmissionError('ADMISSION_PRESSURE_COMMAND_TIMEOUT'))
+ }, deadlineMs)
+ const cleanup = () => {
+ clearTimeout(timer)
+ socket.off('data', onData)
+ socket.off('error', onError)
+ socket.off('close', onClose)
+ }
+ socket.on('data', onData)
+ socket.on('error', onError)
+ socket.on('close', onClose)
+ socket.write(body)
+ })
+ }
+ let hello
+ try {
+ hello = await request({ command: 'hello' })
+ if (hello?.ok !== true) refuse('ADMISSION_PRESSURE_HELLO_REFUSED')
+ } catch (err) {
+ socket.destroy()
+ throw err
+ }
+ let stable
+ const observed = (value, expectation = {}) => {
+ const observation = verifyPressureObservation(value, expectation, metadata)
+ if (!stable) stable = observation
+ else if (
+ observation.inspector.pid !== stable.inspector.pid ||
+ observation.inspector.startTime !== stable.inspector.startTime ||
+ observation.pids.join(',') !== stable.pids.join(',')
+ )
+ refuse('ADMISSION_PRESSURE_PROCESS_CHANGED')
+ return observation
+ }
+ observed(hello)
+ return {
+ metadata,
+ async hold({ maxInFlight } = {}) {
+ const expected = maxInFlight ?? metadata.maxInFlight
+ if (!Number.isSafeInteger(expected) || expected < 1 || expected !== metadata.maxInFlight)
+ refuse('ADMISSION_PRESSURE_MAX_IN_FLIGHT')
+ return observed(
+ await request({ command: 'hold', maxInFlight: expected }),
+ { held: expected, drained: 0 }
+ )
+ },
+ async owners() {
+ return observed(await request({ command: 'owners' }))
+ },
+ async release() {
+ return observed(await request({ command: 'release' }))
+ },
+ async close() {
+ try {
+ await request({ command: 'close' })
+ } finally {
+ socket.destroy()
+ }
+ },
+ }
+}
diff --git a/scripts/e2e/fixtures/subscription-image-runner.Dockerfile b/scripts/e2e/fixtures/subscription-image-runner.Dockerfile
new file mode 100644
index 000000000..c1deb8419
--- /dev/null
+++ b/scripts/e2e/fixtures/subscription-image-runner.Dockerfile
@@ -0,0 +1,112 @@
+# E2E-only image. The build context is an explicitly staged source/lock closure,
+# never the repository root. Main reviews the digest-pinned Linux base first.
+#
+# The base reference comes from subscription-image-runner.base-image and is
+# bound into the sealed main admission, so a changed base record cannot be used
+# with a stale admission. The pinned Debian base does not ship sfw; main either
+# provides a reviewed base that does or approves the documented sfw staging
+# path. The apt package names below are self-verified by the command and ldd
+# checks: a missing package or a renamed Debian package fails the build loudly.
+ARG RUNNER_BASE_IMAGE
+FROM ${RUNNER_BASE_IMAGE} AS build
+USER 0:0
+WORKDIR /opt/evenfire
+# Reviewed SocketDev/sfw-free binary staged by the host admission writer. It is
+# a third-party artifact with its own receipt and hash binding, never part of
+# the Git source manifest, and it is the only sfw in the image.
+COPY third-party/sfw-free /usr/local/bin/sfw
+RUN chmod 0755 /usr/local/bin/sfw \
+ && node -e "if (process.versions.node.split('.')[0] !== '24') process.exit(1)" \
+ && command -v apt-get && command -v sfw
+RUN sfw apt-get update && sfw apt-get install -y --no-install-recommends \
+ ca-certificates git python3 make g++ pkg-config libsecret-1-dev \
+ && rm -rf /var/lib/apt/lists/*
+
+# packages/ contains only the package/lock dependency closure plus the existing
+# image codec/padding source. Exclude environment, personal config and logs.
+COPY packages/ ./packages/
+COPY desktop-app/package.json desktop-app/package-lock.json ./desktop-app/
+COPY mcp-host/package.json mcp-host/package-lock.json ./mcp-host/
+RUN sfw npm ci --prefix desktop-app --userconfig=/dev/null --globalconfig=/dev/null \
+ && sfw npm ci --prefix mcp-host --omit=dev --userconfig=/dev/null --globalconfig=/dev/null
+COPY desktop-app/src/ ./desktop-app/src/
+COPY desktop-app/ui/ ./desktop-app/ui/
+COPY desktop-app/assets/ ./desktop-app/assets/
+COPY desktop-app/renderer/ ./desktop-app/renderer/
+COPY desktop-app/tsconfig.json ./desktop-app/tsconfig.json
+COPY desktop-app/scripts/verify-electron-runtime.mjs ./desktop-app/scripts/verify-electron-runtime.mjs
+COPY scripts/tests/lib/subscription-image-runner-contract.mjs \
+ scripts/tests/lib/subscription-image-source-context.mjs ./scripts/tests/lib/
+COPY desktop-app/test/e2e-playwright/ ./desktop-app/test/e2e-playwright/
+COPY scripts/e2e/run-subscription-image-journeys.mjs ./scripts/e2e/run-subscription-image-journeys.mjs
+COPY scripts/e2e/fixtures/ ./scripts/e2e/fixtures/
+COPY subscription-image-input-source.json ./subscription-image-input-source.json
+# Compile-time UI feature flags come from the admitted suite contract. The
+# default false keeps every other suite on the unmodified UI.
+ARG VITE_SHOW_GLOBAL_FILE_SYSTEM_COMPOSER_ITEM=false
+ENV VITE_SHOW_GLOBAL_FILE_SYSTEM_COMPOSER_ITEM=${VITE_SHOW_GLOBAL_FILE_SYSTEM_COMPOSER_ITEM}
+# Recheck the actual allowlisted input around compilation. HEAD/tree/blob IDs
+# were observed by main from the clean checkout, never synthesized in the image.
+RUN node --input-type=module -e "import fs from 'node:fs'; import {verifyInputSource} from './scripts/tests/lib/subscription-image-source-context.mjs'; verifyInputSource(JSON.parse(fs.readFileSync('subscription-image-input-source.json')), process.cwd())" \
+ && npm --prefix desktop-app run verify:electron && npm --prefix desktop-app run build \
+ && node --input-type=module -e "import fs from 'node:fs'; import {verifyInputSource} from './scripts/tests/lib/subscription-image-source-context.mjs'; verifyInputSource(JSON.parse(fs.readFileSync('subscription-image-input-source.json')), process.cwd())"
+
+FROM ${RUNNER_BASE_IMAGE} AS runner
+USER 0:0
+WORKDIR /opt/evenfire
+COPY third-party/sfw-free /usr/local/bin/sfw
+# Runtime X/dbus/keyring and Electron shared libraries. ca-certificates is
+# required because node:*-slim purges it after fetching Node.
+RUN chmod 0755 /usr/local/bin/sfw \
+ && sfw apt-get update && sfw apt-get install -y --no-install-recommends \
+ ca-certificates xvfb xauth dbus gnome-keyring libsecret-1-0 \
+ libnss3 libnspr4 libatk1.0-0 libatk-bridge2.0-0 libatspi2.0-0 \
+ libcups2 libdrm2 libxkbcommon0 libxcomposite1 libxdamage1 libxfixes3 \
+ libxrandr2 libgbm1 libpango-1.0-0 libcairo2 libasound2 libgtk-3-0 \
+ libx11-xcb1 libxcb-dri3-0 libxshmfence1 fonts-liberation \
+ && rm -rf /var/lib/apt/lists/* \
+ && node -e "if (process.versions.node.split('.')[0] !== '24') process.exit(1)" \
+ && command -v Xvfb && command -v xauth && command -v dbus-daemon \
+ && command -v gnome-keyring-daemon
+RUN test ! -e /home/evenfire-e2e \
+ && groupadd --gid 10001 evenfire-e2e \
+ && useradd --uid 10001 --gid 10001 --home-dir /home/evenfire-e2e --create-home evenfire-e2e \
+ && chmod 0700 /home/evenfire-e2e \
+ && mkdir -p /run/evenfire-e2e /runner-admission \
+ && chown 10001:10001 /run/evenfire-e2e /runner-admission \
+ && chmod 0700 /run/evenfire-e2e /runner-admission
+COPY --from=build /opt/evenfire/packages/ ./packages/
+COPY --from=build /opt/evenfire/desktop-app/node_modules/ ./desktop-app/node_modules/
+COPY --from=build /opt/evenfire/desktop-app/dist/ ./desktop-app/dist/
+COPY --from=build /opt/evenfire/desktop-app/ui-dist/ ./desktop-app/ui-dist/
+COPY --from=build /opt/evenfire/desktop-app/assets/ ./desktop-app/assets/
+COPY --from=build /opt/evenfire/desktop-app/renderer/ ./desktop-app/renderer/
+COPY --from=build /opt/evenfire/desktop-app/package.json /opt/evenfire/desktop-app/package-lock.json ./desktop-app/
+COPY --from=build /opt/evenfire/mcp-host/node_modules/ ./mcp-host/node_modules/
+COPY --from=build /opt/evenfire/mcp-host/package.json /opt/evenfire/mcp-host/package-lock.json ./mcp-host/
+RUN ldd desktop-app/node_modules/electron/dist/electron > /tmp/electron-ldd.txt 2>&1 \
+ && ! grep -q 'not found' /tmp/electron-ldd.txt \
+ && rm -f /tmp/electron-ldd.txt
+COPY desktop-app/test/e2e-playwright/subscription-image-input.spec.ts \
+ desktop-app/test/e2e-playwright/playwright.subscription-image.config.ts \
+ desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts \
+ desktop-app/test/e2e-playwright/subscriptionImageRunContract.ts \
+ desktop-app/test/e2e-playwright/subscriptionImageChallenge.ts \
+ desktop-app/test/e2e-playwright/codexImageChallenge.ts ./desktop-app/test/e2e-playwright/
+COPY scripts/e2e/run-subscription-image-journeys.mjs ./scripts/e2e/run-subscription-image-journeys.mjs
+COPY scripts/e2e/fixtures/subscription-image-provider.mjs \
+ scripts/e2e/fixtures/subscription-image-challenge.cjs \
+ scripts/e2e/fixtures/subscription-image-session.mjs \
+ scripts/e2e/fixtures/subscription-image-runner.base-image ./scripts/e2e/fixtures/
+COPY scripts/tests/lib/subscription-image-runner-contract.mjs \
+ scripts/tests/lib/subscription-image-source-context.mjs ./scripts/tests/lib/
+COPY subscription-image-input-source.json ./subscription-image-input-source.json
+RUN node --input-type=module -e "import {sealSourceManifest} from './scripts/e2e/run-subscription-image-journeys.mjs'; sealSourceManifest(process.cwd())" \
+ && chown root:root desktop-app/node_modules/electron/dist/chrome-sandbox \
+ && chmod 4755 desktop-app/node_modules/electron/dist/chrome-sandbox
+ENV HOME=/home/evenfire-e2e USER=evenfire-e2e LOGNAME=evenfire-e2e
+USER 10001:10001
+ENTRYPOINT ["node", "/opt/evenfire/scripts/e2e/run-subscription-image-journeys.mjs"]
+# A default container cannot launch, authenticate, inspect personal state or
+# activate an external fixture. Reviewed physical admission is mandatory.
+CMD ["bootstrap", "/runner-admission/main-admission.json"]
diff --git a/scripts/e2e/fixtures/subscription-image-runner.base-image b/scripts/e2e/fixtures/subscription-image-runner.base-image
new file mode 100644
index 000000000..8f108a22d
--- /dev/null
+++ b/scripts/e2e/fixtures/subscription-image-runner.base-image
@@ -0,0 +1,19 @@
+{
+ "kind": "evenfire-subscription-image-base-image-v1",
+ "reference": "node:24.16.0-slim@sha256:2c87ef9bd3c6a3bd4b472b4bec2ce9d16354b0c574f736c476489d09f560a203",
+ "nodeMajor": 24,
+ "provenance": "mcp-host/Dockerfile.slim:34 pins this Node 24.16.0 slim digest in the same repository; reuse avoids inventing a new base",
+ "requiredCommands": [
+ "sfw",
+ "apt-get",
+ "git",
+ "xauth",
+ "Xvfb",
+ "dbus-daemon",
+ "gnome-keyring-daemon"
+ ],
+ "unprovedPrerequisites": [
+ "node:24.16.0-slim does not ship sfw; main must supply a reviewed base that does or approve staging the host sfw into the build context",
+ "the apt package names are proved by the build command and ldd checks against the pinned Debian suite"
+ ]
+}
diff --git a/scripts/e2e/fixtures/subscription-image-runner.make.fragment b/scripts/e2e/fixtures/subscription-image-runner.make.fragment
new file mode 100644
index 000000000..0a06f546b
--- /dev/null
+++ b/scripts/e2e/fixtures/subscription-image-runner.make.fragment
@@ -0,0 +1,33 @@
+# PR806 subscription-image runner: fragment for the repository Makefile owner.
+# Do not merge this file into the tree; append the target below the existing
+# minikube image targets so it inherits the branch-owned mutation lease.
+#
+# Required operator inputs (all explicit, no defaults invented here):
+# MINIKUBE_PROFILE, CONTROL_API_REAL_PG_CONTEXT (equal to the profile)
+# SUBSCRIPTION_IMAGE_SUITE subscription-image-input | tool-screenshot | gfs-image | admission-recovery
+# SUBSCRIPTION_IMAGE_MODE fixture | real
+# SUBSCRIPTION_IMAGE_SCRATCH absolute scratch dir outside the repository
+# SUBSCRIPTION_IMAGE_FRAMES absolute 0600 frames file (operator supplied)
+# SUBSCRIPTION_IMAGE_BINDINGS absolute 0600 bindings JSON (owned Host/model ids)
+# SUBSCRIPTION_IMAGE_RED_DETECTOR absolute path to the installed RED detector
+.PHONY: minikube-subscription-image-journeys
+minikube-subscription-image-journeys:
+ @test -n "$${MINIKUBE_PROFILE:-}" || { echo "MINIKUBE_PROFILE required"; exit 1; }
+ @test -n "$${CONTROL_API_REAL_PG_CONTEXT:-}" || { echo "CONTROL_API_REAL_PG_CONTEXT required"; exit 1; }
+ @test -n "$${SUBSCRIPTION_IMAGE_SUITE:-}" || { echo "SUBSCRIPTION_IMAGE_SUITE required"; exit 1; }
+ @test -n "$${SUBSCRIPTION_IMAGE_MODE:-}" || { echo "SUBSCRIPTION_IMAGE_MODE required"; exit 1; }
+ @test -n "$${SUBSCRIPTION_IMAGE_SCRATCH:-}" || { echo "SUBSCRIPTION_IMAGE_SCRATCH required"; exit 1; }
+ @test -n "$${SUBSCRIPTION_IMAGE_FRAMES:-}" || { echo "SUBSCRIPTION_IMAGE_FRAMES required"; exit 1; }
+ @test -n "$${SUBSCRIPTION_IMAGE_BINDINGS:-}" || { echo "SUBSCRIPTION_IMAGE_BINDINGS required"; exit 1; }
+ @test -n "$${SUBSCRIPTION_IMAGE_RED_DETECTOR:-}" || { echo "SUBSCRIPTION_IMAGE_RED_DETECTOR required"; exit 1; }
+ @T2_PROJECT_DIR="$(CURDIR)" T2_PROFILE="$(MINIKUBE_PROFILE)" T2_CONTEXT="$(CONTROL_API_REAL_PG_CONTEXT)" \
+ T2_SKIP_LOCK="$(T2_SKIP_LOCK)" T2_LOCK_TOKEN="$(T2_LOCK_TOKEN)" \
+ bash scripts/minikube/with-t2-mutation-lock.sh -- \
+ node scripts/e2e/prepare-subscription-image-admission.mjs \
+ --suite "$$SUBSCRIPTION_IMAGE_SUITE" \
+ --mode "$$SUBSCRIPTION_IMAGE_MODE" \
+ --profile "$$MINIKUBE_PROFILE" \
+ --scratch "$$SUBSCRIPTION_IMAGE_SCRATCH" \
+ --frames "$$SUBSCRIPTION_IMAGE_FRAMES" \
+ --bindings "$$SUBSCRIPTION_IMAGE_BINDINGS" \
+ --red-detector "$$SUBSCRIPTION_IMAGE_RED_DETECTOR"
diff --git a/scripts/e2e/fixtures/subscription-image-session.mjs b/scripts/e2e/fixtures/subscription-image-session.mjs
new file mode 100644
index 000000000..fc98d25e2
--- /dev/null
+++ b/scripts/e2e/fixtures/subscription-image-session.mjs
@@ -0,0 +1,273 @@
+// E2E-only private session bootstrap. Starts one dbus session daemon, one Xvfb
+// display and one gnome-keyring daemon inside the inspected runner container,
+// unlocks the keyring with a per-run random unlock value held only in this
+// process memory, proves the native keytar roundtrip and proves the login
+// keyring file is encrypted. Nothing here launches Electron or touches the host.
+import { execFileSync, spawn } from 'node:child_process'
+import { randomBytes } from 'node:crypto'
+import fs from 'node:fs'
+import path from 'node:path'
+import {
+ RunnerAdmissionError,
+ verifyEncryptedKeyringFiles,
+ verifyNativePrivateKeychain,
+} from '../../tests/lib/subscription-image-runner-contract.mjs'
+
+const refuse = code => {
+ throw new RunnerAdmissionError(code)
+}
+export const SESSION_READY_DEADLINE_MS = 30_000
+const POLL_INTERVAL_MS = 100
+
+export function sessionPaths(home) {
+ return {
+ runtimeDir: path.join(home, 'runtime'),
+ busSocket: path.join(home, 'runtime', 'bus'),
+ xauthority: path.join(home, '.Xauthority'),
+ x11SocketDir: '/tmp/.X11-unix',
+ dataHome: path.join(home, '.local', 'share'),
+ configHome: path.join(home, '.config'),
+ cacheHome: path.join(home, '.cache'),
+ }
+}
+
+async function waitFor(check, code, deadlineMs = SESSION_READY_DEADLINE_MS) {
+ const started = Date.now()
+ for (;;) {
+ let value
+ try {
+ value = check()
+ } catch {
+ value = null
+ }
+ if (value) return value
+ if (Date.now() - started > deadlineMs) refuse(code)
+ await new Promise(resolve => setTimeout(resolve, POLL_INTERVAL_MS))
+ }
+}
+
+function capture(child, limit = 8 * 1024) {
+ const chunks = []
+ let bytes = 0
+ const collect = value => {
+ bytes += value.length
+ if (bytes <= limit) chunks.push(value)
+ }
+ child.stdout?.on('data', collect)
+ child.stderr?.on('data', collect)
+ return () => Buffer.concat(chunks).toString('utf8')
+}
+
+function spawnOrRefuse(command, args, options, code) {
+ const child = spawn(command, args, options)
+ child.once('error', () => {})
+ if (!Number.isSafeInteger(child.pid)) refuse(code)
+ return child
+}
+
+async function waitForExit(child, deadlineMs) {
+ return new Promise(resolve => {
+ const timer = setTimeout(() => resolve({ code: null, signal: 'timeout' }), deadlineMs)
+ child.once('exit', (code, signal) => {
+ clearTimeout(timer)
+ resolve({ code, signal })
+ })
+ })
+}
+
+function privateDirectory(directory) {
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 })
+ const stat = fs.lstatSync(directory)
+ if (!stat.isDirectory() || stat.isSymbolicLink()) refuse('SESSION_DIRECTORY_UNSAFE')
+ fs.chmodSync(directory, 0o700)
+}
+
+async function startSessionBus(paths, home) {
+ const child = spawnOrRefuse(
+ 'dbus-daemon',
+ [
+ '--session',
+ '--fork',
+ `--address=unix:path=${paths.busSocket}`,
+ '--print-address=1',
+ '--print-pid=1',
+ ],
+ { env: { PATH: process.env.PATH, HOME: home }, stdio: ['ignore', 'pipe', 'pipe'] },
+ 'SESSION_DBUS_UNAVAILABLE'
+ )
+ const output = capture(child)
+ const result = await waitForExit(child, SESSION_READY_DEADLINE_MS)
+ if (result.code !== 0) refuse('SESSION_DBUS_START_FAILED')
+ const lines = output()
+ .split('\n')
+ .map(line => line.trim())
+ .filter(Boolean)
+ const address = lines.find(line => /^unix:path=\//.test(line))
+ const pidLine = lines.find(line => /^[1-9][0-9]*$/.test(line))
+ if (!address || !pidLine) refuse('SESSION_DBUS_OUTPUT')
+ const socket = await waitFor(
+ () => {
+ const stat = fs.lstatSync(paths.busSocket)
+ return stat.isSocket() && stat.uid === process.getuid() ? paths.busSocket : null
+ },
+ 'SESSION_DBUS_SOCKET_TIMEOUT'
+ )
+ return { pid: Number(pidLine), address, socketPath: socket }
+}
+
+async function startDisplay(paths, home) {
+ fs.mkdirSync(paths.x11SocketDir, { recursive: true, mode: 0o1777 })
+ fs.chmodSync(paths.x11SocketDir, 0o1777)
+ let displayNumber = 99
+ for (; displayNumber > 10; displayNumber -= 1) {
+ if (!fs.existsSync(path.join(paths.x11SocketDir, `X${displayNumber}`))) break
+ }
+ const value = `:${displayNumber}`
+ try {
+ execFileSync(
+ 'xauth',
+ ['-f', paths.xauthority, 'add', value, 'MIT-MAGIC-COOKIE-1', randomBytes(16).toString('hex')],
+ { env: { PATH: process.env.PATH, HOME: home }, timeout: 10_000, stdio: 'ignore' }
+ )
+ } catch {
+ refuse('SESSION_XAUTH_UNAVAILABLE')
+ }
+ const authority = fs.lstatSync(paths.xauthority)
+ if (
+ !authority.isFile() ||
+ authority.isSymbolicLink() ||
+ authority.uid !== process.getuid() ||
+ (authority.mode & 0o077) !== 0
+ )
+ refuse('SESSION_XAUTHORITY_MODE')
+ const child = spawnOrRefuse(
+ 'Xvfb',
+ [value, '-screen', '0', '1280x720x24', '-nolisten', 'tcp', '-auth', paths.xauthority],
+ { env: { PATH: process.env.PATH, HOME: home }, stdio: ['ignore', 'pipe', 'pipe'] },
+ 'SESSION_XVFB_UNAVAILABLE'
+ )
+ capture(child)
+ let exited = null
+ child.once('exit', (code, signal) => {
+ exited = { code, signal }
+ })
+ const socketPath = path.join(paths.x11SocketDir, `X${displayNumber}`)
+ await waitFor(
+ () => {
+ if (exited) refuse('SESSION_XVFB_EXITED')
+ const socket = fs.lstatSync(socketPath)
+ return socket.isSocket() && socket.uid === process.getuid() ? socketPath : null
+ },
+ 'SESSION_XVFB_SOCKET_TIMEOUT'
+ )
+ return { pid: child.pid, value, socketPath, xauthorityPath: paths.xauthority }
+}
+
+async function startKeyring(paths, home, env, repoRoot) {
+ const unlockValue = randomBytes(32).toString('hex')
+ const child = spawnOrRefuse(
+ 'gnome-keyring-daemon',
+ ['--foreground', '--unlock', '--components=secrets'],
+ { env, stdio: ['pipe', 'pipe', 'pipe'] },
+ 'SESSION_KEYRING_UNAVAILABLE'
+ )
+ capture(child)
+ child.stdin.end(`${unlockValue}\n`)
+ try {
+ await waitFor(
+ () => {
+ const control = path.join(paths.runtimeDir, 'keyring')
+ if (fs.existsSync(control) || fs.existsSync(path.join(paths.dataHome, 'keyrings')))
+ return true
+ return null
+ },
+ 'SESSION_KEYRING_TIMEOUT'
+ )
+ verifyNativePrivateKeychain(repoRoot, env)
+ } catch (err) {
+ try {
+ child.kill('SIGKILL')
+ } catch {
+ // The failure below is the reported outcome.
+ }
+ throw err
+ }
+ verifyEncryptedKeyringFiles(env, process.getuid())
+ return { pid: child.pid, process: child }
+}
+
+export async function startPrivateSession({ home, repoRoot, desktopRequire }) {
+ if (process.platform !== 'linux' || !Number.isSafeInteger(process.getuid?.()))
+ refuse('NONROOT_LINUX_REQUIRED')
+ if (fs.realpathSync(home) !== home) refuse('SESSION_HOME_UNSAFE')
+ if (process.env.HOME !== home) refuse('SESSION_HOME_ENV')
+ if (Number(process.versions.node.split('.')[0]) !== 24) refuse('NODE24_REQUIRED')
+ if (typeof desktopRequire !== 'function') refuse('SESSION_REQUIRE_MISSING')
+ const paths = sessionPaths(home)
+ privateDirectory(paths.runtimeDir)
+ privateDirectory(paths.dataHome)
+ privateDirectory(paths.configHome)
+ privateDirectory(paths.cacheHome)
+ const children = []
+ const stop = () => {
+ for (const child of children) {
+ try {
+ child.kill('SIGTERM')
+ } catch {
+ // Best effort; the container owns final teardown.
+ }
+ }
+ }
+ try {
+ const sessionBus = await startSessionBus(paths, home)
+ children.push({ kill: signal => process.kill(sessionBus.pid, signal) })
+ const display = await startDisplay(paths, home)
+ children.push({ kill: signal => process.kill(display.pid, signal) })
+ const env = {
+ DISPLAY: display.value,
+ XAUTHORITY: paths.xauthority,
+ DBUS_SESSION_BUS_ADDRESS: sessionBus.address,
+ XDG_RUNTIME_DIR: paths.runtimeDir,
+ XDG_DATA_HOME: paths.dataHome,
+ XDG_CONFIG_HOME: paths.configHome,
+ XDG_CACHE_HOME: paths.cacheHome,
+ }
+ const keyring = await startKeyring(paths, home, { ...process.env, ...env }, repoRoot)
+ children.push({ kill: signal => keyring.process.kill(signal) })
+ return {
+ expected: {
+ sessionBus: {
+ pid: sessionBus.pid,
+ address: sessionBus.address,
+ socketPath: sessionBus.socketPath,
+ },
+ display: {
+ pid: display.pid,
+ value: display.value,
+ socketPath: display.socketPath,
+ xauthorityPath: display.xauthorityPath,
+ },
+ keyring: { pid: keyring.pid },
+ },
+ env,
+ assertAlive: () => {
+ for (const [pid, code] of [
+ [sessionBus.pid, 'SESSION_BUS_EXITED'],
+ [display.pid, 'SESSION_DISPLAY_EXITED'],
+ [keyring.pid, 'SESSION_KEYRING_EXITED'],
+ ]) {
+ if (!Number.isSafeInteger(pid)) refuse(code)
+ try {
+ process.kill(pid, 0)
+ } catch {
+ refuse(code)
+ }
+ }
+ },
+ stop,
+ }
+ } catch (err) {
+ stop()
+ throw err
+ }
+}
diff --git a/scripts/e2e/prepare-subscription-image-admission.mjs b/scripts/e2e/prepare-subscription-image-admission.mjs
new file mode 100644
index 000000000..c35cf03cc
--- /dev/null
+++ b/scripts/e2e/prepare-subscription-image-admission.mjs
@@ -0,0 +1,458 @@
+#!/usr/bin/env node
+// Host-side orchestration for the subscription-image runner chain:
+// export allowlisted source -> build pinned image -> create private container ->
+// copy the in-container session observation -> seal docker inspect, stack marker,
+// owned forward records and the main admission -> stream operator frames ->
+// collect receipts. It never reads repository environment files and never prints
+// frame contents. Docker/kubectl stay explicit local CLIs with bounded deadlines.
+import { execFileSync, spawn } from 'node:child_process'
+import { randomBytes } from 'node:crypto'
+import fs from 'node:fs'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import {
+ MAIN_RECEIPT_FILES,
+ PORT_FORWARD_SERVICES,
+ RUNNER_ADMISSION_ROOT,
+ RUNNER_RUN_BASE,
+ RunnerAdmissionError,
+ digest,
+ parsePortsEnv,
+ pinnedBaseImage,
+ resolveSuite,
+ sfwFreeAsset,
+ suiteBuildArgs,
+ verifyThirdPartyArtifact,
+} from '../tests/lib/subscription-image-runner-contract.mjs'
+import { exportSourceContext } from '../tests/lib/subscription-image-source-context.mjs'
+import {
+ buildAdmission,
+ portForwardReceiptFrom,
+ runtimeFromInspect,
+ stackReceiptFrom,
+} from '../tests/lib/subscription-image-main-admission.mjs'
+
+const refuse = code => {
+ throw new RunnerAdmissionError(code)
+}
+const SCRIPT_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+const CONTAINER_HOME = '/home/evenfire-e2e'
+const DEFAULT_CACHE_ROOT = path.join(process.env.HOME ?? '', '.cache', 'clerum', 'minikube-profiles')
+
+function parseArgs(argv) {
+ const values = {}
+ for (let index = 0; index < argv.length; index += 2) {
+ const key = argv[index]
+ const value = argv[index + 1]
+ if (!key?.startsWith('--') || value === undefined) refuse('PREPARE_ARGUMENTS')
+ values[key.slice(2)] = value
+ }
+ return values
+}
+
+function required(values, name) {
+ const value = values[name]
+ if (!value) refuse('PREPARE_ARGUMENTS')
+ return value
+}
+
+function run(command, args, options = {}) {
+ return execFileSync(command, args, {
+ encoding: 'utf8',
+ timeout: options.timeout ?? 900_000,
+ stdio: options.stdio ?? ['ignore', 'pipe', 'pipe'],
+ })
+}
+
+async function waitFor(check, code, deadlineMs, intervalMs = 1000) {
+ const started = Date.now()
+ for (;;) {
+ let value
+ try {
+ value = check()
+ } catch {
+ value = null
+ }
+ if (value) return value
+ if (Date.now() - started > deadlineMs) refuse(code)
+ await new Promise(resolve => setTimeout(resolve, intervalMs))
+ }
+}
+
+function privateDirectory(directory) {
+ fs.mkdirSync(directory, { recursive: true, mode: 0o700 })
+ fs.chmodSync(directory, 0o700)
+}
+
+function writePrivateJson(filename, value) {
+ fs.writeFileSync(filename, JSON.stringify(value), { flag: 'wx', mode: 0o600 })
+}
+
+// Published into the read-only admission mount: readable by the non-root
+// container user, never writable by it. Integrity stays hash-bound.
+function writePublishedJson(filename, value) {
+ fs.writeFileSync(filename, JSON.stringify(value), { flag: 'wx', mode: 0o644 })
+ fs.chmodSync(filename, 0o644)
+}
+
+export async function prepare(argv = process.argv.slice(2)) {
+ const values = parseArgs(argv)
+ const suiteId = required(values, 'suite')
+ const mode = required(values, 'mode')
+ const profile = values.profile ?? process.env.MINIKUBE_PROFILE
+ const context = process.env.CONTROL_API_REAL_PG_CONTEXT ?? profile
+ const scratch = required(values, 'scratch')
+ const framesFile = required(values, 'frames')
+ const detector = required(values, 'red-detector')
+ const bindingsFile = required(values, 'bindings')
+ const cacheRoot = values['cache-root'] ?? DEFAULT_CACHE_ROOT
+ if (!/^[a-z0-9][a-z0-9-]{0,62}$/.test(profile ?? '') || profile === 'clerum-test')
+ refuse('PREPARE_PROFILE_REQUIRED')
+ if (context !== profile) refuse('PREPARE_CONTEXT_MISMATCH')
+ const suite = resolveSuite(suiteId)
+ if (!suite.modes.includes(mode)) refuse('SUITE_MODE_NOT_ADMITTED')
+ if (!path.isAbsolute(scratch) || !path.isAbsolute(framesFile) || !path.isAbsolute(detector))
+ refuse('PREPARE_ABSOLUTE_PATHS')
+ if (scratch.startsWith(`${SCRIPT_ROOT}/`) || scratch === SCRIPT_ROOT)
+ refuse('PREPARE_SCRATCH_INSIDE_REPO')
+ for (const filename of [framesFile, bindingsFile]) {
+ const stat = fs.lstatSync(filename)
+ const parent = path.dirname(filename)
+ if (
+ !stat.isFile() ||
+ stat.isSymbolicLink() ||
+ (stat.mode & 0o777) !== 0o600 ||
+ fs.realpathSync(parent) !== parent
+ )
+ refuse('PREPARE_PRIVATE_INPUT')
+ }
+ if (fs.realpathSync(detector) !== detector) refuse('PREPARE_RED_DETECTOR')
+ const runId = values['run-id'] ?? `subscription-image-${randomBytes(6).toString('hex')}`
+ if (!/^subscription-image-[a-f0-9]{12}$/.test(runId)) refuse('PREPARE_RUN_ID')
+ const containerName = `evenfire-sir-${runId.slice('subscription-image-'.length)}`
+ privateDirectory(scratch)
+ const contextDir = path.join(scratch, 'context')
+ const admissionDir = path.join(scratch, 'admission-host')
+ const receiptDir = path.join(scratch, 'receipts')
+ if (fs.existsSync(contextDir) || fs.existsSync(admissionDir) || fs.existsSync(receiptDir))
+ refuse('PREPARE_SCRATCH_NOT_FRESH')
+ const base = pinnedBaseImage(SCRIPT_ROOT)
+ const source = exportSourceContext(SCRIPT_ROOT, contextDir, detector)
+ if (source.gitHead !== run('git', ['-C', SCRIPT_ROOT, 'rev-parse', 'HEAD']).trim())
+ refuse('PREPARE_SOURCE_RACE')
+ // Third-party artifact (separate allowlist and receipt; never part of the Git
+ // source manifest). The host fetch stays behind the local sfw wrapper.
+ const sfwAsset = sfwFreeAsset(values.arch ?? process.arch)
+ const artifactPath = path.join(scratch, 'third-party-sfw-free')
+ if (values['sfw-artifact']) {
+ if (!path.isAbsolute(values['sfw-artifact'])) refuse('PREPARE_SFW_ARTIFACT_PATH')
+ fs.copyFileSync(values['sfw-artifact'], artifactPath)
+ } else {
+ try {
+ run('which', ['sfw'], { timeout: 10_000 })
+ } catch {
+ refuse('PREPARE_HOST_SFW_REQUIRED')
+ }
+ run(
+ 'sfw',
+ ['curl', '-fsSL', '--retry', '2', '--max-time', '900', '-o', artifactPath, sfwAsset.url],
+ { timeout: 1_000_000, stdio: ['ignore', 'inherit', 'inherit'] }
+ )
+ }
+ fs.chmodSync(artifactPath, 0o755)
+ const thirdPartyArtifact = verifyThirdPartyArtifact({
+ bytes: fs.readFileSync(artifactPath),
+ asset: sfwAsset,
+ })
+ fs.mkdirSync(path.join(contextDir, 'third-party'), { recursive: true, mode: 0o700 })
+ fs.copyFileSync(artifactPath, path.join(contextDir, 'third-party', 'sfw-free'))
+ fs.chmodSync(path.join(contextDir, 'third-party', 'sfw-free'), 0o755)
+ writePrivateJson(path.join(scratch, 'third-party-sfw-free.receipt.json'), thirdPartyArtifact)
+ const buildArgs = ['-f', path.join(SCRIPT_ROOT, 'scripts/e2e/fixtures/subscription-image-runner.Dockerfile'), '-t', containerName, '--build-arg', `RUNNER_BASE_IMAGE=${base.reference}`]
+ for (const [name, value] of Object.entries(suiteBuildArgs(suite)))
+ buildArgs.push('--build-arg', `${name}=${value}`)
+ buildArgs.push(contextDir)
+ run('docker', ['build', ...buildArgs], { stdio: ['ignore', 'inherit', 'inherit'] })
+ privateDirectory(admissionDir)
+ privateDirectory(receiptDir)
+ const volumeName = `${containerName}-admission`
+ try {
+ run('docker', ['volume', 'inspect', volumeName], { timeout: 30_000 })
+ refuse('PREPARE_VOLUME_ALREADY_EXISTS')
+ } catch (err) {
+ if (err instanceof RunnerAdmissionError) throw err
+ }
+ run('docker', ['volume', 'create', volumeName], { timeout: 60_000 })
+ const volumeInspect = JSON.parse(run('docker', ['volume', 'inspect', volumeName]))[0]
+ const mount = `${volumeName}:${RUNNER_ADMISSION_ROOT}:ro`
+ const tmpfs = (target, options) => ['--tmpfs', `${target}:${options}`]
+ const createArgs = [
+ 'create',
+ '--name',
+ containerName,
+ '--user',
+ '10001:10001',
+ '--read-only',
+ '--cap-drop',
+ 'ALL',
+ '--ipc=private',
+ '--network',
+ 'bridge',
+ '--add-host',
+ 'host.docker.internal:host-gateway',
+ ...tmpfs(CONTAINER_HOME, 'rw,nosuid,nodev,mode=0700,uid=10001,gid=10001'),
+ ...tmpfs(RUNNER_RUN_BASE, 'rw,nosuid,nodev,mode=0700,uid=10001,gid=10001'),
+ ...tmpfs('/tmp', 'rw,nosuid,nodev,mode=1777'),
+ '-v',
+ mount,
+ '-e',
+ `SUBSCRIPTION_IMAGE_RUN_ID=${runId}`,
+ containerName,
+ ]
+ run('docker', createArgs)
+ run('docker', ['start', containerName], { stdio: ['ignore', 'inherit', 'inherit'] })
+ const observationFile = path.join(scratch, 'session-observation.json')
+ try {
+ await waitFor(
+ () => {
+ try {
+ run('docker', ['cp', `${containerName}:${RUNNER_RUN_BASE}/session-observation.json`, observationFile], {
+ timeout: 20_000,
+ })
+ } catch {
+ return null
+ }
+ return fs.existsSync(observationFile) ? observationFile : null
+ },
+ 'PREPARE_SESSION_OBSERVATION_TIMEOUT',
+ 120_000
+ )
+ const observation = JSON.parse(fs.readFileSync(observationFile, 'utf8'))
+ if (
+ observation?.kind !== 'evenfire-subscription-image-session-observation-v1' ||
+ observation.runId !== runId ||
+ observation.source?.gitHead !== source.gitHead ||
+ observation.source?.gitTree !== source.gitTree
+ )
+ refuse('PREPARE_SESSION_OBSERVATION_IDENTITY')
+ const inspect = JSON.parse(run('docker', ['inspect', containerName]))[0]
+ const runtime = runtimeFromInspect(inspect, {
+ runId,
+ suiteId,
+ home: observation.observation.home,
+ })
+ const portsEnvRaw = fs.readFileSync(path.join(cacheRoot, profile, 'ports.env'), 'utf8')
+ const ports = parsePortsEnv(portsEnvRaw)
+ const records = {}
+ for (const [kind, expected] of Object.entries(PORT_FORWARD_SERVICES)) {
+ const recordFile = path.join(cacheRoot, profile, 'pids', `${expected.service}.pid`)
+ const localPort = ports[expected.key]
+ if (!Number.isSafeInteger(localPort)) refuse('PREPARE_PORTS_ENV_REQUIRED')
+ run('bash', [
+ path.join(SCRIPT_ROOT, 'scripts/e2e/subscription-image-pf-owner.sh'),
+ 'matches',
+ recordFile,
+ profile,
+ profile,
+ SCRIPT_ROOT,
+ expected.namespace,
+ expected.service,
+ String(localPort),
+ String(expected.remotePort),
+ ])
+ records[kind] = fs.readFileSync(recordFile, 'utf8')
+ }
+ const stack = stackReceiptFrom({
+ profile,
+ context,
+ configMap: JSON.parse(
+ run('kubectl', [
+ `--context=${profile}`,
+ '-n',
+ 'control-plane',
+ 'get',
+ 'configmap',
+ 'clerum-pre-gate-sync-state',
+ '-o',
+ 'json',
+ ])
+ ),
+ portsEnvRaw,
+ fetchedAt: new Date().toISOString(),
+ })
+ if (stack.data.gitHead !== source.gitHead) refuse('PREPARE_STACK_HEAD_MISMATCH')
+ const portForwards = portForwardReceiptFrom({
+ records,
+ profile,
+ context,
+ portsEnvRaw,
+ verifiedAt: new Date().toISOString(),
+ })
+ const inspectReceipt = {
+ container: inspect,
+ securityOptions: JSON.parse(run('docker', ['info', '--format', '{{json .SecurityOptions}}'])),
+ }
+ const files = [
+ [MAIN_RECEIPT_FILES.inspect, inspectReceipt],
+ [MAIN_RECEIPT_FILES.stack, stack],
+ [MAIN_RECEIPT_FILES.portForwards, portForwards],
+ ]
+ const receipts = {}
+ const receiptNames = {
+ [MAIN_RECEIPT_FILES.inspect]: 'inspect',
+ [MAIN_RECEIPT_FILES.stack]: 'stack',
+ [MAIN_RECEIPT_FILES.portForwards]: 'portForwards',
+ }
+ for (const [name, value] of files) {
+ const filename = path.join(admissionDir, name)
+ writePublishedJson(filename, value)
+ receipts[receiptNames[name]] = { value, sha256: digest(JSON.stringify(value)) }
+ }
+ const sealedFilename = path.join(scratch, 'subscription-image-source.json')
+ run('docker', ['cp', `${containerName}:/opt/evenfire/subscription-image-source.json`, sealedFilename])
+ const bindings = JSON.parse(fs.readFileSync(bindingsFile, 'utf8'))
+ const transports = Object.fromEntries(
+ Object.entries(PORT_FORWARD_SERVICES).map(([kind, expected]) => [
+ kind,
+ {
+ origin: `http://host.docker.internal:${ports[expected.key]}`,
+ service: expected.service,
+ profile,
+ context,
+ worktreeId: stack.data.worktreeId,
+ gitHead: stack.data.gitHead,
+ portsReceiptSha256: stack.portsEnvSha256,
+ forwardBindingSha256: digest(records[kind]),
+ },
+ ])
+ )
+ const admission = buildAdmission({
+ runId,
+ suiteId,
+ mode,
+ profile,
+ context,
+ repoRoot: SCRIPT_ROOT,
+ gitHead: source.gitHead,
+ gitTree: source.gitTree,
+ inputManifestSha256: source.inputManifestSha256,
+ sourceManifestSha256: digest(fs.readFileSync(sealedFilename)),
+ imageId: inspect.Image,
+ thirdPartyArtifacts: [thirdPartyArtifact],
+ runtime,
+ observation: observation.observation,
+ networkNamespace: observation.networkNamespace,
+ ipcNamespace: observation.ipcNamespace,
+ stack,
+ receipts: {
+ generatedAt: new Date().toISOString(),
+ dockerInspectSha256: receipts.inspect.sha256,
+ stackMarkerSha256: receipts.stack.sha256,
+ portForwardsSha256: receipts.portForwards.sha256,
+ },
+ bindings,
+ transports,
+ })
+ admission.volume = {
+ name: volumeName,
+ driver: 'local',
+ createdAt: new Date(Date.parse(volumeInspect.CreatedAt)).toISOString(),
+ inspectSha256: digest(JSON.stringify(volumeInspect)),
+ }
+ writePublishedJson(path.join(admissionDir, 'main-admission.json'), admission)
+ const framesPayload = [
+ 'main-admission.json',
+ ...Object.values(MAIN_RECEIPT_FILES),
+ ]
+ .map(name => {
+ const contents = fs.readFileSync(path.join(admissionDir, name))
+ return `${JSON.stringify({ name, contentsBase64: contents.toString('base64') })}\n`
+ })
+ .join('')
+ run(
+ 'docker',
+ [
+ 'run',
+ '--rm',
+ '--user',
+ '10001:10001',
+ '--read-only',
+ '--cap-drop',
+ 'ALL',
+ '--network',
+ 'none',
+ '-v',
+ `${volumeName}:${RUNNER_ADMISSION_ROOT}`,
+ '-i',
+ '--entrypoint',
+ 'node',
+ containerName,
+ '/opt/evenfire/scripts/e2e/run-subscription-image-journeys.mjs',
+ 'admission-write',
+ ],
+ { input: framesPayload, timeout: 120_000 }
+ )
+ const attached = spawn('docker', ['attach', '--sig-proxy=false', containerName], {
+ stdio: ['pipe', 'inherit', 'inherit'],
+ })
+ const frames = fs.readFileSync(framesFile)
+ attached.stdin.end(frames)
+ const result = await new Promise(resolve => attached.once('exit', (code, signal) => resolve({ code, signal })))
+ const status = run('docker', ['wait', containerName], { timeout: 30_000 }).trim()
+ for (const name of ['runner.json', 'journey-result.json', path.basename(observationFile)]) {
+ try {
+ run('docker', ['cp', `${containerName}:${RUNNER_RUN_BASE}/${
+ name === path.basename(observationFile) ? 'session-observation.json' : `${runId}/${name}`
+ }`, path.join(receiptDir, name)], { timeout: 20_000 })
+ } catch {
+ // A missing receipt is reported below by the compact summary.
+ }
+ }
+ const summary = {
+ kind: 'evenfire-subscription-image-prepare-v1',
+ runId,
+ suiteId,
+ mode,
+ profile,
+ container: containerName,
+ attachExit: result.code,
+ attachSignal: result.signal,
+ containerStatus: status,
+ admissionDir,
+ receiptDir,
+ scratch,
+ }
+ console.log(JSON.stringify(summary, null, 2))
+ return status === '0' && result.code === 0 ? 0 : 1
+ } catch (err) {
+ if (values.keep !== 'true') {
+ try {
+ run('docker', ['rm', '-f', containerName], { timeout: 60_000 })
+ } catch {
+ // The original failure is the reported outcome.
+ }
+ try {
+ run('docker', ['volume', 'rm', '-f', `${containerName}-admission`], { timeout: 60_000 })
+ } catch {
+ // The original failure is the reported outcome.
+ }
+ }
+ throw err
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ prepare()
+ .then(code => {
+ process.exitCode = code
+ })
+ .catch(err => {
+ console.error(
+ JSON.stringify({
+ kind: 'prepare-refused',
+ code: err instanceof RunnerAdmissionError ? err.code : 'PREPARE_FAILED',
+ })
+ )
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/e2e/run-subscription-image-journeys.mjs b/scripts/e2e/run-subscription-image-journeys.mjs
new file mode 100644
index 000000000..d7594d327
--- /dev/null
+++ b/scripts/e2e/run-subscription-image-journeys.mjs
@@ -0,0 +1,784 @@
+#!/usr/bin/env node
+// E2E_GUARDIAN_IPC_FLOW: an inspected Linux runner launches the existing visible
+// Desktop journeys. This entry never seeds, logs in through an API, mutates
+// browser storage, or replaces Host/authorization/database/proxy behavior.
+import { spawn } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import fs from 'node:fs'
+import { createRequire } from 'node:module'
+import net from 'node:net'
+import path from 'node:path'
+import { fileURLToPath, pathToFileURL } from 'node:url'
+import {
+ MAIN_RECEIPT_FILES,
+ RUNNER_ADMISSION_ROOT,
+ RUNNER_RUN_BASE,
+ RunnerAdmissionError,
+ SESSION_OBSERVATION_FILE,
+ SESSION_READY_MARKER,
+ admitVendorFrame,
+ digest,
+ inspectPrivateIsolation,
+ observeLinuxRunner,
+ observePrivateIsolation,
+ readPrivateJson,
+ readMainRecord,
+ readPrivateRecord,
+ resolveSuite,
+ verifyMainAdmission,
+ verifyMountIsolation,
+ verifyNativePrivateKeychain,
+ verifySealedArtifacts,
+ verifySuiteReport,
+ verifySourceManifest,
+} from '../tests/lib/subscription-image-runner-contract.mjs'
+import { startPrivateSession } from './fixtures/subscription-image-session.mjs'
+
+const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+const RUN_BASE = RUNNER_RUN_BASE
+const ADMISSION_ROOT = RUNNER_ADMISSION_ROOT
+const MAX_FRAME_BYTES = 4 * 1024 * 1024
+const SESSION_ADMISSION_DEADLINE_MS = 2_700_000
+const VOLUME_MANIFEST_FILE = 'volume-manifest.json'
+const refuse = code => {
+ throw new RunnerAdmissionError(code)
+}
+const privateJson = (filename, value) => {
+ fs.writeFileSync(filename, JSON.stringify(value), {
+ flag: 'wx',
+ mode: 0o600,
+ })
+}
+
+export function runnerPlan() {
+ return {
+ kind: 'evenfire-subscription-image-runner-plan-v1',
+ sourceOnly: true,
+ image:
+ 'Node24 Linux base pinned by digest in subscription-image-runner.base-image; the reviewed base must ship sfw and the OS X/dbus/keyring packages',
+ runtime: {
+ user: '10001:10001',
+ readOnlyRootfs: true,
+ network: 'Dedicated reviewed bridge',
+ ipc: 'private',
+ pid: 'private',
+ capDrop: ['ALL'],
+ chromiumSandbox: 'Enabled; reviewed seccomp permits the required unprivileged namespaces',
+ tmpfs: [
+ '/home/evenfire-e2e:rw,nosuid,nodev,mode=0700,uid=10001,gid=10001',
+ `${RUN_BASE}:rw,nosuid,nodev,mode=0700,uid=10001,gid=10001`,
+ '/tmp:rw,nosuid,nodev,mode=1777',
+ ],
+ readOnlyMount: `${ADMISSION_ROOT}: independently inspected main admission and process bindings only`,
+ },
+ order: [
+ 'Build the minimal reviewed context from the exact owned commit',
+ 'bootstrap: start Xvfb, a private session bus and an encrypted gnome-keyring store, then collect physical account/namespaces/mounts/process/socket observations',
+ 'Main copies the session observation plus docker inspect, stack marker and forward records, then seals the admission in the read-only volume',
+ 'run: stream credentials and actual proxy vendor frames over stdin; no credentials in Docker env/argv or evidence',
+ 'Restore test-only vendor hooks and owned relays under the profile lease after completion',
+ ],
+ fixtureBoundary:
+ 'Only the existing vendor --import module in the actual Grok/Codex proxy processes; fixture results are not G8',
+ sourceContext: [
+ 'desktop-app package/lock, production src/ui/assets, selected six subscription tests/helpers',
+ 'mcp-host package/lock and the exact local package dependency closure',
+ 'new runner/helpers plus existing vendor/challenge files; main-owned true HEAD/tree/blob manifest, no Git metadata',
+ 'No environment files, personal config, runtime logs, credentials or whole-repository COPY',
+ ],
+ missingJourneys: [
+ 'tool screenshot near 20 MiB',
+ 'authorized GFS image flow',
+ 'visible admission saturation and subsequent primary recovery',
+ ],
+ deadlineMs: 3_600_000,
+ }
+}
+
+function sourceIdentity() {
+ const filename = path.join(REPO_ROOT, 'subscription-image-source.json')
+ const stat = fs.lstatSync(filename)
+ if (!stat.isFile() || stat.isSymbolicLink() || stat.size > 4 * 1024 * 1024)
+ refuse('SOURCE_MANIFEST_BOUND')
+ const raw = fs.readFileSync(filename)
+ const manifest = JSON.parse(raw.toString('utf8'))
+ verifySourceManifest(manifest, REPO_ROOT)
+ return {
+ gitHead: manifest.gitHead,
+ gitTree: manifest.gitTree,
+ inputManifestSha256: manifest.inputManifestSha256,
+ manifestSha256: digest(raw),
+ }
+}
+
+export function sealSourceManifest(repoRoot) {
+ const inputBytes = fs.readFileSync(path.join(repoRoot, 'subscription-image-input-source.json'))
+ const input = JSON.parse(inputBytes.toString('utf8'))
+ const files = []
+ const walk = relative => {
+ const filename = path.join(repoRoot, relative),
+ stat = fs.lstatSync(filename)
+ if (stat.isSymbolicLink()) refuse('SOURCE_SYMLINK')
+ if (stat.isDirectory()) {
+ for (const name of fs.readdirSync(filename).sort()) walk(path.join(relative, name))
+ } else if (stat.isFile())
+ files.push({
+ path: relative,
+ bytes: stat.size,
+ sha256: digest(fs.readFileSync(filename)),
+ })
+ else refuse('SOURCE_SPECIAL_FILE')
+ }
+ for (const relative of [
+ 'desktop-app/dist',
+ 'desktop-app/ui-dist',
+ 'desktop-app/test/e2e-playwright',
+ 'desktop-app/package.json',
+ 'desktop-app/package-lock.json',
+ 'mcp-host/package.json',
+ 'mcp-host/package-lock.json',
+ 'scripts/e2e/run-subscription-image-journeys.mjs',
+ 'scripts/e2e/fixtures',
+ 'scripts/tests/lib/subscription-image-runner-contract.mjs',
+ 'scripts/tests/lib/subscription-image-source-context.mjs',
+ 'subscription-image-input-source.json',
+ 'packages',
+ ])
+ walk(relative)
+ const manifest = {
+ kind: 'evenfire-subscription-image-source-v1',
+ gitHead: input.gitHead,
+ gitTree: input.gitTree,
+ inputManifestSha256: digest(inputBytes),
+ files,
+ }
+ verifySourceManifest(manifest, repoRoot)
+ fs.writeFileSync(
+ path.join(repoRoot, 'subscription-image-source.json'),
+ JSON.stringify(manifest),
+ { flag: 'wx', mode: 0o444 }
+ )
+}
+
+function inspectPhysical(bindings) {
+ const physical = observeLinuxRunner()
+ const home = physical.observation.home
+ const stat = fs.lstatSync(home)
+ if (
+ !stat.isDirectory() ||
+ stat.isSymbolicLink() ||
+ stat.uid !== physical.observation.uid ||
+ (stat.mode & 0o077) !== 0
+ )
+ refuse('PRIVATE_HOME_OWNERSHIP')
+ const mountIds = verifyMountIsolation(physical.mounts, home, RUN_BASE, ADMISSION_ROOT)
+ const isolation = inspectPrivateIsolation(
+ bindings,
+ physical.observation,
+ process.env,
+ RUN_BASE,
+ mountIds
+ )
+ return { physical, isolation, source: sourceIdentity() }
+}
+
+async function loopbackRelay(target) {
+ const endpoint = new URL(target)
+ const sockets = new Set()
+ // A fixed-target byte relay preserves HTTP bodies and RPC WebSocket
+ // upgrades. It never treats a client request URL as a new proxy target.
+ const server = net.createServer(socket => {
+ const upstream = net.connect({
+ host: endpoint.hostname.replace(/^\[|\]$/g, ''),
+ port: Number(endpoint.port),
+ })
+ sockets.add(socket)
+ sockets.add(upstream)
+ for (const peer of [socket, upstream]) {
+ peer.setTimeout(180_000, () => {
+ socket.destroy()
+ upstream.destroy()
+ })
+ peer.once('error', () => {
+ socket.destroy()
+ upstream.destroy()
+ })
+ peer.once('close', () => sockets.delete(peer))
+ }
+ socket.once('close', () => upstream.destroy())
+ upstream.once('close', () => socket.destroy())
+ socket.pipe(upstream)
+ upstream.pipe(socket)
+ socket.once('close', () => sockets.delete(socket))
+ })
+ await new Promise((resolve, reject) => {
+ server.once('error', reject)
+ server.listen(0, '127.0.0.1', () => resolve(undefined))
+ })
+ const address = server.address()
+ if (!address || typeof address === 'string')
+ throw new RunnerAdmissionError('LOOPBACK_RELAY_NOT_BOUND')
+ return {
+ url: `http://127.0.0.1:${address.port}`,
+ close: () =>
+ new Promise(resolve => {
+ for (const socket of sockets) socket.destroy()
+ server.close(resolve)
+ }),
+ }
+}
+
+function inputFrames(admission, root) {
+ let buffered = Buffer.alloc(0),
+ receivedLogin = false
+ const previous = new Map(admission.bindings.map(binding => [binding.provider, []]))
+ const vendorReady = new Set()
+ let resolveReady, rejectReady, rejectFailure
+ const ready = new Promise((resolve, reject) => {
+ resolveReady = resolve
+ rejectReady = reject
+ })
+ const failure = new Promise((_resolve, reject) => {
+ rejectFailure = reject
+ })
+ // Retain a handler immediately, including before the runner starts waiting.
+ void failure.catch(() => {})
+ const fail = err => {
+ rejectReady(err)
+ rejectFailure(err)
+ }
+ const timer = setTimeout(
+ () => rejectReady(new RunnerAdmissionError('PRIVATE_INPUT_DEADLINE')),
+ 30_000
+ )
+ const accept = frame => {
+ if (frame.kind === 'evenfire-subscription-image-login-v1') {
+ if (
+ receivedLogin ||
+ frame.runId !== admission.runId ||
+ typeof frame.email !== 'string' ||
+ frame.email.length > 320 ||
+ typeof frame.password !== 'string' ||
+ !frame.password ||
+ frame.password.length > 1024
+ )
+ refuse('PRIVATE_LOGIN_FRAME')
+ // The authorized test login stays only in this process and the existing
+ // visible-login fixture's child environment. Never persist or echo it.
+ process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_EMAIL = frame.email
+ process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_PASSWORD = frame.password
+ receivedLogin = true
+ } else {
+ const binding = admission.bindings.find(candidate => candidate.provider === frame.provider)
+ if (admission.mode !== 'fixture' || !binding) refuse('VENDOR_FRAME_NOT_AUTHORIZED')
+ const source = admission.vendorSources?.[frame.provider]
+ if (
+ !source?.podUid ||
+ !/^sha256:[a-f0-9]{64}$/.test(source.imageId) ||
+ !/^[a-f0-9]{64}$/.test(source.fixtureImportSha256) ||
+ source.profile !== admission.profile ||
+ source.gitHead !== admission.gitHead
+ )
+ refuse('PHYSICAL_VENDOR_SOURCE_REQUIRED')
+ const ledger = admitVendorFrame(
+ frame,
+ admission.runId,
+ binding,
+ source,
+ previous.get(frame.provider)
+ )
+ const destination = path.join(root, `${frame.provider}-vendor.json`),
+ temporary = `${destination}.next`
+ fs.writeFileSync(temporary, JSON.stringify(ledger), {
+ flag: 'wx',
+ mode: 0o600,
+ })
+ fs.renameSync(temporary, destination)
+ previous.set(frame.provider, ledger.attempts)
+ vendorReady.add(frame.provider)
+ }
+ if (receivedLogin && (admission.mode === 'real' || vendorReady.size === 2)) {
+ clearTimeout(timer)
+ resolveReady()
+ }
+ }
+ const onData = chunk => {
+ try {
+ if (buffered.length + chunk.length > MAX_FRAME_BYTES) refuse('PRIVATE_INPUT_FRAME_BOUND')
+ buffered = Buffer.concat([buffered, chunk])
+ for (let end; (end = buffered.indexOf(10)) !== -1; ) {
+ const line = buffered.subarray(0, end)
+ buffered = buffered.subarray(end + 1)
+ if (!line.length) refuse('PRIVATE_INPUT_FRAME_EMPTY')
+ try {
+ accept(JSON.parse(line.toString('utf8')))
+ } finally {
+ line.fill(0)
+ }
+ }
+ } catch (err) {
+ fail(err)
+ process.stdin.pause()
+ }
+ }
+ process.stdin.on('data', onData)
+ const onEnd = () => {
+ if (!receivedLogin || admission.mode === 'fixture')
+ fail(new RunnerAdmissionError('PRIVATE_INPUT_ENDED'))
+ }
+ process.stdin.once('end', onEnd)
+ const onError = () => fail(new RunnerAdmissionError('PRIVATE_INPUT_FAILED'))
+ process.stdin.once('error', onError)
+ return {
+ ready,
+ failure,
+ close: () => {
+ clearTimeout(timer)
+ process.stdin.off('data', onData)
+ process.stdin.off('end', onEnd)
+ process.stdin.off('error', onError)
+ process.stdin.pause()
+ buffered.fill(0)
+ },
+ }
+}
+
+async function prepare(admissionFile) {
+ process.umask(0o077)
+ const mainRecord = readMainRecord(admissionFile)
+ const admission = mainRecord.value
+ const inspected = inspectPhysical(admission.isolation)
+ const receipts = {
+ inspect: readMainRecord(path.join(ADMISSION_ROOT, MAIN_RECEIPT_FILES.inspect)),
+ stack: readMainRecord(path.join(ADMISSION_ROOT, MAIN_RECEIPT_FILES.stack)),
+ portForwards: readMainRecord(path.join(ADMISSION_ROOT, MAIN_RECEIPT_FILES.portForwards)),
+ }
+ const volumeManifest = readMainRecord(path.join(ADMISSION_ROOT, VOLUME_MANIFEST_FILE)).value
+ if (
+ volumeManifest?.kind !== 'evenfire-subscription-image-volume-manifest-v1' ||
+ !Array.isArray(volumeManifest.manifest) ||
+ volumeManifest.manifest.length !== 4
+ )
+ refuse('ADMISSION_VOLUME_MANIFEST')
+ for (const row of volumeManifest.manifest) {
+ const record = readMainRecord(path.join(ADMISSION_ROOT, row.name))
+ if (record.sha256 !== row.sha256 || fs.statSync(path.join(ADMISSION_ROOT, row.name)).size !== row.bytes)
+ refuse('ADMISSION_VOLUME_MANIFEST_MISMATCH')
+ }
+ verifyMainAdmission(
+ admission,
+ inspected.physical,
+ inspected.source,
+ REPO_ROOT,
+ process.env,
+ 'admit',
+ receipts
+ )
+ verifySealedArtifacts(admission)
+ const suite = resolveSuite(admission.suiteId)
+ const root = path.join(RUN_BASE, admission.runId)
+ fs.writeFileSync(path.join(RUN_BASE, 'runner-created'), admission.runId, {
+ flag: 'wx',
+ mode: 0o600,
+ })
+ fs.mkdirSync(root, { mode: 0o700 })
+ const rest = await loopbackRelay(admission.transports.rest.origin)
+ let rpc, channel
+ try {
+ rpc = await loopbackRelay(admission.transports.rpc.origin)
+ /** @type {NodeJS.ProcessEnv} */
+ const env = {}
+ for (const name of [
+ 'PATH',
+ 'HOME',
+ 'USER',
+ 'LOGNAME',
+ 'LANG',
+ 'LC_ALL',
+ 'DISPLAY',
+ 'DBUS_SESSION_BUS_ADDRESS',
+ 'XAUTHORITY',
+ 'XDG_RUNTIME_DIR',
+ 'XDG_CONFIG_HOME',
+ 'XDG_CACHE_HOME',
+ 'XDG_DATA_HOME',
+ 'TMPDIR',
+ 'GROK_REAL_UPSTREAM_CONFIRM',
+ 'CODEX_REAL_UPSTREAM_CONFIRM',
+ 'SUBSCRIPTION_IMAGE_FIXTURE_CONFIRM',
+ ]) {
+ if (process.env[name]) env[name] = process.env[name]
+ }
+ Object.assign(env, {
+ E2E_SUBSCRIPTION_IMAGE_INPUT: '1',
+ E2E_SUBSCRIPTION_IMAGE_MODE: admission.mode,
+ E2E_SUBSCRIPTION_IMAGE_RUN_ID: admission.runId,
+ E2E_SUBSCRIPTION_IMAGE_SUITE: admission.suiteId,
+ MINIKUBE_PROFILE: admission.profile,
+ CONTROL_API_REAL_PG_CONTEXT: admission.context,
+ SUBSCRIPTION_IMAGE_RUN_ROOT: root,
+ SUBSCRIPTION_IMAGE_RUNNER_RECEIPT: path.join(root, 'runner.json'),
+ EXTERNAL_REST_API_BASE_URL: rest.url,
+ RPC_PROXY_BASE_URL: rpc.url,
+ })
+ for (const binding of admission.bindings) {
+ const prefix = binding.provider === 'grok-subscription' ? 'GROK' : 'CODEX'
+ for (const [field, suffix] of [
+ ['hostRef', 'HOST_REF'],
+ ['hostLabel', 'HOST_LABEL'],
+ ['modelId', 'MODEL'],
+ ['modelLabel', 'MODEL_LABEL'],
+ ['unsupportedModelId', 'UNSUPPORTED_MODEL'],
+ ['unsupportedModelLabel', 'UNSUPPORTED_MODEL_LABEL'],
+ ])
+ env[`E2E_${prefix}_IMAGE_${suffix}`] = binding[field]
+ if (admission.mode === 'fixture')
+ env[`E2E_${prefix}_IMAGE_EVIDENCE_PATH`] = path.join(
+ root,
+ `${binding.provider}-vendor.json`
+ )
+ }
+ channel = inputFrames(admission, root)
+ await channel.ready
+ env.E2E_SUBSCRIPTION_IMAGE_LOGIN_EMAIL = process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_EMAIL
+ env.E2E_SUBSCRIPTION_IMAGE_LOGIN_PASSWORD = process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_PASSWORD
+ const contract = await import(
+ pathToFileURL(
+ path.join(REPO_ROOT, 'desktop-app/test/e2e-playwright/subscriptionImageRunContract.ts')
+ ).href
+ )
+ const run = contract.requireSubscriptionImageRun(env)
+ const desktopRequire = createRequire(path.join(REPO_ROOT, 'desktop-app/package.json'))
+ const electronPath = desktopRequire('electron')
+ if (typeof electronPath !== 'string' || !fs.statSync(electronPath).isFile())
+ refuse('LINUX_ELECTRON_REQUIRED')
+ const fd = fs.openSync(electronPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW)
+ try {
+ const magic = Buffer.alloc(4)
+ if (fs.readSync(fd, magic, 0, 4, 0) !== 4 || magic.toString('hex') !== '7f454c46')
+ refuse('LINUX_ELECTRON_REQUIRED')
+ } finally {
+ fs.closeSync(fd)
+ }
+ createRequire(path.join(REPO_ROOT, 'scripts/e2e/fixtures/subscription-image-challenge.cjs'))(
+ './subscription-image-challenge.cjs'
+ ).requirePixelRenderer()
+ verifyNativePrivateKeychain(REPO_ROOT, env)
+ const physical = observeLinuxRunner()
+ const mountIds = verifyMountIsolation(
+ physical.mounts,
+ physical.observation.home,
+ RUN_BASE,
+ ADMISSION_ROOT
+ )
+ const isolation = observePrivateIsolation(
+ admission.isolation,
+ physical.observation,
+ env,
+ root,
+ mountIds
+ )
+ privateJson(run.runnerReceipt, {
+ kind: 'evenfire-subscription-image-runner-v2',
+ runId: run.runId,
+ repoRoot: REPO_ROOT,
+ gitHead: inspected.source.gitHead,
+ gitTree: inspected.source.gitTree,
+ inputManifestSha256: inspected.source.inputManifestSha256,
+ profile: run.profile,
+ context: run.context,
+ restUrl: run.restUrl,
+ rpcUrl: run.rpcUrl,
+ bindings: run.bindings,
+ observation: physical.observation,
+ isolation,
+ mainAdmissionFile: admissionFile,
+ mainAdmissionSha256: mainRecord.sha256,
+ admittedAt: new Date().toISOString(),
+ sourceManifestSha256: inspected.source.manifestSha256,
+ mode: run.mode,
+ suiteId: run.suiteId,
+ })
+ return {
+ run,
+ suite,
+ env,
+ root,
+ desktopRequire,
+ inputFailure: channel.failure,
+ close: async () => {
+ channel.close()
+ await Promise.all([rest.close(), rpc.close()])
+ },
+ }
+ } catch (err) {
+ channel?.close()
+ await Promise.all([rest.close(), rpc?.close()])
+ throw err
+ }
+}
+
+async function runJourneys(prepared) {
+ const cli = prepared.desktopRequire.resolve('@playwright/test/cli')
+ const child = spawn(
+ process.execPath,
+ [
+ cli,
+ 'test',
+ `--config=${prepared.suite.configFile}`,
+ '--reporter=json',
+ ],
+ {
+ cwd: path.join(REPO_ROOT, 'desktop-app'),
+ env: prepared.env,
+ detached: true,
+ stdio: ['ignore', 'pipe', 'pipe'],
+ }
+ )
+ // Do not persist raw child diagnostics, trace contents, credentials or image
+ // bodies. Artifacts remain in this private tmpfs until main reviews export.
+ const hashes = { stdout: createHash('sha256'), stderr: createHash('sha256') }
+ const reportChunks = []
+ let reportBytes = 0
+ child.stdout.on('data', value => {
+ hashes.stdout.update(value)
+ reportBytes += value.length
+ if (reportBytes <= 16 * 1024 * 1024) reportChunks.push(value)
+ else stop('report-bound')
+ })
+ child.stderr.on('data', value => hashes.stderr.update(value))
+ let cancellationCause
+ let hardStop
+ const terminate = signal => {
+ if (Number.isInteger(child.pid) && child.exitCode === null) {
+ try {
+ process.kill(-child.pid, signal)
+ } catch (err) {
+ if (err.code !== 'ESRCH') throw err
+ }
+ }
+ }
+ const stop = cause => {
+ if (cancellationCause) return
+ cancellationCause = cause
+ terminate('SIGTERM')
+ hardStop = setTimeout(() => terminate('SIGKILL'), 10_000)
+ }
+ const signalStop = () => stop('signal')
+ process.once('SIGTERM', signalStop)
+ process.once('SIGINT', signalStop)
+ let inputFailed = false
+ void prepared.inputFailure.catch(() => {
+ inputFailed = true
+ stop('input')
+ })
+ const deadline = setTimeout(() => stop('deadline'), runnerPlan().deadlineMs)
+ let result
+ try {
+ result = await new Promise((resolve, reject) => {
+ child.once('error', reject)
+ child.once('exit', (code, signal) => resolve({ code, signal }))
+ })
+ } finally {
+ clearTimeout(deadline)
+ clearTimeout(hardStop)
+ process.off('SIGTERM', signalStop)
+ process.off('SIGINT', signalStop)
+ }
+ let namedCases, reportFailure
+ try {
+ namedCases = verifySuiteReport(
+ JSON.parse(Buffer.concat(reportChunks).toString('utf8')),
+ prepared.run.mode,
+ prepared.suite,
+ path.join(REPO_ROOT, prepared.suite.specFile)
+ )
+ } catch (err) {
+ reportFailure = err instanceof RunnerAdmissionError ? err.code : 'JOURNEY_REPORT_INVALID'
+ }
+ // Only case identities/status and digests leave memory; reporter diagnostics
+ // may contain auth details and are never copied into the receipt.
+ privateJson(path.join(prepared.root, 'journey-result.json'), {
+ kind: 'evenfire-subscription-image-result-v1',
+ runId: prepared.run.runId,
+ suiteId: prepared.suite.suiteId,
+ mode: prepared.run.mode,
+ producerExit: result.code,
+ signal: result.signal,
+ cancellationCause,
+ inputFailed,
+ stdoutSha256: hashes.stdout.digest('hex'),
+ stderrSha256: hashes.stderr.digest('hex'),
+ namedCases,
+ reportFailure,
+ evidenceClass:
+ prepared.run.mode === 'fixture' ? 'external-vendor-fixture' : 'real-subscription',
+ })
+ return result.code === 0 && !cancellationCause && !inputFailed && !reportFailure ? 0 : 1
+}
+
+async function runAdmission(input) {
+ const prepared = await prepare(input)
+ try {
+ console.log(
+ JSON.stringify({
+ kind: 'runner-admitted',
+ runId: prepared.run.runId,
+ mode: prepared.run.mode,
+ suiteId: prepared.suite.suiteId,
+ receipt: prepared.run.runnerReceipt,
+ })
+ )
+ return await runJourneys(prepared)
+ } finally {
+ await prepared.close()
+ }
+}
+
+// Prep phase of the per-run named volume. Reads the four main-sealed JSON files
+// as base64 NDJSON on stdin (host originals stay 0600 on the host) and writes
+// them 0600 owned by the container user, then exits. The run container mounts
+// the same volume read-only.
+async function admissionWrite() {
+ process.umask(0o077)
+ const expected = ['main-admission.json', ...Object.values(MAIN_RECEIPT_FILES)]
+ const chunks = []
+ let bytes = 0
+ for await (const chunk of process.stdin) {
+ bytes += chunk.length
+ if (bytes > 4 * 1024 * 1024) refuse('ADMISSION_WRITE_BOUND')
+ chunks.push(chunk)
+ }
+ const lines = Buffer.concat(chunks)
+ .toString('utf8')
+ .split('\n')
+ .filter(Boolean)
+ if (lines.length !== expected.length) refuse('ADMISSION_WRITE_FRAMES')
+ const manifest = []
+ for (const line of lines) {
+ const frame = JSON.parse(line)
+ if (!expected.includes(frame.name)) refuse('ADMISSION_WRITE_NAME')
+ const payload = Buffer.from(frame.contentsBase64, 'base64')
+ fs.writeFileSync(path.join(ADMISSION_ROOT, frame.name), payload, { flag: 'wx', mode: 0o600 })
+ manifest.push({ name: frame.name, sha256: digest(payload), bytes: payload.length })
+ }
+ fs.writeFileSync(
+ path.join(ADMISSION_ROOT, VOLUME_MANIFEST_FILE),
+ JSON.stringify({ kind: 'evenfire-subscription-image-volume-manifest-v1', manifest }),
+ { flag: 'wx', mode: 0o600 }
+ )
+ console.log(JSON.stringify({ kind: 'runner-admission-written', manifest }))
+ return 0
+}
+
+async function waitForMainAdmission(admissionFile) {
+ const deadline = Date.now() + SESSION_ADMISSION_DEADLINE_MS
+ let interrupted = false
+ const onSignal = () => {
+ interrupted = true
+ }
+ process.once('SIGTERM', onSignal)
+ process.once('SIGINT', onSignal)
+ try {
+ for (;;) {
+ if (interrupted) refuse('RUNNER_INTERRUPTED')
+ if (fs.existsSync(admissionFile)) return
+ if (Date.now() > deadline) refuse('MAIN_ADMISSION_TIMEOUT')
+ await new Promise(resolve => setTimeout(resolve, 1000))
+ }
+ } finally {
+ process.off('SIGTERM', onSignal)
+ process.off('SIGINT', onSignal)
+ }
+}
+
+// Inspected bootstrap: create the private session, publish its physical
+// observation for main, then wait for the sealed admission before launching.
+async function bootstrap(admissionFile) {
+ process.umask(0o077)
+ const runId = process.env.SUBSCRIPTION_IMAGE_RUN_ID
+ if (!/^subscription-image-[a-f0-9]{12}$/.test(runId ?? ''))
+ refuse('SUBSCRIPTION_IMAGE_RUN_ID_REQUIRED')
+ if (fs.existsSync(path.join(RUN_BASE, SESSION_READY_MARKER)))
+ refuse('SESSION_ALREADY_BOOTSTRAPPED')
+ const initial = observeLinuxRunner()
+ const home = initial.observation.home
+ const desktopRequire = createRequire(path.join(REPO_ROOT, 'desktop-app/package.json'))
+ privateJson(path.join(RUN_BASE, SESSION_READY_MARKER), runId)
+ const session = await startPrivateSession({ home, repoRoot: REPO_ROOT, desktopRequire })
+ for (const [name, value] of Object.entries(session.env)) process.env[name] = value
+ const physical = observeLinuxRunner()
+ const mountIds = verifyMountIsolation(physical.mounts, home, RUN_BASE, ADMISSION_ROOT)
+ const isolation = observePrivateIsolation(
+ session.expected,
+ physical.observation,
+ process.env,
+ RUN_BASE,
+ mountIds
+ )
+ const observationFile = path.join(RUN_BASE, SESSION_OBSERVATION_FILE)
+ privateJson(observationFile, {
+ kind: 'evenfire-subscription-image-session-observation-v1',
+ runId,
+ observation: physical.observation,
+ networkNamespace: physical.networkNamespace,
+ ipcNamespace: physical.ipcNamespace,
+ isolation,
+ source: sourceIdentity(),
+ startedAt: new Date().toISOString(),
+ })
+ console.log(JSON.stringify({ kind: 'runner-session-ready', output: observationFile }))
+ try {
+ await waitForMainAdmission(admissionFile)
+ session.assertAlive()
+ return await runAdmission(admissionFile)
+ } catch (err) {
+ session.stop()
+ throw err
+ }
+}
+
+export async function main(args = process.argv.slice(2)) {
+ const [mode = 'run', input] = args
+ if (args.length > 2) refuse('RUNNER_ARGUMENTS')
+ if (mode === 'plan') {
+ console.log(JSON.stringify(runnerPlan(), null, 2))
+ return 0
+ }
+ if (mode === 'admission-write') {
+ if (input) refuse('RUNNER_ARGUMENTS')
+ return admissionWrite()
+ }
+ if (!['bootstrap', 'inspect', 'run'].includes(mode) || !input || !path.isAbsolute(input))
+ refuse('RUNNER_ARGUMENTS')
+ if (path.dirname(input) !== ADMISSION_ROOT) refuse('MAIN_ADMISSION_PATH')
+ if (mode === 'inspect') {
+ observeLinuxRunner()
+ const inspected = inspectPhysical(readPrivateJson(input))
+ const output = path.join(RUN_BASE, 'physical-inspection.json')
+ privateJson(output, {
+ kind: 'evenfire-subscription-image-inspection-v1',
+ ...inspected,
+ })
+ console.log(JSON.stringify({ kind: 'runner-inspected', output }))
+ return 0
+ }
+ if (mode === 'bootstrap') return bootstrap(input)
+ return runAdmission(input)
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ main()
+ .then(code => {
+ process.exitCode = code
+ })
+ .catch(err => {
+ console.error(
+ JSON.stringify({
+ kind: 'runner-refused',
+ code: err instanceof RunnerAdmissionError ? err.code : 'RUNNER_OPERATION_FAILED',
+ })
+ )
+ process.exitCode = 1
+ })
+}
diff --git a/scripts/e2e/subscription-image-pf-owner.sh b/scripts/e2e/subscription-image-pf-owner.sh
new file mode 100644
index 000000000..aebadafa5
--- /dev/null
+++ b/scripts/e2e/subscription-image-pf-owner.sh
@@ -0,0 +1,43 @@
+#!/usr/bin/env bash
+# Fixed CLI surface for the two owned forwards the subscription-image runner
+# consumes. No source path or command body comes from caller arguments; each
+# operation has a literal call into the existing ownership library.
+set -euo pipefail
+
+fail() { printf '%s\n' 'Invalid subscription-image forward ownership request' >&2; exit 2; }
+SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd -P)"
+WORKTREE="$(cd -- "${SCRIPT_DIR}/../.." && pwd -P)"
+operation="${1:-}"
+[[ $# -gt 0 ]] || fail
+shift
+case "$operation" in
+ matches) [[ $# -eq 8 ]] || fail ;;
+ *) fail ;;
+esac
+
+args=("$@")
+record="$1" profile="$2" context="$3" worktree="$4" namespace="$5" service="$6"
+local_port="$7" remote_port="$8"
+[[ "$profile" =~ ^[a-z0-9][a-z0-9-]{0,62}$ && ${#profile} -le 63 ]] || fail
+[[ "$profile" == "${MINIKUBE_PROFILE:-}" && "$context" == "$profile" &&
+ "$context" == "${CONTROL_API_REAL_PG_CONTEXT:-}" && "$worktree" == "$WORKTREE" ]] || fail
+case "$namespace/$service" in
+ profiles/external-rest-api) [[ "$remote_port" == 8091 ]] || fail ;;
+ rpc-proxy/rpc-proxy) [[ "$remote_port" == 8094 ]] || fail ;;
+ *) fail ;;
+esac
+[[ "$local_port" =~ ^[0-9]{4,5}$ ]] || fail
+(( 10#$local_port >= 1024 && 10#$local_port <= 65535 )) || fail
+
+cache_root="${MINIKUBE_PROFILE_CACHE_ROOT:-${HOME}/.cache/clerum/minikube-profiles}"
+[[ "$cache_root" == /* ]] || fail
+pid_directory="$(cd -- "${cache_root}/${profile}/pids" && pwd -P)" || fail
+[[ "${record%/*}" == "$pid_directory" ]] || fail
+[[ "${record##*/}" == "${service}.pid" ]] || fail
+[[ ! -L "$record" && -f "$record" ]] || fail
+
+# shellcheck source=scripts/minikube/port-forward-owner.sh
+source "${SCRIPT_DIR}/../minikube/port-forward-owner.sh"
+case "$operation" in
+ matches) pf_owner_record_process_matches "${args[@]}" ;;
+esac
diff --git a/scripts/tests/lib/control-api-authorize-memory-companion.ts b/scripts/tests/lib/control-api-authorize-memory-companion.ts
index 4d0c0d316..c0028f9cc 100644
--- a/scripts/tests/lib/control-api-authorize-memory-companion.ts
+++ b/scripts/tests/lib/control-api-authorize-memory-companion.ts
@@ -1,4 +1,4 @@
-/** Test-only in-pod driver. Production signing, HTTP, PostgreSQL and terminal lifecycle remain real. */
+/** Test-only in-pod driver. Signing, HTTP, PostgreSQL and issued-ticket expiry remain real. */
import fs from 'node:fs'
import path from 'node:path'
import http from 'node:http'
@@ -7,6 +7,30 @@ import { createRequire } from 'node:module'
import { once } from 'node:events'
import { connectInspector, parseCgroup } from './control-api-authorize-memory-inspector.mjs'
+type CleanupRow = { id: string; invocation_id: string; host_ref: string; request_hash: string; connection_id: string; status: string; ticket_status: string; ticket_expired: boolean; reservation_id: string | null; reservation_host_ref: string | null; budget_id: string | null }
+type ConfirmedAttempt = { invocationId: string; hostRef: string; requestHash: string }
+
+/** An issued ticket cannot be receipt-finalized. Only known, never-dispatched
+ * authorizations with observed ticket expiry may release their own ephemeral reservation through the real
+ * Host endpoint; the issued ticket and authorized audit row remain untouched.
+ */
+export function ownedIssuedCleanupPlan(rows: CleanupRow[], bindings: any[], confirmed: Map<string, ConfirmedAttempt>) {
+ const attempts = new Set<string>(), reservations = new Map<string, { reservationId: string; hostRef: string }>()
+ for (const row of rows) {
+ const binding = bindings.find(value => value.hostRef === row.host_ref)
+ const witness = confirmed.get(row.id)
+ if (!binding || binding.connectionId !== row.connection_id || !witness || witness.invocationId !== row.invocation_id || witness.hostRef !== row.host_ref || witness.requestHash !== row.request_hash) throw new Error('unconfirmed or changed attempt ownership')
+ if (row.status !== 'authorized' || row.ticket_status !== 'issued' || row.ticket_expired !== true) throw new Error('issued benchmark lifecycle changed')
+ attempts.add(row.id)
+ if (row.reservation_id !== null) {
+ if (row.reservation_host_ref !== row.host_ref || row.budget_id !== binding.budgetId) throw new Error('reservation ownership changed')
+ reservations.set(row.reservation_id, { reservationId: row.reservation_id, hostRef: row.host_ref })
+ }
+ }
+ if (attempts.size !== confirmed.size) throw new Error('confirmed authorization audit is incomplete')
+ return { retainedAuthorizedAuditRows: attempts.size, reservations: [...reservations.values()] }
+}
+
type Frame = { callId: string; kind: string; requestId?: string; length?: number; options?: Record<string, unknown> }
export async function runCompanion(): Promise<void> {
const output = process.stdout.write.bind(process.stdout)
@@ -14,17 +38,28 @@ export async function runCompanion(): Promise<void> {
// and secret-bearing response bodies cannot reach the controller.
process.stdout.write = () => true; process.stderr.write = () => true
const emit = (value: unknown) => output(JSON.stringify(value) + '\n')
- const sockets = new Map<string, any>(), created = new Map<string, any>()
+ const sockets = new Map<string, any>(), created = new Map<string, any>(), confirmed = new Map<string, ConfirmedAttempt>()
+ let releasedReservationRows = 0
const cookieName = 'control_ui_admin_session'
const knownErrors = new Set(['authorize_capacity_exceeded', 'payload_too_large', 'invalid_request', 'request_timeout', 'authorize_timeout', 'unauthorized', 'Unauthorized', 'disabled', 'insufficient_scope', 'no_grant', 'model_not_allowed', 'unassigned_connection', 'connection_unavailable', 'budget_denied', 'host_binding_mismatch', 'provider_unavailable', 'stale_generation', 'idempotency_conflict'])
let options: any, inspector: any, prod: any, lockClient: any
const require = createRequire(path.join(process.cwd(), 'package.json'))
const hash = (value: Uint8Array) => createHash('sha256').update(value).digest('hex')
+ const processCounts = (serverPid: number) => {
+ const ids = fs.readdirSync('/proc').filter(name => /^\d+$/.test(name)); let applications = 0, nodes = 0
+ for (const id of ids) {
+ let args: string[]; try { args = fs.readFileSync(`/proc/${id}/cmdline`, 'utf8').split('\0') } catch (error: any) { if (error.code === 'ENOENT') continue; throw error }
+ if (path.basename(args[0] || '') !== 'node') continue
+ nodes++; if (args.includes('dist/main.js') || args.includes(path.join(process.cwd(), 'dist/main.js'))) { if (Number(id) !== serverPid) throw new Error('another application process is measured'); applications++ }
+ }
+ if (applications !== 1) throw new Error('application process count is unknown')
+ return { applicationProcesses: applications, nodeProcessesIncludingAuxiliary: nodes }
+ }
const cgroup = () => parseCgroup({ current: fs.readFileSync('/sys/fs/cgroup/memory.current', 'utf8'), peak: fs.readFileSync('/sys/fs/cgroup/memory.peak', 'utf8'), limit: fs.readFileSync('/sys/fs/cgroup/memory.max', 'utf8'), events: fs.readFileSync('/sys/fs/cgroup/memory.events', 'utf8') })
- function ordinary(method: string, route: string, body?: unknown, cookie = options.cookie): Promise<any> {
+ function ordinary(method: string, route: string, body?: unknown, cookie = options.cookie, extraHeaders: Record<string, string> = {}): Promise<any> {
return new Promise((resolve, reject) => {
const request = http.request({ hostname: '127.0.0.1', port: prod.config.port, method, path: route,
- headers: { 'content-type': 'application/json', ...(cookie ? { cookie: `${cookieName}=${cookie}` } : {}) } }, response => {
+ headers: { 'content-type': 'application/json', ...(cookie ? { cookie: `${cookieName}=${cookie}` } : {}), ...extraHeaders } }, response => {
const chunks: Buffer[] = []; let bytes = 0
response.on('data', chunk => { bytes += chunk.length; if (bytes > 65536) request.destroy(new Error('bounded response exceeded')); else chunks.push(chunk) })
response.on('end', () => { try { resolve({ status: response.statusCode, headers: response.headers, body: bytes ? JSON.parse(Buffer.concat(chunks).toString()) : null }) } catch { reject(new Error('invalid bounded response')) } })
@@ -33,16 +68,32 @@ export async function runCompanion(): Promise<void> {
if (body) request.write(JSON.stringify(body)); request.end()
})
}
+ const reservationJoin = `r.host_ref = a.host_ref AND (r.id::text = a.budget_reservation_id OR r.task_ref = a.invocation_id || ':' || a.attempt_generation::text || ':' || a.provider_attempt_index::text)`
async function counts() {
const rows = await prod.db.pool.query(`SELECT COUNT(DISTINCT a.id)::int AS total,
- COUNT(DISTINCT a.id) FILTER (WHERE a.status <> 'finalized')::int AS active,
- COUNT(DISTINCT t.jti) FILTER (WHERE t.status <> 'finalized' AND t.expires_at > NOW())::int AS active_tickets,
- COUNT(DISTINCT r.id)::int AS reservations FROM llm_provider_attempts a
- LEFT JOIN llm_provider_attempt_tickets t ON t.provider_attempt_id = a.id
- LEFT JOIN budget_pending_reservations r ON r.id::text = a.budget_reservation_id OR r.task_ref = a.budget_reservation_id
+ COUNT(DISTINCT a.id) FILTER (WHERE a.status = 'authorized')::int AS authorized_audit_rows,
+ COUNT(DISTINCT a.id) FILTER (WHERE a.status = 'redeemed')::int AS redeemed_audit_rows,
+ COUNT(DISTINCT a.id) FILTER (WHERE a.status = 'finalized')::int AS finalized_audit_rows,
+ COUNT(DISTINCT t.jti)::int AS tickets,
+ COUNT(DISTINCT t.jti) FILTER (WHERE t.status = 'issued' AND t.expires_at > NOW())::int AS live_issued_tickets,
+ COUNT(DISTINCT t.jti) FILTER (WHERE t.status = 'issued' AND t.expires_at <= NOW())::int AS expired_issued_tickets,
+ COUNT(DISTINCT t.jti) FILTER (WHERE t.status = 'redeemed')::int AS redeemed_tickets,
+ COUNT(DISTINCT t.jti) FILTER (WHERE t.status = 'finalized')::int AS finalized_tickets,
+ COUNT(DISTINCT r.id)::int AS reservation_rows,
+ COUNT(DISTINCT r.id) FILTER (WHERE r.expires_at > NOW())::int AS active_reservations,
+ COALESCE(GREATEST(0, CEIL(EXTRACT(EPOCH FROM (MAX(t.expires_at) FILTER (WHERE t.status = 'issued') - NOW())) * 1000)), 0)::int AS expiry_remaining_ms,
+ NOW() AS observed_at
+ FROM llm_provider_attempts a LEFT JOIN llm_provider_attempt_tickets t ON t.provider_attempt_id = a.id
+ LEFT JOIN budget_pending_reservations r ON ${reservationJoin}
WHERE a.invocation_id LIKE $1 AND a.host_ref = ANY($2::text[]) AND a.provider = 'grok-subscription'`, [`${options.runId}-%`, options.bindings.map((binding: any) => binding.hostRef)])
const value = rows.rows[0]
- return { total: value.total, active: value.active, activeTickets: value.active_tickets, reservations: value.reservations }
+ return { total: value.total, retainedAuthorizedAuditRows: value.authorized_audit_rows, redeemedAuditRows: value.redeemed_audit_rows, finalizedAuditRows: value.finalized_audit_rows,
+ tickets: value.tickets, liveIssuedTickets: value.live_issued_tickets, expiredIssuedTickets: value.expired_issued_tickets, redeemedTickets: value.redeemed_tickets, finalizedTickets: value.finalized_tickets,
+ reservationRows: value.reservation_rows, activeReservations: value.active_reservations, executionTicketExpiryRemainingMs: value.expiry_remaining_ms, observedAt: value.observed_at.toISOString() }
+ }
+ function hostHeaders(binding: any) {
+ const issued = prod.jwt.issueMcpHostAccessJwt(prod.config.hostsNamespace, 'standalone', [binding.hostRef], { workflowControlScopes: ['llm:grok:execute', 'llm:codex:execute'], hccCredential: { hostUid: binding.hostUid } })
+ return { authorization: `Bearer ${issued.token}` }
}
async function hello(input: any) {
options = input
@@ -51,17 +102,24 @@ export async function runCompanion(): Promise<void> {
prod = { config: require('./dist/config.js').config, db: require('./dist/db.js'), jwt: require('./dist/utils/auth/mcpHostJwtToken.js'),
connections: require('./dist/services/grokSubscriptionConnection.js'),
policy: require('./dist/middleware/llmProviderAttemptAdmissionLimits.js').LLM_PROVIDER_ATTEMPT_ADMISSION_POLICY,
- grok: require('@clerum/grok-provider-attempt-contract'), finalize: require('./dist/services/grokProviderAttemptFinalization.js').finalizeGrokProviderAttempt,
- opaque: require('./dist/services/llmProviderAttemptRedemption.js').opaqueAttemptReceipt }
- if (!prod.config.grokSubscriptionEnabled || !prod.config.codexSubscriptionEnabled) throw new Error('both actual provider validators must be enabled')
+ grok: require('@clerum/grok-provider-attempt-contract') }
+ if (options.hostNamespace !== prod.config.hostsNamespace || !prod.config.grokSubscriptionEnabled || !prod.config.codexSubscriptionEnabled) throw new Error('both actual provider validators must be enabled')
+ if (prod.config.subscriptionCatalogSyncCronEnabled !== false || prod.config.llmCatalogSyncCronEnabled !== false) throw new Error('actual vendor crons must be disabled')
inspector = await connectInspector(options.inspectorPort)
const server = await inspector.snapshot()
const flags = [...server.execArgv, ...server.nodeOptions.split(/\s+/).filter(Boolean)]
- if (server.cwd !== process.cwd() || !server.argv[1]?.endsWith('/dist/main.js') ||
- !flags.includes(`--max-old-space-size=${options.candidate.heapSizeMiB}`) || !flags.includes(`--inspect=127.0.0.1:${options.inspectorPort}`) ||
+ if (server.cwd !== process.cwd() || server.argv.length !== 2 || !server.argv[1]?.endsWith('/dist/main.js') ||
+ flags.filter(flag => flag.startsWith('--max-old-space-size=')).length !== 1 || !flags.includes(`--max-old-space-size=${options.candidate.heapSizeMiB}`) || flags.filter(flag => flag.startsWith('--inspect=')).length !== 1 || !flags.includes(`--inspect=127.0.0.1:${options.inspectorPort}`) ||
flags.some(flag => !/^--(?:max-old-space-size=\d+|inspect=127\.0\.0\.1:\d+|enable-source-maps)$/.test(flag))) throw new Error('actual server source/argv mismatch')
const expected = { maxInFlight: options.candidate.concurrency, readDeadlineMs: options.candidate.readDeadlineMs, workDeadlineMs: options.candidate.workDeadlineMs, closeGraceMs: options.candidate.closeGraceMs }
- if (JSON.stringify(prod.policy) !== JSON.stringify(expected)) throw new Error('actual compiled admission policy differs from candidate')
+ if (!Object.keys(expected).every(key => prod.policy[key] === expected[key]) || Object.keys(prod.policy).length !== 4) throw new Error('actual compiled admission policy differs from candidate')
+ if (options.pressureOnly === true) {
+ if (options.bindings.some((binding: any) => !/^[a-z0-9][a-z0-9-]{0,62}$/.test(binding.hostRef) || !/^[a-f0-9-]{36}$/.test(binding.hostUid))) throw new Error('pressure Host identity invalid')
+ if ((await counts()).total !== 0) throw new Error('pressure run is not fresh')
+ const owner = await inspector.owners()
+ if (owner.pid !== server.pid || owner.inFlight !== 0) throw new Error('pressure baseline is not quiescent')
+ return { pressureOnly: true, bindings: options.bindings.map((binding: any) => ({ hostRef: binding.hostRef, hostUid: binding.hostUid })), policy: prod.policy, serverPid: server.pid, owner, compiledPolicySha256: hash(fs.readFileSync('./dist/middleware/llmProviderAttemptAdmissionLimits.js')) }
+ }
if (!options.cookie) {
if (!options.operatorPassword || !options.operatorUser) throw new Error('operator material unavailable')
const login = await ordinary('POST', '/api/v1/admin/auth/login', { username: options.operatorUser, password: options.operatorPassword }, '')
@@ -84,12 +142,12 @@ export async function runCompanion(): Promise<void> {
const budget = await prod.db.pool.query('SELECT name FROM token_budgets WHERE id = $1', [binding.budgetId])
if (budget.rows.length !== 1 || !budget.rows[0].name.includes(options.fixtureRunId)) throw new Error('budget not fixture-owned')
const policyHash = prod.grok.computeGrokPolicyHash({ model: 'grok-4.6', catalogRevision: connection.catalogRevision, credentialRevision: connection.credentialRevision, connectionKey: binding.connectionKey })
- bindings.push({ ...binding, connectionId: connection.id, policyRevision: connection.catalogRevision, policyHash })
+ bindings.push({ hostRef: binding.hostRef, hostUid: binding.hostUid, connectionKey: binding.connectionKey, budgetId: binding.budgetId, connectionId: connection.id, policyRevision: connection.catalogRevision, policyHash })
}
options.bindings = bindings
if ((await counts()).total !== 0) throw new Error('run id is not fresh')
- return { bindings, policy: prod.policy, compiledPolicySha256: hash(fs.readFileSync('./dist/middleware/llmProviderAttemptAdmissionLimits.js')),
- server: { ...server, nodeOptions: undefined }, cgroup: cgroup(), operatorSessionValidated: true, gfsParentResourceId: options.gfsParentResourceId,
+ return { bindings, policy: prod.policy, executionTicketTtlMs: prod.grok.LIMITS.executionTicketTtlMs, compiledPolicySha256: hash(fs.readFileSync('./dist/middleware/llmProviderAttemptAdmissionLimits.js')),
+ server: { ...server, nodeOptions: undefined, ...processCounts(server.pid) }, cgroup: cgroup(), operatorSessionValidated: true, gfsParentResourceId: options.gfsParentResourceId,
auxiliary: { pid: process.pid, memory: process.memoryUsage(), inputHighWaterMark: process.stdin.readableHighWaterMark } }
}
async function unlock() {
@@ -98,12 +156,12 @@ export async function runCompanion(): Promise<void> {
}
function open(input: any) {
if (sockets.size >= 8 || sockets.has(input.requestId) || !Number.isSafeInteger(input.length) || input.length < 1 || input.length > 36 * 1024 * 1024) throw new Error('invalid bounded request')
+ if (options.pressureOnly === true && (input.route !== 'authorize' || input.length !== 35 * 1024 * 1024 - 4096 || !input.requestId?.startsWith(`${options.runId}-pressure-`) || sockets.size >= prod.policy.maxInFlight)) throw new Error('pressure must remain an owned incomplete authorize body')
let route: string; const headers: Record<string, string> = { 'content-type': 'application/json', 'content-length': String(input.length) }
if (input.route === 'authorize') {
const binding = options.bindings.find((value: any) => value.hostRef === input.hostRef)
if (!binding) throw new Error('Host not owned')
- const issued = prod.jwt.issueMcpHostAccessJwt(prod.config.hostsNamespace, 'standalone', [binding.hostRef], { workflowControlScopes: ['llm:grok:execute', 'llm:codex:execute'], hccCredential: { hostUid: binding.hostUid } })
- headers.authorization = `Bearer ${issued.token}`; route = '/api/v1/mcp-host/llm/provider-attempts/authorize'
+ Object.assign(headers, hostHeaders(binding)); route = '/api/v1/mcp-host/llm/provider-attempts/authorize'
} else if (input.route === 'gfs') {
if (!input.name?.startsWith(`${options.runId}-`)) throw new Error('GFS filename not owned')
headers.cookie = `${cookieName}=${options.cookie}`; route = `/api/v1/gfs/proxy/v1/resources/${options.gfsParentRid}/children`
@@ -112,11 +170,18 @@ export async function runCompanion(): Promise<void> {
const request = http.request({ hostname: '127.0.0.1', port: prod.config.port, method: 'POST', path: route, headers }, response => {
const chunks: Buffer[] = []; let bytes = 0
response.on('data', chunk => { bytes += chunk.length; if (bytes > 65536) request.destroy(new Error('response bound')); else chunks.push(chunk) })
- response.on('end', () => {
+ response.on('end', async () => {
try {
const body = bytes ? JSON.parse(Buffer.concat(chunks).toString()) : null
let data: any = { status: response.statusCode, acceptedWriteBytes: state.acceptedWriteBytes, maxWritableBytes: state.maxWritableBytes, closedByClient: state.closedByClient, error: knownErrors.has(body?.error) ? body.error : undefined }
- if (input.route === 'authorize' && response.statusCode === 200) data = { ...data, providerAttemptId: body.providerAttemptId, requestHash: body.requestHash }
+ if (input.route === 'authorize' && response.statusCode === 200) {
+ const rows = await prod.db.pool.query(`SELECT a.id, a.invocation_id, a.host_ref, a.request_hash, a.status, r.id::text AS reservation_id, r.budget_id::text, r.host_ref AS reservation_host_ref, r.est_amount, r.expires_at > NOW() AS reservation_active, t.status AS ticket_status, t.expires_at FROM llm_provider_attempts a LEFT JOIN budget_pending_reservations r ON r.id::text = a.budget_reservation_id LEFT JOIN llm_provider_attempt_tickets t ON t.provider_attempt_id = a.id WHERE a.id = $1`, [body.providerAttemptId])
+ if (rows.rows.length !== 1 || rows.rows[0].invocation_id !== input.requestId || rows.rows[0].host_ref !== input.hostRef || rows.rows[0].request_hash !== body.requestHash || rows.rows[0].status !== 'authorized') throw new Error('real durable authorize witness missing')
+ const binding = options.bindings.find((value: any) => value.hostRef === input.hostRef), witness = rows.rows[0]
+ if (!binding || witness.budget_id !== binding.budgetId || witness.reservation_host_ref !== input.hostRef || Number(witness.est_amount) !== 200 || witness.reservation_active !== true || witness.ticket_status !== 'issued') throw new Error('real danger-zone reservation witness missing')
+ confirmed.set(body.providerAttemptId, { invocationId: input.requestId, hostRef: input.hostRef, requestHash: body.requestHash })
+ data = { ...data, providerAttemptId: body.providerAttemptId, requestHash: body.requestHash, durableRowVerified: true, reservationVerified: true, reservationAmount: Number(witness.est_amount), ticketExpiresAt: witness.expires_at.toISOString() }
+ }
if (input.route === 'gfs' && response.statusCode === 201 && body?.ok === true) {
const value = body.data
if (value.name !== input.name || value.parentResourceId !== options.gfsParentResourceId || value.bytes !== input.decodedBytes || value.kind !== 'file') throw new Error('GFS receipt mismatch')
@@ -145,11 +210,19 @@ export async function runCompanion(): Promise<void> {
async function cleanup() {
for (const state of sockets.values()) { state.closedByClient = true; state.request.destroy() }
await unlock()
- const rows = await prod.db.pool.query(`SELECT a.id, a.request_hash, a.connection_id, t.jti::text FROM llm_provider_attempts a JOIN llm_provider_attempt_tickets t ON t.provider_attempt_id = a.id WHERE a.invocation_id LIKE $1 AND a.host_ref = ANY($2::text[]) AND a.provider = 'grok-subscription'`, [`${options.runId}-%`, options.bindings.map((value: any) => value.hostRef)])
- for (const row of rows.rows) {
- if (!options.bindings.some((value: any) => value.connectionId === row.connection_id)) throw new Error('attempt owner changed')
- const opaque = prod.opaque({ jti: row.jti, providerAttemptId: row.id, requestHash: row.request_hash })
- await prod.finalize({ attemptReceipt: opaque, receipt: { schemaVersion: 'grok-attempt-receipt.v1', providerAttemptId: row.id, requestHash: row.request_hash, outcome: 'canceled' } })
+ const rows = await prod.db.pool.query(`SELECT a.id::text, a.invocation_id, a.host_ref, a.request_hash, a.connection_id::text, a.status, t.status AS ticket_status, t.expires_at <= NOW() AS ticket_expired,
+ r.id::text AS reservation_id, r.host_ref AS reservation_host_ref, r.budget_id::text
+ FROM llm_provider_attempts a LEFT JOIN llm_provider_attempt_tickets t ON t.provider_attempt_id = a.id
+ LEFT JOIN budget_pending_reservations r ON ${reservationJoin}
+ WHERE a.invocation_id LIKE $1 AND a.host_ref = ANY($2::text[]) AND a.provider = 'grok-subscription'`, [`${options.runId}-%`, options.bindings.map((value: any) => value.hostRef)])
+ const plan = ownedIssuedCleanupPlan(rows.rows, options.bindings, confirmed)
+ // This existing Host endpoint releases only ephemeral reservations. It does
+ // not manufacture a receipt, redeem a ticket, or rewrite the audit ledger.
+ for (const reservation of plan.reservations) {
+ const binding = options.bindings.find((value: any) => value.hostRef === reservation.hostRef)
+ const response = await ordinary('POST', '/api/v1/internal/budgets/release', { host_ref: reservation.hostRef, reservationId: reservation.reservationId }, '', hostHeaders(binding))
+ if (response.status !== 200 || !Number.isInteger(response.body?.released) || response.body.released < 0 || response.body.released > 1) throw new Error('owned reservation release refused')
+ releasedReservationRows += response.body.released
}
for (const [rid, expected] of created) {
const current = await ordinary('GET', `/api/v1/gfs/proxy/v1/resources/${rid}`)
@@ -159,16 +232,23 @@ export async function runCompanion(): Promise<void> {
created.delete(rid)
}
const after = await counts()
- if (after.active || after.activeTickets || after.reservations) throw new Error('terminal lifetime incomplete')
- return { ...after, ownedGfsRemaining: created.size, retainedFinalizedAuditRows: rows.rows.length }
+ if (after.reservationRows || after.activeReservations || after.redeemedTickets || after.finalizedTickets || after.retainedAuthorizedAuditRows !== confirmed.size || after.tickets !== confirmed.size) throw new Error('issued cleanup incomplete')
+ return { ...after, lifecycle: 'pg-issued-expiry-before-host-release', ownedGfsRemaining: created.size, releaseEndpoint: '/api/v1/internal/budgets/release', releasedReservationRows }
}
async function command(input: any): Promise<unknown> {
- if (input.kind === 'hello') return hello(input.options)
+ if (input.kind === 'hello') { if (prod) throw new Error('private runtime binding cannot be replaced'); return hello(input.options) }
if (!prod) throw new Error('runtime admission required')
+ if (options.pressureOnly === true && !['open', 'close', 'owners', 'counts', 'health'].includes(input.kind)) throw new Error('pressure mode cannot advance business work')
if (input.kind === 'open') return open(input)
if (input.kind === 'end') { sockets.get(input.requestId)?.request.end(); return { ended: true } }
if (input.kind === 'close') { const state = sockets.get(input.requestId); if (state) { state.closedByClient = true; state.request.destroy() }; return { clientClosed: true } }
if (input.kind === 'counts') return counts()
+ if (input.kind === 'owners') {
+ const owner = await inspector.owners()
+ const incomplete = [...sockets.values()].map(state => ({ requestId: state.input.requestId, acceptedWriteBytes: state.acceptedWriteBytes, declaredBytes: state.input.length, closedByClient: state.closedByClient }))
+ if (incomplete.some(value => value.acceptedWriteBytes >= value.declaredBytes)) throw new Error('pressure body is not incomplete')
+ return { ...owner, incompleteFixtureBodies: incomplete }
+ }
if (input.kind === 'lock') {
if (lockClient) throw new Error('lock already held')
lockClient = await prod.db.pool.connect(); await lockClient.query('BEGIN'); await lockClient.query('SET LOCAL statement_timeout = 60000')
@@ -181,7 +261,7 @@ export async function runCompanion(): Promise<void> {
const pid = (await lockClient.query('SELECT pg_backend_pid() AS pid')).rows[0].pid
return (await prod.db.pool.query("SELECT COUNT(*)::int AS count FROM pg_stat_activity WHERE $1::int = ANY(pg_blocking_pids(pid)) AND wait_event_type = 'Lock' AND usename = current_user", [pid])).rows[0]
}
- if (input.kind === 'sample') return { server: await inspector.snapshot(), cgroup: cgroup() }
+ if (input.kind === 'sample') { const server = await inspector.snapshot(); return { server: { ...server, nodeOptions: undefined, ...processCounts(server.pid) }, cgroup: cgroup() } }
if (input.kind === 'gc') return { gc: await inspector.forceGc(), cgroup: cgroup() }
if (input.kind === 'coverage-start') { await inspector.startCoverage(); return { started: true } }
if (input.kind === 'coverage') return inspector.coverage()
@@ -199,7 +279,8 @@ export async function runCompanion(): Promise<void> {
if (remaining) {
const length = Math.min(remaining, chunk.length - offset), state = sockets.get(frame.requestId!)
if (!state) throw new Error('request closed before streaming completed')
- state.acceptedWriteBytes += length
+ if (options.pressureOnly === true && (state.acceptedWriteBytes + length > 65536 || state.acceptedWriteBytes + length >= state.input.length)) throw new Error('pressure body cannot complete')
+ state.acceptedWriteBytes += length
const writable = state.request.write(chunk.subarray(offset, offset + length))
state.maxWritableBytes = Math.max(state.maxWritableBytes, state.request.writableLength)
if (!writable) await once(state.request, 'drain')
@@ -221,5 +302,5 @@ export async function runCompanion(): Promise<void> {
}
if (remaining || header.length) throw new Error('incomplete frame')
} catch { emit({ fatal: true, code: 'COMPANION_PROTOCOL_FAILED' }); process.exitCode = 1 }
- finally { for (const state of sockets.values()) state.request.destroy(); await unlock().catch(() => {}); inspector?.close(); if (prod) await prod.db.pool.end().catch(() => {}) }
+ finally { for (const state of sockets.values()) state.request.destroy(); await unlock().catch(() => {}); inspector?.close(); if (prod) await prod.db.pool.end().catch(() => {}); http.globalAgent.destroy() }
}
diff --git a/scripts/tests/lib/control-api-authorize-memory-inspector.mjs b/scripts/tests/lib/control-api-authorize-memory-inspector.mjs
index 393758f3f..df1d56c3c 100644
--- a/scripts/tests/lib/control-api-authorize-memory-inspector.mjs
+++ b/scripts/tests/lib/control-api-authorize-memory-inspector.mjs
@@ -31,6 +31,21 @@ export class InspectorClient {
if (!Number.isSafeInteger(data.pid) || !Number.isSafeInteger(data.at) || !/^24\./.test(data.nodeVersion)) throw new Error('Actual server process identity is invalid')
return data
}
+ async owners() {
+ const group = 'qa-admission-owner-observation'
+ try {
+ // Inspect the already-loaded production class and its retained singleton.
+ // A separate import in the auxiliary process would observe a false zero.
+ const prototype = await this.call('Runtime.evaluate', { expression: "process.mainModule.require('./middleware/llmProviderAttemptBodyAdmission.js').AuthorizeBodyAdmission.prototype", objectGroup: group })
+ if (prototype?.exceptionDetails || !prototype?.result?.objectId) throw new Error('Actual admission prototype unavailable')
+ const objects = await this.call('Runtime.queryObjects', { prototypeObjectId: prototype.result.objectId, objectGroup: group })
+ if (!objects?.objects?.objectId) throw new Error('Actual admission instances unavailable')
+ const read = await this.call('Runtime.callFunctionOn', { objectId: objects.objects.objectId, functionDeclaration: 'function(){return {pid:process.pid,at:Date.now(),instanceCount:this.length,inFlight:this.length===1?this[0].snapshot().inFlight:null}}', returnByValue: true })
+ const value = read?.result?.value
+ if (read?.exceptionDetails || value?.instanceCount !== 1 || !Number.isSafeInteger(value.pid) || !Number.isSafeInteger(value.at) || !Number.isSafeInteger(value.inFlight) || value.inFlight < 0) throw new Error('Actual singleton admission ownership is unknown')
+ return { kind: 'native-inspector-AuthorizeBodyAdmission.snapshot', ...value }
+ } finally { await this.call('Runtime.releaseObjectGroup', { objectGroup: group }) }
+ }
async forceGc() {
const before = await this.snapshot()
await this.call('HeapProfiler.enable')
diff --git a/scripts/tests/lib/control-api-authorize-memory-seeder.ts b/scripts/tests/lib/control-api-authorize-memory-seeder.ts
new file mode 100644
index 000000000..d23a75c76
--- /dev/null
+++ b/scripts/tests/lib/control-api-authorize-memory-seeder.ts
@@ -0,0 +1,167 @@
+/** Test-only QA preparation. The caller must prove an exclusive owned profile/DB,
+ * current image/source marker and mutation lease before running this companion.
+ * Opaque QA connection state is not real G8 evidence. No vendor is contacted.
+ */
+import fs from 'node:fs'
+import path from 'node:path'
+import http from 'node:http'
+import { createRequire } from 'node:module'
+import { randomBytes, createHash } from 'node:crypto'
+
+type SeedOptions = { runId: string; hostNamespace: string; operatorUser: string; operatorPassword?: string; cookie?: string }
+const seedAssert = (condition: unknown, code: string) => { if (!condition) throw new Error(code) }
+export function assertQaBudget(budget: any, hostRef: string, name: string): void {
+ const scope = budget.scope
+ seedAssert(budget.name === name && budget.enabled === true && budget.unit === 'tokens' && budget.currency === null && budget.enforcement === 'block' &&
+ Number(budget.limit_amount) === 100 && Number(budget.max_task_amount) === 200 && Number(budget.min_start_amount) === 1 && budget.period === 'daily' && budget.timezone === 'UTC' &&
+ scope && Object.keys(scope).length === 3 && scope.host_ref?.length === 1 && scope.host_ref[0] === hostRef && scope.provider?.length === 1 && scope.provider[0] === 'grok-subscription' && scope.model?.length === 1 && scope.model[0] === 'grok-4.6', 'QA_DANGER_ZONE_BUDGET_MISMATCH')
+}
+export async function runSeedCompanion(): Promise<void> {
+ const output = process.stdout.write.bind(process.stdout)
+ process.stdout.write = () => true; process.stderr.write = () => true
+ process.env.LOG_LEVEL = 'silent'
+ const emit = (value: unknown) => output(JSON.stringify(value) + '\n')
+ const require = createRequire(path.join(process.cwd(), 'package.json'))
+ let prod: any, options: SeedOptions, phase = 'private-input', input = Buffer.alloc(0)
+ const cookieName = 'control_ui_admin_session'
+ async function request(method: string, route: string, body?: unknown, cookie = options.cookie): Promise<any> {
+ return new Promise((resolve, reject) => {
+ const req = http.request({ hostname: '127.0.0.1', port: prod.config.port, method, path: route,
+ headers: { 'content-type': 'application/json', ...(cookie ? { cookie: `${cookieName}=${cookie}` } : {}) } }, res => {
+ const chunks: Buffer[] = []; let bytes = 0
+ res.on('data', chunk => { bytes += chunk.length; if (bytes > 65536) req.destroy(new Error('SEED_RESPONSE_BOUND')); else chunks.push(chunk) })
+ res.on('end', () => { try { resolve({ status: res.statusCode, headers: res.headers, body: bytes ? JSON.parse(Buffer.concat(chunks).toString()) : null }) } catch { reject(new Error('SEED_RESPONSE_INVALID')) } })
+ })
+ req.on('error', () => reject(new Error('SEED_HTTP_FAILED')))
+ req.setTimeout(30000, () => req.destroy(new Error('SEED_HTTP_DEADLINE')))
+ if (body) req.write(JSON.stringify(body)); req.end()
+ })
+ }
+ function takeSession(response: any) {
+ const value = (response.headers['set-cookie'] ?? []).find((item: string) => item.startsWith(`${cookieName}=`))
+ seedAssert(response.status === 200 && value, 'SEED_LOGIN_OR_SETUP_REFUSED')
+ options.cookie = value.split(';')[0].slice(cookieName.length + 1)
+ }
+ async function prepare() {
+ seedAssert(/^pr806-memory-[a-f0-9]{12}$/.test(options.runId), 'SEED_RUN_ID_INVALID')
+ prod = { config: require('./dist/config.js').config, db: require('./dist/db.js'),
+ connection: require('./dist/services/grokSubscriptionConnection.js'), encryption: require('./dist/oauth/encryption.js'),
+ gateway: new (require('./dist/k8s.js').K8sGateway)() }
+ seedAssert(prod.config.hostsNamespace === options.hostNamespace && prod.config.grokSubscriptionEnabled && prod.config.codexSubscriptionEnabled, 'SEED_PROVIDER_OR_NAMESPACE_MISMATCH')
+ seedAssert(prod.config.subscriptionCatalogSyncCronEnabled === false && prod.config.llmCatalogSyncCronEnabled === false, 'SEED_VENDOR_CRON_MUST_BE_DISABLED')
+ phase = 'operator-session'
+ let setupPerformed = false
+ if (!options.cookie) {
+ seedAssert(typeof options.operatorPassword === 'string' && options.operatorPassword.length >= 8, 'SEED_PRIVATE_OPERATOR_MATERIAL_REQUIRED')
+ const bootstrap = await prod.db.pool.query(`SELECT id::text, username, status, last_login_at FROM control_admin_users WHERE username = $1`, [prod.config.adminBootstrapUsername])
+ const active = await prod.db.pool.query("SELECT COUNT(*)::int AS count FROM control_admin_users WHERE status = 'active'")
+ const eligible = bootstrap.rows.length === 1 && bootstrap.rows[0].status === 'active' && bootstrap.rows[0].last_login_at === null && active.rows[0].count === 1
+ if (eligible) {
+ seedAssert(options.operatorUser === `${options.runId}-operator`, 'SEED_FIRST_RUN_OPERATOR_MUST_BE_OWNED')
+ takeSession(await request('POST', '/api/v1/admin/auth/setup', { username: options.operatorUser, email: `${options.runId}@example.invalid`, password: options.operatorPassword, seedDesktopPassword: false }, ''))
+ setupPerformed = true
+ } else {
+ // Only explicit canonical harness material authenticates an initialized
+ // account. No reset, alternate secret store or bootstrap retry occurs.
+ takeSession(await request('POST', '/api/v1/admin/auth/login', { username: options.operatorUser, password: options.operatorPassword }, ''))
+ }
+ }
+ const me = await request('GET', '/api/v1/admin/auth/me')
+ seedAssert(me.status === 200 && me.body?.me?.username === options.operatorUser && me.body.me.role === 'admin', 'SEED_OPERATOR_IDENTITY_MISMATCH')
+ phase = 'context-binding'
+ const context = await request('GET', '/api/v1/admin/contexts/context1')
+ seedAssert(context.status === 200 && context.body?.metadata?.name === 'context1' && context.body.metadata.namespace === prod.config.contextsNamespace && /^[a-f0-9-]{36}$/.test(context.body.metadata.uid) &&
+ !context.body.metadata.deletionTimestamp && typeof context.body.metadata.resourceVersion === 'string' && context.body.spec?.contextId === 'context1', 'SEED_CONTEXT1_UNPROVED')
+ // A new Host boots MCP inventory. Empty actual inventory prevents that boot
+ // from connecting external services; stateless/suspend is not a shortcut.
+ seedAssert(Array.isArray(context.body.spec?.mcpServers) && context.body.spec.mcpServers.length === 0, 'SEED_CONTEXT1_VENDOR_FREE_INVENTORY_UNPROVED')
+ const bindings = []
+ for (const [index, hostRef] of ['pr806-memory-grok-host', 'pr806-memory-grok-host-2'].entries()) {
+ const connectionKey = `${options.runId}-grok-${index + 1}`, fingerprint = `qa-memory-${options.runId}-${index + 1}`
+ phase = `connection-${index + 1}`
+ await prod.db.withTransaction(async (tx: any) => {
+ const existing = await tx.query('SELECT id::text, account_fingerprint, credential_revision, catalog_revision, status, catalog_status, revoked_at FROM grok_subscription_connections WHERE connection_key = $1', [connectionKey])
+ if (existing.rows.length) {
+ const row = existing.rows[0]
+ seedAssert(existing.rows.length === 1 && row.account_fingerprint === fingerprint && row.credential_revision === 1 && row.catalog_revision === 1 && row.status === 'connected' && row.catalog_status === 'ready' && row.revoked_at === null, 'SEED_EXISTING_CONNECTION_CHANGED')
+ } else {
+ const created = await prod.connection.insertInitialGrokSubscriptionConnection(tx, prod.encryption.deriveOAuthEncryptionKey(prod.config.oauthEncryptionKey),
+ { refreshToken: randomBytes(32).toString('base64url'), accountFingerprint: fingerprint, status: 'connected' }, connectionKey)
+ const ready = await prod.connection.recordGrokCatalogOutcome(tx, { connectionKey, catalogStatus: 'ready', connectionStatus: 'connected', expectedCredentialRevision: 1, expectedCatalogRevision: 0 })
+ seedAssert(ready?.id === created.id && ready.catalogRevision === 1, 'SEED_CATALOG_REVISION_GUARD_FAILED')
+ await tx.query(`INSERT INTO grok_catalog_models (connection_id, model, enabled, source, discovered_at, last_seen_at, stale)
+ VALUES ($1, 'grok-4.6', true, 'discovery', NOW(), NOW(), false)`, [created.id])
+ }
+ })
+ const connection = await prod.connection.getSafeGrokSubscriptionConnection(prod.db.pool, connectionKey)
+ const catalog = await prod.db.pool.query("SELECT enabled, stale FROM grok_catalog_models WHERE connection_id = $1 AND model = 'grok-4.6'", [connection.id])
+ seedAssert(connection.status === 'connected' && connection.catalogStatus === 'ready' && catalog.rows.length === 1 && catalog.rows[0].enabled === true && catalog.rows[0].stale === false, 'SEED_CATALOG_WITNESS_MISSING')
+ // HCC consumes the production per-connection ConfigMap projection. Ready
+ // PostgreSQL state alone does not publish that runtime contract.
+ await prod.gateway.llmAllowedModelsConfigMap().materialize()
+ phase = `budget-${index + 1}`
+ const budgetName = `${options.runId}-${hostRef}-budget`
+ const found = await prod.db.pool.query('SELECT id::text, name, enabled, scope, unit, currency, enforcement, limit_amount, max_task_amount, min_start_amount, period, timezone FROM token_budgets WHERE name = $1', [budgetName])
+ let budget
+ if (found.rows.length) {
+ seedAssert(found.rows.length === 1, 'SEED_BUDGET_NAME_AMBIGUOUS'); budget = found.rows[0]
+ } else {
+ const created = await request('POST', '/api/v1/admin/budgets', { name: budgetName, enabled: true, scope: { host_ref: [hostRef], provider: ['grok-subscription'], model: ['grok-4.6'] },
+ unit: 'tokens', currency: null, limit_amount: 100, max_task_amount: 200, min_start_amount: 1, period: 'daily', timezone: 'UTC', enforcement: 'block' })
+ seedAssert(created.status === 201, 'SEED_BUDGET_API_REFUSED'); budget = created.body
+ }
+ assertQaBudget(budget, hostRef, budgetName)
+ const storedBudget = await request('GET', `/api/v1/admin/budgets/${budget.id}`)
+ seedAssert(storedBudget.status === 200, 'SEED_BUDGET_NOT_DURABLE'); assertQaBudget(storedBudget.body, hostRef, budgetName)
+ phase = `host-${index + 1}`
+ const contextNow = await request('GET', '/api/v1/admin/contexts/context1')
+ seedAssert(contextNow.status === 200 && contextNow.body?.metadata?.uid === context.body.metadata.uid && contextNow.body.metadata.resourceVersion === context.body.metadata.resourceVersion &&
+ !contextNow.body.metadata.deletionTimestamp && Array.isArray(contextNow.body.spec?.mcpServers) && contextNow.body.spec.mcpServers.length === 0, 'SEED_CONTEXT_CHANGED_BEFORE_HOST_CREATE')
+ let host = await request('GET', `/api/v1/admin/hosts/${hostRef}`), createdHost = false
+ if (host.status === 404) {
+ host = await request('POST', '/api/v1/admin/hosts', { metadata: { name: hostRef, labels: { 'evenfire.io/qa-memory-run': options.runId } },
+ spec: { host: hostRef, contextRef: 'context1', model: { provider: 'grok-subscription', name: 'grok-4.6', connectionRef: connectionKey }, allowedModels: [{ provider: 'grok-subscription', model: 'grok-4.6' }] } })
+ seedAssert(host.status === 201, 'SEED_HOST_API_REFUSED'); createdHost = true
+ }
+ const value = host.body
+ seedAssert((host.status === 200 || host.status === 201) && value?.metadata?.name === hostRef && value.metadata.namespace === options.hostNamespace && /^[a-f0-9-]{36}$/.test(value.metadata.uid) &&
+ value.metadata.labels?.['evenfire.io/qa-memory-run'] === options.runId && value.spec?.host === hostRef && value.spec.contextRef === 'context1' && value.spec.model?.provider === 'grok-subscription' && value.spec.model.name === 'grok-4.6' && value.spec.model.connectionRef === connectionKey &&
+ value.spec.allowedModels?.length === 1 && value.spec.allowedModels[0].provider === 'grok-subscription' && value.spec.allowedModels[0].model === 'grok-4.6', 'SEED_EXISTING_HOST_OWNER_OR_SPEC_CHANGED')
+ bindings.push({ hostRef, hostUid: value.metadata.uid, connectionKey, connectionId: connection.id, credentialRevision: connection.credentialRevision, catalogRevision: connection.catalogRevision, budgetId: budget.id, budgetName, reservationAmount: 200, hostCreateStatus: createdHost ? 201 : 200, catalogProjectionPublished: true })
+ }
+ phase = 'gfs-owned-directory'
+ const root = await request('GET', '/api/v1/gfs/by-path?drive=main&path=%2F')
+ seedAssert(root.status === 200 && root.body?.drive === 'main' && root.body.kind === 'directory' && root.body.path === '/' && /^[a-f0-9]{32}$/.test(root.body.rid), 'SEED_GFS_ROOT_UNPROVED')
+ const statRoot = await request('GET', `/api/v1/gfs/proxy/v1/resources/${root.body.rid}`)
+ seedAssert(statRoot.status === 200 && statRoot.body?.data?.resourceId === root.body.resourceId && statRoot.body.data.parentResourceId === null && statRoot.body.data.drive === 'main', 'SEED_GFS_ROOT_NOT_CANONICAL')
+ const existingDirectory = await request('GET', `/api/v1/gfs/by-path?drive=main&path=${encodeURIComponent('/' + options.runId)}`)
+ seedAssert(existingDirectory.status === 404, 'SEED_GFS_DIRECTORY_ALREADY_EXISTS_NO_OVERWRITE')
+ const directory = await request('POST', `/api/v1/gfs/proxy/v1/resources/${root.body.rid}/children`, { name: options.runId, kind: 'directory' })
+ seedAssert(directory.status === 201 && directory.body?.ok === true && directory.body.data.name === options.runId && directory.body.data.kind === 'directory' && directory.body.data.parentResourceId === root.body.resourceId && directory.body.data.drive === 'main', 'SEED_GFS_DIRECTORY_CREATE_FAILED')
+ const parent = await request('GET', `/api/v1/gfs/proxy/v1/resources/${directory.body.data.rid}`)
+ seedAssert(parent.status === 200 && parent.body?.data?.resourceId === directory.body.data.resourceId && parent.body.data.name === options.runId && parent.body.data.parentResourceId === root.body.resourceId, 'SEED_GFS_DIRECTORY_NOT_DURABLE')
+ phase = 'complete'
+ return { fixtureCredentialState: 'opaque-qa-not-real-G8', upstreamDispatch: 'NOT_RUN', operatorUsername: me.body.me.username, operatorId: me.body.me.id, setupPerformed,
+ context: { name: 'context1', namespace: context.body.metadata.namespace, uid: context.body.metadata.uid, resourceVersion: context.body.metadata.resourceVersion, mcpServers: [] }, bindings,
+ gfs: { drive: 'main', rootRid: root.body.rid, rootResourceId: root.body.resourceId, parentRid: directory.body.data.rid, parentResourceId: directory.body.data.resourceId, name: options.runId, createStatus: 201, durableReadStatus: 200 },
+ budgetCache: { definitionsTtlMs: 5000, strategy: 'benchmark-requires-new-actual-api-pod-before-first-authorize', resetHelperCalled: false },
+ vendorCronsDisabled: true, compiledPolicySha256: createHash('sha256').update(fs.readFileSync('./dist/middleware/llmProviderAttemptAdmissionLimits.js')).digest('hex') }
+ }
+ let handled = false
+ try {
+ for await (const chunk of process.stdin) {
+ input = Buffer.concat([input, chunk]); seedAssert(input.length <= 32768, 'SEED_PRIVATE_INPUT_BOUND')
+ const end = input.indexOf(10); if (end < 0) continue
+ seedAssert(end === input.length - 1, 'SEED_ONE_PRIVATE_COMMAND_REQUIRED')
+ const frame = JSON.parse(input.toString()); input = Buffer.alloc(0)
+ seedAssert(frame.kind === 'prepare' && typeof frame.callId === 'string', 'SEED_PRIVATE_COMMAND_INVALID')
+ options = frame.options
+ handled = true
+ try { emit({ callId: frame.callId, data: await prepare() }) }
+ catch (error: any) { emit({ callId: frame.callId, failed: true, code: /^[A-Z0-9_]+$/.test(error.message) ? error.message : 'SEED_REAL_RUNTIME_FAILED', phase }); process.exitCode = 1 }
+ break
+ }
+ seedAssert(handled, 'SEED_PRIVATE_INPUT_MISSING')
+ } catch { emit({ fatal: true, code: 'SEED_PRIVATE_PROTOCOL_FAILED', phase }); process.exitCode = 1 }
+ finally { if (prod) await prod.db.pool.end().catch(() => {}); http.globalAgent.destroy() }
+}
diff --git a/scripts/tests/lib/subscription-image-main-admission.mjs b/scripts/tests/lib/subscription-image-main-admission.mjs
new file mode 100644
index 000000000..bd16c9192
--- /dev/null
+++ b/scripts/tests/lib/subscription-image-main-admission.mjs
@@ -0,0 +1,255 @@
+// Host-side builders for the sealed main admission. Pure data shaping only:
+// every value either comes from a real docker inspect / kubectl / owned file
+// read by the caller, or the builder refuses. The full physical verification
+// stays in subscription-image-runner-contract.mjs inside the container.
+import {
+ MAIN_ADMISSION_KIND,
+ PORT_FORWARD_SERVICES,
+ RUNNER_ADMISSION_ROOT,
+ RUNNER_RUN_BASE,
+ RunnerAdmissionError,
+ digest,
+ parsePortForwardRecord,
+ pinnedBaseImage,
+ resolveSuite,
+ suiteBuildArgs,
+} from './subscription-image-runner-contract.mjs'
+
+const refuse = code => {
+ throw new RunnerAdmissionError(code)
+}
+const PERSONAL = /(^|\/)(Users|\.ssh|\.aws|\.gnupg|\.config|keychains?|credentials?|docker\.sock)(\/|$)/i
+const ALLOWED_CONTAINER_ENV = new Set([
+ 'PATH',
+ 'HOME',
+ 'USER',
+ 'LOGNAME',
+ 'LANG',
+ 'LC_ALL',
+ 'TERM',
+ 'NODE_VERSION',
+ 'YARN_VERSION',
+ 'SUBSCRIPTION_IMAGE_RUN_ID',
+])
+
+export function runtimeFromInspect(inspect, { runId, suiteId, home }) {
+ const hostConfig = inspect?.HostConfig
+ if (
+ typeof inspect?.Id !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(inspect.Id) ||
+ typeof inspect.Image !== 'string' ||
+ !/^sha256:[a-f0-9]{64}$/.test(inspect.Image) ||
+ !Number.isFinite(Date.parse(inspect.Created)) ||
+ typeof inspect.Config?.User !== 'string' ||
+ inspect.State?.Running !== true ||
+ !hostConfig ||
+ hostConfig.ReadonlyRootfs !== true ||
+ hostConfig.Privileged !== false ||
+ (hostConfig.PidMode || 'private') !== 'private' ||
+ (hostConfig.IpcMode || 'private') !== 'private' ||
+ typeof hostConfig.NetworkMode !== 'string' ||
+ !hostConfig.NetworkMode ||
+ hostConfig.NetworkMode === 'host' ||
+ hostConfig.NetworkMode.startsWith('container:') ||
+ !Array.isArray(hostConfig.CapDrop) ||
+ hostConfig.CapDrop.join(',') !== 'ALL' ||
+ !Array.isArray(hostConfig.SecurityOpt) ||
+ hostConfig.SecurityOpt.some(
+ value => typeof value !== 'string' || /seccomp=unconfined|no-new-privileges/i.test(value)
+ )
+ )
+ refuse('HOST_INSPECT_RUNTIME_REFUSED')
+ const mounts = Array.isArray(inspect.Mounts) ? inspect.Mounts : []
+ const admissionMounts = mounts.filter(mount => mount.Destination === RUNNER_ADMISSION_ROOT)
+ const tmpfsOk =
+ typeof home === 'string' &&
+ home.startsWith('/') &&
+ [home, RUNNER_RUN_BASE, '/tmp'].every(destination => {
+ const matches = mounts.filter(mount => mount.Destination === destination)
+ return matches.length === 1 && matches[0].Type === 'tmpfs' && matches[0].RW === true
+ })
+ if (
+ mounts.length !== 4 ||
+ admissionMounts.length !== 1 ||
+ admissionMounts[0].Type !== 'bind' ||
+ admissionMounts[0].RW !== false ||
+ typeof admissionMounts[0].Source !== 'string' ||
+ !admissionMounts[0].Source ||
+ mounts.some(mount => mount.Type === 'bind' && mount.Destination !== RUNNER_ADMISSION_ROOT) ||
+ mounts.some(
+ mount => PERSONAL.test(String(mount.Source ?? '')) || PERSONAL.test(String(mount.Destination ?? ''))
+ ) ||
+ !tmpfsOk
+ )
+ refuse('HOST_INSPECT_MOUNTS_REFUSED')
+ const envEntries = Array.isArray(inspect.Config?.Env) ? inspect.Config.Env : []
+ for (const entry of envEntries) {
+ const split = typeof entry === 'string' ? entry.indexOf('=') : -1
+ if (split <= 0) refuse('HOST_CONTAINER_ENV_REFUSED')
+ const name = entry.slice(0, split)
+ if (!ALLOWED_CONTAINER_ENV.has(name) || /(SECRET|TOKEN|PASSWORD|CREDENTIAL|API_KEY|AUTH)/i.test(name))
+ refuse('HOST_CONTAINER_ENV_REFUSED')
+ }
+ if (!envEntries.includes(`SUBSCRIPTION_IMAGE_RUN_ID=${runId}`))
+ refuse('HOST_CONTAINER_ENV_RUN_BINDING')
+ if (typeof suiteId !== 'string' || !suiteId) refuse('HOST_SUITE_REQUIRED')
+ return {
+ readOnlyRootfs: true,
+ privileged: false,
+ pidMode: 'private',
+ ipcMode: 'private',
+ networkMode: hostConfig.NetworkMode,
+ user: inspect.Config.User,
+ capDrop: ['ALL'],
+ seccompMode: 'filter',
+ containerId: inspect.Id,
+ createdAt: new Date(Date.parse(inspect.Created)).toISOString(),
+ }
+}
+
+export function stackReceiptFrom({ profile, context, configMap, portsEnvRaw, fetchedAt }) {
+ const data = configMap?.data
+ if (
+ !data ||
+ typeof data.gitHead !== 'string' ||
+ !/^[a-f0-9]{40}$/.test(data.gitHead) ||
+ typeof data.worktreeId !== 'string' ||
+ !/^[a-f0-9]{40}$/.test(data.worktreeId) ||
+ typeof data.clusterFingerprint !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(data.clusterFingerprint) ||
+ typeof data.imagesGeneratedAt !== 'string' ||
+ !data.imagesGeneratedAt ||
+ typeof configMap?.metadata?.resourceVersion !== 'string' ||
+ !configMap.metadata.resourceVersion
+ )
+ refuse('HOST_STACK_MARKER_REFUSED')
+ if (typeof portsEnvRaw !== 'string' || !portsEnvRaw.length) refuse('HOST_PORTS_ENV_REFUSED')
+ return {
+ kind: 'evenfire-subscription-image-stack-marker-v1',
+ context,
+ configMapName: 'clerum-pre-gate-sync-state',
+ resourceVersion: configMap.metadata.resourceVersion,
+ fetchedAt,
+ profile,
+ portsEnvRaw,
+ portsEnvSha256: digest(portsEnvRaw),
+ data: {
+ gitHead: data.gitHead,
+ worktreeId: data.worktreeId,
+ clusterFingerprint: data.clusterFingerprint,
+ imagesGeneratedAt: data.imagesGeneratedAt,
+ imageSource: data.imageSource ?? '',
+ imageTag: data.imageTag ?? '',
+ },
+ }
+}
+
+export function portForwardReceiptFrom({ records, profile, context, portsEnvRaw, verifiedAt }) {
+ const ports = {}
+ for (const line of String(portsEnvRaw).split('\n')) {
+ const split = line.indexOf('=')
+ if (split > 0) ports[line.slice(0, split)] = line.slice(split + 1)
+ }
+ const entries = {}
+ for (const [kind, expected] of Object.entries(PORT_FORWARD_SERVICES)) {
+ const raw = records?.[kind]
+ if (typeof raw !== 'string' || !raw.length) refuse('HOST_PORT_FORWARD_RECORD_REQUIRED')
+ const record = parsePortForwardRecord(raw)
+ if (
+ record.profile !== profile ||
+ record.context !== context ||
+ record.namespace !== expected.namespace ||
+ record.service !== expected.service ||
+ record.remotePort !== expected.remotePort ||
+ String(record.localPort) !== String(ports[expected.key] ?? '')
+ )
+ refuse('HOST_PORT_FORWARD_RECORD_MISMATCH')
+ entries[kind] = { raw, recordSha256: digest(raw), pid: record.pid, processStart: record.processStart }
+ }
+ return {
+ kind: 'evenfire-subscription-image-port-forwards-v1',
+ profile,
+ context,
+ verifiedAt,
+ entries,
+ }
+}
+
+export function buildAdmission({
+ runId,
+ suiteId,
+ mode,
+ profile,
+ context,
+ repoRoot,
+ source,
+ gitHead,
+ gitTree,
+ inputManifestSha256,
+ sourceManifestSha256,
+ imageId,
+ runtime,
+ observation,
+ networkNamespace,
+ ipcNamespace,
+ stack,
+ receipts,
+ bindings,
+ transports,
+ vendorSources,
+ uiFeatures,
+ thirdPartyArtifacts,
+}) {
+ const suite = resolveSuite(suiteId)
+ const base = pinnedBaseImage(repoRoot)
+ if (!suite.modes.includes(mode)) refuse('SUITE_MODE_NOT_ADMITTED')
+ if (!gitHead || !gitTree || !sourceManifestSha256) refuse('HOST_SOURCE_IDENTITY_REQUIRED')
+ if (
+ !stack ||
+ !receipts ||
+ typeof imageId !== 'string' ||
+ !/^sha256:[a-f0-9]{64}$/.test(imageId) ||
+ !Array.isArray(bindings) ||
+ bindings.length !== 2
+ )
+ refuse('HOST_ADMISSION_INPUT')
+ if (
+ !Array.isArray(thirdPartyArtifacts) ||
+ thirdPartyArtifacts.length !== 1 ||
+ thirdPartyArtifacts[0].name !== 'sfw-free' ||
+ !/^[a-f0-9]{64}$/.test(thirdPartyArtifacts[0].sha256 ?? '')
+ )
+ refuse('HOST_THIRD_PARTY_ARTIFACT_REQUIRED')
+ return {
+ kind: MAIN_ADMISSION_KIND,
+ runId,
+ suiteId,
+ mode,
+ profile,
+ context,
+ repoRoot,
+ gitHead,
+ gitTree,
+ inputManifestSha256,
+ sourceManifestSha256,
+ imageId,
+ baseImage: base.reference,
+ uiFeatures: { ...suiteBuildArgs(suite), ...(uiFeatures ?? {}) },
+ runtime,
+ observation,
+ networkNamespace,
+ ipcNamespace,
+ stack: {
+ gitHead,
+ worktreeId: stack.data.worktreeId,
+ clusterFingerprint: stack.data.clusterFingerprint,
+ imagesGeneratedAt: stack.data.imagesGeneratedAt,
+ portsReceiptSha256: stack.portsEnvSha256,
+ },
+ receipts,
+ thirdPartyArtifacts,
+ bindings,
+ transports,
+ ...(vendorSources ? { vendorSources } : {}),
+ }
+}
diff --git a/scripts/tests/lib/subscription-image-runner-contract.mjs b/scripts/tests/lib/subscription-image-runner-contract.mjs
new file mode 100644
index 000000000..c64386a18
--- /dev/null
+++ b/scripts/tests/lib/subscription-image-runner-contract.mjs
@@ -0,0 +1,1290 @@
+// E2E_GUARDIAN_IPC_FLOW: physical admission helpers only; no launch, login,
+// environment-file loading, network, or filesystem access at module import.
+import { execFileSync } from 'node:child_process'
+import { createHash } from 'node:crypto'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import { isDeepStrictEqual } from 'node:util'
+
+export class RunnerAdmissionError extends Error {
+ constructor(code) {
+ super(code)
+ this.name = 'RunnerAdmissionError'
+ this.code = code
+ }
+}
+const refuse = code => {
+ throw new RunnerAdmissionError(code)
+}
+export const digest = value => createHash('sha256').update(value).digest('hex')
+const inside = (root, value) => path.isAbsolute(value) && value.startsWith(`${root}/`)
+const integer = value => Number.isSafeInteger(value) && value > 0
+const nsFields = ['mountNamespace', 'pidNamespace', 'userNamespace']
+const nsNames = ['mnt', 'pid', 'user']
+export const RUNNER_RUN_BASE = '/run/evenfire-e2e'
+export const RUNNER_ADMISSION_ROOT = '/runner-admission'
+
+export function readPrivateRecord(filename, maxBytes = 64 * 1024, uid = process.getuid?.()) {
+ if (fs.realpathSync(path.dirname(filename)) !== path.dirname(filename))
+ refuse('PRIVATE_PARENT_SYMLINK')
+ const fd = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW)
+ try {
+ const stat = fs.fstatSync(fd)
+ if (
+ !stat.isFile() ||
+ stat.nlink !== 1 ||
+ stat.uid !== uid ||
+ (stat.mode & 0o777) !== 0o600 ||
+ stat.size > maxBytes
+ )
+ refuse('PRIVATE_JSON_OWNERSHIP_OR_BOUND')
+ const raw = fs.readFileSync(fd)
+ return { value: JSON.parse(raw.toString('utf8')), sha256: digest(raw) }
+ } finally {
+ fs.closeSync(fd)
+ }
+}
+export function readPrivateJson(filename, maxBytes = 64 * 1024, uid = process.getuid?.()) {
+ return readPrivateRecord(filename, maxBytes, uid).value
+}
+
+// Sealed receipts reach the run container through a per-run named volume: the
+// non-root prep helper in this image writes them as 0600 owned by the container
+// user, then the run container mounts that volume read-only. Provenance is the
+// main-side docker inspect plus the volume identity and hash bindings in the
+// admission, not an "other uid" assertion.
+export function readMainRecord(filename, maxBytes = 4 * 1024 * 1024) {
+ const parent = path.dirname(filename)
+ if (fs.realpathSync(parent) !== parent) refuse('MAIN_RECEIPT_PARENT_SYMLINK')
+ const fd = fs.openSync(filename, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW)
+ try {
+ const stat = fs.fstatSync(fd)
+ if (
+ !stat.isFile() ||
+ stat.nlink !== 1 ||
+ (stat.mode & 0o777) !== 0o600 ||
+ stat.uid !== process.getuid?.() ||
+ stat.size > maxBytes
+ )
+ refuse('MAIN_RECEIPT_BOUND_OR_MODE')
+ if (stat.uid === process.getuid?.()) refuse('MAIN_RECEIPT_AUTHORED_BY_RUNNER')
+ const raw = fs.readFileSync(fd)
+ return { value: JSON.parse(raw.toString('utf8')), sha256: digest(raw), uid: stat.uid }
+ } finally {
+ fs.closeSync(fd)
+ }
+}
+
+const PORT_FORWARD_RECORD_VERSION = '1'
+const PORT_FORWARD_RECORD_KEYS = [
+ 'PORT_FORWARD_OWNER_VERSION',
+ 'PID',
+ 'PROCESS_START',
+ 'PROFILE',
+ 'CONTEXT',
+ 'WORKTREE',
+ 'NAMESPACE',
+ 'SERVICE',
+ 'LOCAL_PORT',
+ 'REMOTE_PORT',
+ 'ADDRESS',
+]
+// Exact parser for scripts/minikube/port-forward-owner.sh records.
+export function parsePortForwardRecord(text) {
+ if (typeof text !== 'string' || !text.length || text.length > 8 * 1024)
+ refuse('PORT_FORWARD_RECORD_BOUND')
+ const lines = text.split('\n')
+ while (lines.length && lines[lines.length - 1] === '') lines.pop()
+ const first = lines.shift()
+ if (!/^[1-9][0-9]*$/.test(first ?? '')) refuse('PORT_FORWARD_RECORD_PID')
+ const fields = {}
+ for (const line of lines) {
+ const split = line.indexOf('=')
+ if (split <= 0) refuse('PORT_FORWARD_RECORD_LINE')
+ const key = line.slice(0, split)
+ if (!PORT_FORWARD_RECORD_KEYS.includes(key) || Object.hasOwn(fields, key))
+ refuse('PORT_FORWARD_RECORD_KEY')
+ fields[key] = line.slice(split + 1)
+ }
+ if (
+ fields.PORT_FORWARD_OWNER_VERSION !== PORT_FORWARD_RECORD_VERSION ||
+ fields.PID !== first ||
+ fields.ADDRESS !== '127.0.0.1' ||
+ !/^[0-9]{1,5}$/.test(fields.LOCAL_PORT ?? '') ||
+ !/^[0-9]{1,5}$/.test(fields.REMOTE_PORT ?? '') ||
+ !fields.PROCESS_START ||
+ !fields.PROFILE ||
+ !fields.CONTEXT ||
+ !fields.WORKTREE ||
+ !fields.NAMESPACE ||
+ !fields.SERVICE
+ )
+ refuse('PORT_FORWARD_RECORD_SHAPE')
+ return {
+ pid: Number(fields.PID),
+ processStart: fields.PROCESS_START,
+ profile: fields.PROFILE,
+ context: fields.CONTEXT,
+ worktree: fields.WORKTREE,
+ namespace: fields.NAMESPACE,
+ service: fields.SERVICE,
+ localPort: Number(fields.LOCAL_PORT),
+ remotePort: Number(fields.REMOTE_PORT),
+ address: fields.ADDRESS,
+ }
+}
+
+const PORTS_ENV_KEYS = new Set([
+ 'PORT_BASE',
+ 'CONTROL_UI_PORT',
+ 'PROFILE_UI_PORT',
+ 'CONTROL_API_PORT',
+ 'EXTERNAL_REST_API_PORT',
+ 'MEMBER_REGISTRATION_SERVICE_PORT',
+ 'RPC_PROXY_PORT',
+ 'REGISTRY_API_PORT',
+ 'WORKFLOW_APPROVAL_READER_PORT',
+ 'MCP_HOST_PORT',
+ 'CONTROL_UI_URL',
+ 'CONTROL_UI_BASE_URL',
+ 'PROFILE_UI_URL',
+ 'PROFILE_UI_BASE_URL',
+ 'CONTROL_API_URL',
+ 'CONTROL_API_BASE_URL',
+ 'EXTERNAL_REST_API_URL',
+ 'EXTERNAL_REST_API_BASE_URL',
+ 'MEMBER_REGISTRATION_SERVICE_URL',
+ 'MEMBER_REGISTRATION_SERVICE_BASE_URL',
+ 'RPC_PROXY_URL',
+ 'RPC_PROXY_BASE_URL',
+ 'REGISTRY_API_URL',
+ 'REGISTRY_API_BASE_URL',
+ 'WORKFLOW_APPROVAL_READER_URL',
+ 'WORKFLOW_APPROVAL_READER_BASE_URL',
+ 'MCP_HOST_URL',
+ 'MCP_HOST_BASE_URL',
+])
+export function parsePortsEnv(text) {
+ if (typeof text !== 'string' || !text.length || text.length > 8 * 1024)
+ refuse('PORTS_ENV_BOUND')
+ const values = {}
+ for (const raw of text.split('\n')) {
+ const line = raw.trim()
+ if (!line || line.startsWith('#')) continue
+ const split = line.indexOf('=')
+ if (split <= 0) refuse('PORTS_ENV_LINE')
+ const key = line.slice(0, split),
+ value = line.slice(split + 1)
+ if (!PORTS_ENV_KEYS.has(key) || Object.hasOwn(values, key)) refuse('PORTS_ENV_KEY')
+ if (/^[0-9]{2,5}$/.test(value)) values[key] = Number(value)
+ else if (/^http:\/\/127\.0\.0\.1:[0-9]{2,5}$/.test(value)) values[key] = value
+ else refuse('PORTS_ENV_VALUE')
+ }
+ return values
+}
+
+export const MAIN_ADMISSION_KIND = 'evenfire-subscription-image-main-admission-v2'
+export const MAIN_RECEIPT_FILES = {
+ inspect: 'docker-inspect.json',
+ stack: 'stack-marker.json',
+ portForwards: 'port-forwards.json',
+}
+export const PINNED_BASE_IMAGE_FILE = 'scripts/e2e/fixtures/subscription-image-runner.base-image'
+export const SFW_FREE_VERSION = '1.15.1'
+// Official SocketDev/sfw-free release metadata, reviewed from the GitHub API.
+// The linux x86_64 asset name follows the same release naming as arm64; a wrong
+// name fails the pinned checksum fetch instead of silently passing.
+export const SFW_FREE_ASSETS = Object.freeze({
+ 'linux-arm64': {
+ name: 'sfw-free-linux-arm64',
+ arch: 'arm64',
+ machine: 0xb7,
+ bytes: 136_907_904,
+ sha256: '4d02d1c1f5d6b6444721b0a67bd0e80aab182fe7f22d692570d1c14797602c47',
+ },
+ 'linux-x64': {
+ name: 'sfw-free-linux-x86_64',
+ arch: 'x64',
+ machine: 0x3e,
+ bytes: 139_922_624,
+ sha256: '8898d0667c2165aecd695ca797473ec3a429d2ed807d4d0bf9e67c45817ea809',
+ },
+})
+export function sfwFreeAsset(arch = process.arch) {
+ const key = arch === 'arm64' ? 'linux-arm64' : arch === 'x64' ? 'linux-x64' : null
+ if (!key) refuse('SFW_FREE_ARCH_UNSUPPORTED')
+ const asset = SFW_FREE_ASSETS[key]
+ return {
+ ...asset,
+ url: `https://github.com/SocketDev/sfw-free/releases/download/v${SFW_FREE_VERSION}/${asset.name}`,
+ }
+}
+export function verifyThirdPartyArtifact({ bytes, asset } = {}) {
+ if (!Buffer.isBuffer(bytes) || !asset || !/^[a-f0-9]{64}$/.test(asset.sha256 ?? ''))
+ refuse('THIRD_PARTY_ARTIFACT_INPUT')
+ if (bytes.length !== asset.bytes || digest(bytes) !== asset.sha256)
+ refuse('THIRD_PARTY_ARTIFACT_HASH')
+ if (bytes.length < 20 || bytes.subarray(0, 4).toString('hex') !== '7f454c46')
+ refuse('THIRD_PARTY_ARTIFACT_NOT_ELF')
+ if (bytes[4] !== 2 || bytes[5] !== 1) refuse('THIRD_PARTY_ARTIFACT_NOT_ELF64_LE')
+ const elfMachine = bytes.readUInt16LE(18)
+ if (elfMachine !== asset.machine) refuse('THIRD_PARTY_ARTIFACT_MACHINE')
+ return {
+ name: 'sfw-free',
+ version: SFW_FREE_VERSION,
+ arch: asset.arch,
+ sha256: asset.sha256,
+ bytes: asset.bytes,
+ elfMachine,
+ }
+}
+export const SESSION_OBSERVATION_FILE = 'session-observation.json'
+export const SESSION_READY_MARKER = 'session-created'
+export const PORT_FORWARD_SERVICES = {
+ rest: { namespace: 'profiles', service: 'external-rest-api', remotePort: 8091, key: 'EXTERNAL_REST_API_PORT' },
+ rpc: { namespace: 'rpc-proxy', service: 'rpc-proxy', remotePort: 8094, key: 'RPC_PROXY_PORT' },
+}
+const personalStatePath = value =>
+ /(^|\/)(Users|\.ssh|\.aws|\.gnupg|\.config|keychains?|credentials?|docker\.sock)(\/|$)/i.test(
+ typeof value === 'string' ? value : ''
+ )
+
+const unescapeMount = value =>
+ value.replace(/\\([0-7]{3})/g, (_whole, octal) => String.fromCharCode(Number.parseInt(octal, 8)))
+export function parseMountInfo(raw) {
+ return raw
+ .trim()
+ .split('\n')
+ .map(line => {
+ const split = line.indexOf(' - ')
+ if (split < 0) refuse('MOUNTINFO_MALFORMED')
+ const left = line.slice(0, split).split(' '),
+ right = line.slice(split + 3).split(' ')
+ if (left.length < 6 || right.length < 3 || !/^\d+$/.test(left[0]))
+ refuse('MOUNTINFO_MALFORMED')
+ return {
+ id: left[0],
+ root: unescapeMount(left[3]),
+ point: unescapeMount(left[4]),
+ options: left[5].split(','),
+ fsType: right[0],
+ source: unescapeMount(right[1]),
+ superOptions: right[2].split(','),
+ }
+ })
+}
+
+export function verifyMountIsolation(mounts, home, runBase, admissionRoot) {
+ const exact = point => {
+ const matches = mounts.filter(mount => mount.point === point)
+ if (matches.length !== 1) refuse('MOUNT_REQUIRED_OR_AMBIGUOUS')
+ return matches[0]
+ }
+ const root = exact('/')
+ if (!root.options.includes('ro')) refuse('ROOT_FILESYSTEM_WRITABLE')
+ const admission = exact(admissionRoot)
+ if (!admission.options.includes('ro')) refuse('MAIN_ADMISSION_NOT_READONLY')
+ const writable = [exact(home), exact(runBase), exact('/tmp')]
+ for (const mount of writable) {
+ if (
+ mount.fsType !== 'tmpfs' ||
+ mount.root !== '/' ||
+ mount.source !== 'tmpfs' ||
+ !mount.options.includes('rw') ||
+ !mount.options.includes('nosuid') ||
+ !mount.options.includes('nodev')
+ )
+ refuse('FRESH_PRIVATE_TMPFS_REQUIRED')
+ }
+ const allowed = [
+ '/',
+ home,
+ runBase,
+ admissionRoot,
+ '/tmp',
+ '/proc',
+ '/sys',
+ '/dev',
+ '/etc/hosts',
+ '/etc/hostname',
+ '/etc/resolv.conf',
+ '/dev/pts',
+ '/dev/shm',
+ '/dev/mqueue',
+ '/sys/fs/cgroup',
+ ...[
+ 'bus',
+ 'fs',
+ 'irq',
+ 'sys',
+ 'sysrq-trigger',
+ 'acpi',
+ 'interrupts',
+ 'kcore',
+ 'keys',
+ 'latency_stats',
+ 'timer_list',
+ 'timer_stats',
+ 'scsi',
+ ].map(name => `/proc/${name}`),
+ ]
+ for (const mount of mounts) {
+ if (!allowed.includes(mount.point)) refuse('UNREVIEWED_MOUNT')
+ if (personalStatePath(mount.root) || personalStatePath(mount.source))
+ refuse('PERSONAL_STATE_MOUNT')
+ // Nested mounts can hide an inherited home, bus or authentication store.
+ if ([home, runBase, '/tmp', admissionRoot].some(prefix => inside(prefix, mount.point)))
+ refuse('PRIVATE_MOUNT_SHADOWED')
+ }
+ return {
+ homeMountId: writable[0].id,
+ runMountId: writable[1].id,
+ tmpMountId: writable[2].id,
+ admissionMountId: admission.id,
+ }
+}
+
+export function verifyAccount(passwd, uid, gid, home, username) {
+ const accounts = passwd
+ .split('\n')
+ .map(line => line.split(':'))
+ .filter(fields => fields.length === 7 && Number(fields[2]) === uid)
+ if (
+ accounts.length !== 1 ||
+ !integer(uid) ||
+ !integer(gid) ||
+ Number(accounts[0][3]) !== gid ||
+ accounts[0][0] !== username ||
+ accounts[0][5] !== home
+ )
+ refuse('PASSWD_ACCOUNT_MISMATCH')
+}
+
+export function observeLinuxRunner() {
+ if (process.platform !== 'linux' || !integer(process.getuid?.()) || !integer(process.getgid?.()))
+ refuse('NONROOT_LINUX_REQUIRED')
+ if (Number(process.versions.node.split('.')[0]) !== 24) refuse('NODE24_REQUIRED')
+ const user = os.userInfo(),
+ home = fs.realpathSync(user.homedir)
+ verifyAccount(
+ fs.readFileSync('/etc/passwd', 'utf8'),
+ process.getuid(),
+ process.getgid(),
+ home,
+ user.username
+ )
+ const rawMountInfo = fs.readFileSync('/proc/self/mountinfo', 'utf8')
+ const status = fs.readFileSync('/proc/self/status', 'utf8')
+ const statusField = pattern => {
+ const match = status.match(pattern)
+ return match ? match[1] : null
+ }
+ const capEff = statusField(/^CapEff:\s+([0-9a-fA-F]+)$/m)
+ const seccomp = statusField(/^Seccomp:\s+(\d+)$/m)
+ const noNewPrivs = statusField(/^NoNewPrivs:\s+(\d+)$/m)
+ if (!capEff || !/^0+$/.test(capEff)) refuse('RUNNER_CAPABILITIES_PRESENT')
+ if (seccomp !== '2') refuse('RUNNER_SECCOMP_FILTER_REQUIRED')
+ if (noNewPrivs === null) refuse('RUNNER_STATUS_INCOMPLETE')
+ return {
+ observation: {
+ platform: process.platform,
+ uid: process.getuid(),
+ gid: process.getgid(),
+ home,
+ mountNamespace: fs.readlinkSync('/proc/self/ns/mnt'),
+ pidNamespace: fs.readlinkSync('/proc/self/ns/pid'),
+ userNamespace: fs.readlinkSync('/proc/self/ns/user'),
+ mountInfoSha256: digest(rawMountInfo),
+ capabilityStatus: {
+ capEff,
+ seccompMode: Number(seccomp),
+ noNewPrivs: Number(noNewPrivs),
+ },
+ },
+ networkNamespace: fs.readlinkSync('/proc/self/ns/net'),
+ ipcNamespace: fs.readlinkSync('/proc/self/ns/ipc'),
+ mounts: parseMountInfo(rawMountInfo),
+ }
+}
+
+export function verifyRunnerEnvironment(env, observation) {
+ if (
+ env.HOME !== observation.home ||
+ env.SSH_AUTH_SOCK ||
+ env.NODE_OPTIONS ||
+ env.ELECTRON_DISABLE_SANDBOX ||
+ env.ELECTRON_RUN_AS_NODE
+ )
+ refuse('INHERITED_STATE_OR_SANDBOX_OVERRIDE')
+ for (const name of [
+ 'XDG_RUNTIME_DIR',
+ 'XDG_CONFIG_HOME',
+ 'XDG_CACHE_HOME',
+ 'XDG_DATA_HOME',
+ 'TMPDIR',
+ 'XAUTHORITY',
+ ]) {
+ if (
+ env[name] &&
+ !inside(observation.home, env[name]) &&
+ !inside('/run/evenfire-e2e', env[name])
+ )
+ refuse('PRIVATE_RUNTIME_PATH_ESCAPED')
+ }
+}
+
+export function observeProcess(pid, executable, observation) {
+ if (!integer(pid)) refuse('PRIVATE_PROCESS_PID')
+ const proc = `/proc/${pid}`
+ const stat = fs.readFileSync(`${proc}/stat`, 'utf8')
+ const close = stat.lastIndexOf(') ')
+ const fields = stat.slice(close + 2).split(' ')
+ if (close < 0 || !/^\d+$/.test(fields[19]) || ['Z', 'X', 'x'].includes(fields[0]))
+ refuse('PRIVATE_PROCESS_NOT_LIVE')
+ const uidFields = fs
+ .readFileSync(`${proc}/status`, 'utf8')
+ .match(/^Uid:\s+(\d+)\s+(\d+)\s+(\d+)\s+(\d+)$/m)
+ if (!uidFields || uidFields.slice(1).some(value => Number(value) !== observation.uid))
+ refuse('PRIVATE_PROCESS_UID')
+ const executablePath = fs.readlinkSync(`${proc}/exe`)
+ if (
+ path.basename(executablePath) !== executable ||
+ !['/usr/bin/', '/usr/sbin/', '/usr/libexec/', '/usr/lib/', '/bin/', '/sbin/'].some(prefix =>
+ executablePath.startsWith(prefix)
+ )
+ )
+ refuse('PRIVATE_PROCESS_EXECUTABLE')
+ const namespaces = nsNames.map(name => fs.readlinkSync(`${proc}/ns/${name}`))
+ nsFields.forEach((field, index) => {
+ if (namespaces[index] !== observation[field]) refuse('PRIVATE_PROCESS_NAMESPACE')
+ })
+ return {
+ pid,
+ uid: observation.uid,
+ startTime: fields[19],
+ executable,
+ executablePath,
+ argvSha256: digest(fs.readFileSync(`${proc}/cmdline`)),
+ mountNamespace: namespaces[0],
+ pidNamespace: namespaces[1],
+ userNamespace: namespaces[2],
+ }
+}
+
+export function unixSocketInode(table, socketPath) {
+ const rows = table
+ .trim()
+ .split('\n')
+ .slice(1)
+ .map(line => line.trim().split(/\s+/))
+ .filter(fields => fields.slice(7).join(' ') === socketPath)
+ if (rows.length !== 1 || !/^\d+$/.test(rows[0][6])) refuse('PRIVATE_SOCKET_INODE')
+ return rows[0][6]
+}
+export function verifySocketBinding(inode, links) {
+ if (links.filter(value => value === `socket:[${inode}]`).length !== 1)
+ refuse('PRIVATE_SOCKET_PROCESS_BINDING')
+}
+export function privateBusPath(address) {
+ const match =
+ typeof address === 'string' && address.match(/^unix:path=(\/[^,;]+)(?:,guid=[a-f0-9]{32})?$/)
+ if (!match) refuse('PRIVATE_BUS_ADDRESS')
+ return match[1]
+}
+function observeSocketProcess(expected, executable, observation) {
+ const processObservation = observeProcess(expected.pid, executable, observation)
+ const socket = fs.lstatSync(expected.socketPath)
+ if (
+ !socket.isSocket() ||
+ socket.isSymbolicLink() ||
+ socket.uid !== observation.uid ||
+ fs.realpathSync(path.dirname(expected.socketPath)) !== path.dirname(expected.socketPath)
+ )
+ refuse('PRIVATE_SOCKET_OWNERSHIP')
+ const inode = unixSocketInode(fs.readFileSync('/proc/net/unix', 'utf8'), expected.socketPath)
+ const fds = fs.readdirSync(`/proc/${expected.pid}/fd`)
+ if (fds.length > 4096) refuse('PRIVATE_PROCESS_FD_BOUND')
+ const links = fds.map(fd => {
+ try {
+ return fs.readlinkSync(`/proc/${expected.pid}/fd/${fd}`)
+ } catch (err) {
+ if (err.code === 'ENOENT') return ''
+ throw err
+ }
+ })
+ verifySocketBinding(inode, links)
+ return {
+ ...processObservation,
+ socketPath: expected.socketPath,
+ socketInode: inode,
+ }
+}
+
+export function verifyPrivateIsolation(expected, actual, observation, env, runRoot) {
+ if (!expected || !actual || !isDeepStrictEqual(expected, actual))
+ refuse('PRIVATE_ISOLATION_CHANGED')
+ const bus = actual.sessionBus,
+ display = actual.display,
+ keyring = actual.keyring
+ if (
+ !bus ||
+ !display ||
+ !keyring ||
+ !inside(observation.home, bus.socketPath) ||
+ privateBusPath(bus.address) !== bus.socketPath ||
+ env.DBUS_SESSION_BUS_ADDRESS !== bus.address ||
+ !/^:\d+$/.test(display.value) ||
+ env.DISPLAY !== display.value ||
+ env.XAUTHORITY !== display.xauthorityPath ||
+ (!inside(observation.home, display.xauthorityPath) && !inside(runRoot, display.xauthorityPath))
+ )
+ refuse('PRIVATE_BUS_OR_DISPLAY_BINDING')
+ for (const [record, executable] of [
+ [bus, 'dbus-daemon'],
+ [display, 'Xvfb'],
+ [keyring, 'gnome-keyring-daemon'],
+ ]) {
+ if (
+ !integer(record.pid) ||
+ record.uid !== observation.uid ||
+ record.executable !== executable ||
+ path.basename(record.executablePath ?? '') !== executable ||
+ !['/usr/bin/', '/usr/sbin/', '/usr/libexec/', '/usr/lib/', '/bin/', '/sbin/'].some(prefix =>
+ record.executablePath?.startsWith(prefix)
+ ) ||
+ !/^\d+$/.test(record.startTime) ||
+ !/^[a-f0-9]{64}$/.test(record.argvSha256)
+ )
+ refuse('PRIVATE_PROCESS_OBSERVATION')
+ nsFields.forEach(field => {
+ if (record[field] !== observation[field]) refuse('PRIVATE_PROCESS_NAMESPACE')
+ })
+ }
+ if (!/^\d+$/.test(bus.socketInode) || !/^\d+$/.test(display.socketInode))
+ refuse('PRIVATE_SOCKET_OBSERVATION')
+}
+
+export function inspectPrivateIsolation(expected, observation, env, runRoot, mountIds) {
+ if (!expected?.sessionBus || !expected?.display || !expected?.keyring)
+ refuse('PRIVATE_AUTH_OBSERVATION_REQUIRED')
+ if (
+ !inside(observation.home, expected.sessionBus.socketPath) ||
+ privateBusPath(expected.sessionBus.address) !== expected.sessionBus.socketPath
+ )
+ refuse('PRIVATE_BUS_PATH')
+ if (expected.display.socketPath !== `/tmp/.X11-unix/X${expected.display.value?.slice(1)}`)
+ refuse('PRIVATE_DISPLAY_PATH')
+ if (
+ !inside(observation.home, expected.display.xauthorityPath) &&
+ !inside(runRoot, expected.display.xauthorityPath)
+ )
+ refuse('PRIVATE_XAUTHORITY_PATH')
+ const authority = fs.lstatSync(expected.display.xauthorityPath)
+ if (
+ !authority.isFile() ||
+ authority.isSymbolicLink() ||
+ authority.nlink !== 1 ||
+ authority.uid !== observation.uid ||
+ (authority.mode & 0o077) !== 0
+ )
+ refuse('PRIVATE_XAUTHORITY_OWNERSHIP')
+ const actual = {
+ ...mountIds,
+ sessionBus: {
+ ...observeSocketProcess(expected.sessionBus, 'dbus-daemon', observation),
+ address: expected.sessionBus.address,
+ },
+ display: {
+ ...observeSocketProcess(expected.display, 'Xvfb', observation),
+ value: expected.display.value,
+ xauthorityPath: expected.display.xauthorityPath,
+ },
+ keyring: observeProcess(expected.keyring.pid, 'gnome-keyring-daemon', observation),
+ }
+ verifyPrivateIsolation(actual, actual, observation, env, runRoot)
+ return actual
+}
+
+export function observePrivateIsolation(expected, observation, env, runRoot, mountIds) {
+ const actual = inspectPrivateIsolation(expected, observation, env, runRoot, mountIds)
+ verifyPrivateIsolation(expected, actual, observation, env, runRoot)
+ return actual
+}
+
+// GNOME's encrypted binary format has this 16-byte magic plus four supported
+// version/cipher/hash bytes. Only these public bytes are read, never contents.
+// https://github.com/GNOME/gnome-keyring/blob/main/pkcs11/secret-store/gkm-secret-binary.c
+const encryptedKeyringHeader = Buffer.from('GnomeKeyring\n\r\0\n\0\0\0\0', 'utf8')
+export function isEncryptedKeyringHeader(bytes) {
+ return bytes.length === 20 && bytes.equals(encryptedKeyringHeader)
+}
+export function verifyEncryptedKeyringFiles(env, uid) {
+ if (!env.XDG_DATA_HOME || !inside(env.HOME, env.XDG_DATA_HOME))
+ refuse('PRIVATE_KEYRING_DATA_PATH')
+ const directory = path.join(env.XDG_DATA_HOME, 'keyrings')
+ if (fs.realpathSync(directory) !== directory) refuse('PRIVATE_KEYRING_DIRECTORY')
+ const files = fs.readdirSync(directory).filter(name => name.endsWith('.keyring'))
+ if (!files.length || files.length > 16) refuse('PRIVATE_ENCRYPTED_KEYRING_REQUIRED')
+ for (const name of files) {
+ const fd = fs.openSync(
+ path.join(directory, name),
+ fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW
+ )
+ try {
+ const stat = fs.fstatSync(fd),
+ header = Buffer.alloc(20)
+ if (
+ !stat.isFile() ||
+ stat.nlink !== 1 ||
+ stat.uid !== uid ||
+ (stat.mode & 0o077) !== 0 ||
+ fs.readSync(fd, header, 0, 20, 0) !== 20 ||
+ !isEncryptedKeyringHeader(header)
+ )
+ refuse('PLAINTEXT_OR_UNOWNED_KEYRING')
+ } finally {
+ fs.closeSync(fd)
+ }
+ }
+}
+export function verifyNativePrivateKeychain(repoRoot, env) {
+ verifyEncryptedKeyringFiles(env, process.getuid())
+ // keytar has no per-call AbortSignal. Keep the random roundtrip in a bounded
+ // disposable native process so a stalled service cannot hang admission.
+ const code = `import {createRequire} from 'node:module'; import {randomBytes,randomUUID} from 'node:crypto';
+ const keytar=createRequire(process.argv[1])('keytar'); const account=randomUUID(); const value=randomBytes(32).toString('hex');
+ try { await keytar.setPassword('evenfire-subscription-image-isolation-probe',account,value);
+ if (await keytar.getPassword('evenfire-subscription-image-isolation-probe',account)!==value) process.exitCode=1;
+ } finally { await keytar.deletePassword('evenfire-subscription-image-isolation-probe',account); }`
+ /** @type {NodeJS.ProcessEnv} */
+ const nativeEnv = {}
+ for (const name of [
+ 'PATH',
+ 'HOME',
+ 'USER',
+ 'LOGNAME',
+ 'LANG',
+ 'LC_ALL',
+ 'DISPLAY',
+ 'XAUTHORITY',
+ 'DBUS_SESSION_BUS_ADDRESS',
+ 'XDG_RUNTIME_DIR',
+ 'XDG_CONFIG_HOME',
+ 'XDG_CACHE_HOME',
+ 'XDG_DATA_HOME',
+ 'TMPDIR',
+ ])
+ if (env[name]) nativeEnv[name] = env[name]
+ try {
+ execFileSync(
+ process.execPath,
+ ['--input-type=module', '-e', code, path.join(repoRoot, 'desktop-app/package.json')],
+ {
+ env: nativeEnv,
+ timeout: 10_000,
+ killSignal: 'SIGKILL',
+ stdio: 'ignore',
+ }
+ )
+ } catch {
+ refuse('PRIVATE_NATIVE_KEYCHAIN_FAILED')
+ }
+ verifyEncryptedKeyringFiles(env, process.getuid())
+}
+
+export function refusePlaintextSessionFiles(directories) {
+ for (const directory of directories) {
+ if (!fs.existsSync(directory)) continue
+ if (
+ fs
+ .readdirSync(directory)
+ .some(name => /^session-token(?:-.*)?\.json(?:\..*\.tmp)?$/.test(name))
+ )
+ refuse('PLAINTEXT_DESKTOP_SESSION_FORBIDDEN')
+ }
+}
+
+export function expectedJourneyNames(mode) {
+ const names = [
+ 'png pixels reach the selected owned Host and model',
+ 'jpeg pixels reach the selected owned Host and model',
+ 'mixed PNG/JPEG preserve attachment and wire order',
+ 'near 16 MiB composer image carries real pixels',
+ 'twenty ordered images complete without a dropped or repeated code',
+ 'over-budget refusal leaves no task or dispatch and permits a subsequent text turn',
+ 'unsupported model blocks image send, then visible removal and primary selection recover',
+ ]
+ const cases = ['grok-subscription', 'codex-subscription'].flatMap(provider =>
+ names.map(name => `${provider} ${name}`)
+ )
+ if (mode === 'real') cases.push('G8 Grok reads pixels in a 9000 px PNG through the owned Host')
+ return cases
+}
+
+export const CERTIFIED_SUITE_ID = 'subscription-image-input'
+const SUITE_PROVIDERS = ['grok-subscription', 'codex-subscription']
+// Opt-in suite registry. Additional suites stay separate from the certified
+// 14/15 inventory: each suite owns its own config/spec, project name and exact
+// case identities, and a runner receipt never merges two suites.
+export const SUITE_CONTRACTS = Object.freeze({
+ [CERTIFIED_SUITE_ID]: {
+ suiteId: CERTIFIED_SUITE_ID,
+ project: 'subscription-image-input',
+ configFile: 'test/e2e-playwright/playwright.subscription-image.config.ts',
+ specFile: 'desktop-app/test/e2e-playwright/subscription-image-input.spec.ts',
+ modes: ['fixture', 'real'],
+ buildArgs: {},
+ expectedNames: mode => expectedJourneyNames(mode),
+ },
+ 'tool-screenshot': {
+ suiteId: 'tool-screenshot',
+ project: 'tool-screenshot',
+ configFile: 'test/e2e-playwright/playwright.subscription-tool-screenshot.config.ts',
+ specFile: 'desktop-app/test/e2e-playwright/subscription-tool-screenshot.spec.ts',
+ modes: ['fixture', 'real'],
+ buildArgs: {},
+ optInEnv: 'E2E_SUBSCRIPTION_TOOL_SCREENSHOT',
+ fixtureReceiptEnv: 'E2E_SUBSCRIPTION_REMAINING_FIXTURE_RECEIPT',
+ expectedNames: () => [
+ 'grok-subscription real desktop screenshot tool yields pixel evidence after visible approval',
+ 'codex-subscription real desktop screenshot tool yields pixel evidence after visible approval',
+ ],
+ },
+ 'gfs-image': {
+ suiteId: 'gfs-image',
+ project: 'gfs-image',
+ configFile: 'test/e2e-playwright/playwright.subscription-gfs-image.config.ts',
+ specFile: 'desktop-app/test/e2e-playwright/subscription-gfs-image.spec.ts',
+ modes: ['fixture', 'real'],
+ buildArgs: { VITE_SHOW_GLOBAL_FILE_SYSTEM_COMPOSER_ITEM: 'true' },
+ optInEnv: 'E2E_SUBSCRIPTION_GFS_IMAGE',
+ fixtureReceiptEnv: 'E2E_SUBSCRIPTION_REMAINING_FIXTURE_RECEIPT',
+ expectedNames: () =>
+ SUITE_PROVIDERS.map(
+ provider =>
+ `${provider} Files preview and attached GFS image preserve source and ordered pixels`
+ ),
+ },
+ 'admission-recovery': {
+ suiteId: 'admission-recovery',
+ project: 'admission-recovery',
+ configFile: 'test/e2e-playwright/playwright.subscription-admission-recovery.config.ts',
+ specFile: 'desktop-app/test/e2e-playwright/subscription-admission-recovery.spec.ts',
+ modes: ['fixture'],
+ buildArgs: {},
+ optInEnv: 'E2E_SUBSCRIPTION_ADMISSION_RECOVERY',
+ fixtureReceiptEnv: 'E2E_SUBSCRIPTION_REMAINING_FIXTURE_RECEIPT',
+ expectedNames: () =>
+ SUITE_PROVIDERS.map(
+ provider =>
+ `${provider} local admission refusal settles visibly and a subsequent text turn stays on primary`
+ ),
+ },
+})
+export function resolveSuite(suiteId = CERTIFIED_SUITE_ID) {
+ const suite = SUITE_CONTRACTS[suiteId]
+ if (!suite) refuse('SUITE_UNKNOWN')
+ return suite
+}
+export function suiteBuildArgs(suite) {
+ const args = suite?.buildArgs ?? {}
+ for (const [name, value] of Object.entries(args)) {
+ if (!/^VITE_[A-Z0-9_]+$/.test(name) || !['true', 'false'].includes(value))
+ refuse('SUITE_BUILD_ARG_INVALID')
+ }
+ return args
+}
+export function suiteExpectedNames(suite, mode) {
+ if (!suite.modes.includes(mode)) refuse('SUITE_MODE_NOT_ADMITTED')
+ const names = suite.expectedNames(mode)
+ if (!Array.isArray(names) || !names.length || new Set(names).size !== names.length)
+ refuse('SUITE_EXPECTED_NAMES')
+ return names
+}
+export function verifySuiteReport(report, mode, suite, expectedFile) {
+ const expected = suiteExpectedNames(suite, mode)
+ if (
+ !report?.config?.rootDir ||
+ !Array.isArray(report.suites) ||
+ !Array.isArray(report.errors) ||
+ report.errors.length ||
+ report.stats?.expected !== expected.length ||
+ report.stats.unexpected !== 0 ||
+ report.stats.flaky !== 0 ||
+ report.stats.skipped !== 0
+ )
+ refuse('JOURNEY_REPORT_INCOMPLETE')
+ const actual = []
+ const visit = (reportSuite, parents) => {
+ const names =
+ reportSuite.title === path.basename(expectedFile) ? parents : [...parents, reportSuite.title]
+ for (const spec of reportSuite.specs ?? []) {
+ if (
+ path.resolve(report.config.rootDir, spec.file) !== expectedFile ||
+ spec.ok !== true ||
+ spec.tests?.length !== 1
+ )
+ refuse('JOURNEY_REPORT_PHYSICAL_FILE')
+ const result = spec.tests[0]
+ if (
+ result.projectName !== suite.project ||
+ result.expectedStatus !== 'passed' ||
+ result.status !== 'expected' ||
+ result.results?.length !== 1 ||
+ result.results[0].status !== 'passed'
+ )
+ refuse('JOURNEY_REPORT_NONGREEN')
+ actual.push([...names, spec.title].filter(Boolean).join(' '))
+ }
+ for (const child of reportSuite.suites ?? []) visit(child, names)
+ }
+ report.suites.forEach(suite => visit(suite, []))
+ if (
+ actual.length !== expected.length ||
+ new Set(actual).size !== actual.length ||
+ expected.some(name => !actual.includes(name))
+ )
+ refuse('JOURNEY_REPORT_CASE_IDENTITY')
+ return { executed: actual.length, passed: actual.length, fullNames: actual }
+}
+export function verifyJourneyReport(report, mode, expectedFile) {
+ return verifySuiteReport(report, mode, resolveSuite(), expectedFile)
+}
+
+export function admitVendorFrame(frame, runId, binding, source, previous) {
+ if (
+ frame.kind !== 'evenfire-subscription-image-vendor-frame-v1' ||
+ frame.runId !== runId ||
+ frame.provider !== binding.provider ||
+ !isDeepStrictEqual(frame.source, source) ||
+ frame.ledger?.kind !== 'evenfire-subscription-image-vendor-v1' ||
+ frame.ledger.runId !== runId ||
+ !Array.isArray(frame.ledger.attempts) ||
+ frame.ledger.attempts.length > 256 ||
+ frame.ledger.attempts.length < previous.length
+ )
+ refuse('VENDOR_EVIDENCE_SOURCE_OR_SEQUENCE')
+ for (const [index, row] of frame.ledger.attempts.entries()) {
+ const allowed = [
+ 'sequence',
+ 'provider',
+ 'model',
+ 'receiptId',
+ 'imageSha256',
+ 'mimeTypes',
+ 'requestSha256',
+ 'responseKind',
+ 'outputSha256',
+ ]
+ if (
+ Object.keys(row).some(key => !allowed.includes(key)) ||
+ row.sequence !== index + 1 ||
+ row.provider !== binding.provider ||
+ ![binding.modelId, binding.unsupportedModelId].includes(row.model) ||
+ !/^[a-f0-9-]{36}$/.test(row.receiptId) ||
+ !Array.isArray(row.imageSha256) ||
+ row.imageSha256.length > 20 ||
+ row.imageSha256.some(value => !/^[a-f0-9]{64}$/.test(value)) ||
+ !Array.isArray(row.mimeTypes) ||
+ row.mimeTypes.length !== row.imageSha256.length ||
+ row.mimeTypes.some(value => !['image/png', 'image/jpeg'].includes(value)) ||
+ !/^[a-f0-9]{64}$/.test(row.requestSha256) ||
+ !['pixels', 'text', 'rejected'].includes(row.responseKind) ||
+ (row.outputSha256 !== undefined && !/^[a-f0-9]{64}$/.test(row.outputSha256))
+ )
+ refuse('VENDOR_EVIDENCE_SHAPE')
+ if (index < previous.length && !isDeepStrictEqual(row, previous[index]))
+ refuse('VENDOR_EVIDENCE_HISTORY_CHANGED')
+ }
+ return frame.ledger
+}
+
+export function pinnedBaseImage(repoRoot) {
+ const raw = fs.readFileSync(path.join(repoRoot, PINNED_BASE_IMAGE_FILE), 'utf8')
+ if (!raw.length || raw.length > 16 * 1024) refuse('PINNED_BASE_IMAGE_BOUND')
+ let parsed
+ try {
+ parsed = JSON.parse(raw)
+ } catch {
+ refuse('PINNED_BASE_IMAGE_INVALID')
+ }
+ if (
+ parsed.kind !== 'evenfire-subscription-image-base-image-v1' ||
+ typeof parsed.reference !== 'string' ||
+ !/^[a-z0-9][a-z0-9._/-]*(?::[a-zA-Z0-9._-]+)?@sha256:[a-f0-9]{64}$/.test(parsed.reference) ||
+ parsed.nodeMajor !== 24 ||
+ !Array.isArray(parsed.requiredCommands) ||
+ parsed.requiredCommands.some(name => typeof name !== 'string' || !name)
+ )
+ refuse('PINNED_BASE_IMAGE_INVALID')
+ return parsed
+}
+
+export function verifyRuntimeReceipts(admission, receipts, phase = 'admit') {
+ const runtime = admission.runtime
+ const inspectRecord = receipts?.inspect,
+ stackRecord = receipts?.stack,
+ portForwardsRecord = receipts?.portForwards
+ if (
+ !inspectRecord?.value?.container ||
+ !Array.isArray(inspectRecord.value.securityOptions) ||
+ !stackRecord?.value ||
+ !portForwardsRecord?.value
+ )
+ refuse('MAIN_RECEIPTS_REQUIRED')
+ if (
+ !/^[a-f0-9]{64}$/.test(inspectRecord.sha256 ?? '') ||
+ !/^[a-f0-9]{64}$/.test(stackRecord.sha256 ?? '') ||
+ !/^[a-f0-9]{64}$/.test(portForwardsRecord.sha256 ?? '')
+ )
+ refuse('MAIN_RECEIPT_HASHES_REQUIRED')
+ const inspect = inspectRecord.value,
+ stack = stackRecord.value,
+ portForwards = portForwardsRecord.value
+ const container = inspect.container,
+ hostConfig = container.HostConfig,
+ securityOptions = inspect.securityOptions
+ if (
+ container.Id !== runtime.containerId ||
+ container.Image !== admission.imageId ||
+ Date.parse(container.Created) !== Date.parse(runtime.createdAt) ||
+ container.Config?.User !== runtime.user ||
+ container.State?.Running !== true ||
+ !hostConfig ||
+ hostConfig.ReadonlyRootfs !== true ||
+ hostConfig.Privileged !== false ||
+ (hostConfig.PidMode || 'private') !== 'private' ||
+ (hostConfig.IpcMode || 'private') !== 'private' ||
+ typeof hostConfig.NetworkMode !== 'string' ||
+ !hostConfig.NetworkMode ||
+ hostConfig.NetworkMode === 'host' ||
+ hostConfig.NetworkMode.startsWith('container:') ||
+ !isDeepStrictEqual(hostConfig.CapDrop, ['ALL']) ||
+ !Array.isArray(hostConfig.SecurityOpt) ||
+ hostConfig.SecurityOpt.some(value => typeof value !== 'string') ||
+ hostConfig.SecurityOpt.some(value => /seccomp=unconfined|no-new-privileges/i.test(value)) ||
+ securityOptions.some(value => typeof value !== 'string' || /unconfined/i.test(value)) ||
+ !securityOptions.some(value => /seccomp/i.test(value))
+ )
+ refuse('DOCKER_INSPECT_RUNTIME_MISMATCH')
+ const home = admission.observation.home
+ const mounts = Array.isArray(container.Mounts) ? container.Mounts : []
+ const admissionMounts = mounts.filter(mount => mount.Destination === RUNNER_ADMISSION_ROOT)
+ const tmpfsOk = [home, RUNNER_RUN_BASE, '/tmp'].every(destination => {
+ const matches = mounts.filter(mount => mount.Destination === destination)
+ return matches.length === 1 && matches[0].Type === 'tmpfs' && matches[0].RW === true
+ })
+ if (
+ mounts.length !== 4 ||
+ admissionMounts.length !== 1 ||
+ admissionMounts[0].Type !== 'bind' ||
+ admissionMounts[0].RW !== false ||
+ typeof admissionMounts[0].Source !== 'string' ||
+ !admissionMounts[0].Source ||
+ mounts.some(mount => mount.Type === 'bind' && mount.Destination !== RUNNER_ADMISSION_ROOT) ||
+ mounts.some(mount => personalStatePath(mount.Source) || personalStatePath(mount.Destination)) ||
+ !tmpfsOk
+ )
+ refuse('DOCKER_INSPECT_MOUNTS_MISMATCH')
+ const allowedEnv = new Set([
+ 'PATH',
+ 'HOME',
+ 'USER',
+ 'LOGNAME',
+ 'LANG',
+ 'LC_ALL',
+ 'TERM',
+ 'NODE_VERSION',
+ 'YARN_VERSION',
+ 'SUBSCRIPTION_IMAGE_RUN_ID',
+ ])
+ const envEntries = Array.isArray(container.Config?.Env) ? container.Config.Env : []
+ for (const entry of envEntries) {
+ const split = typeof entry === 'string' ? entry.indexOf('=') : -1
+ if (split <= 0) refuse('CONTAINER_ENV_NOT_REVIEWED')
+ const name = entry.slice(0, split)
+ if (!allowedEnv.has(name) || /(SECRET|TOKEN|PASSWORD|CREDENTIAL|API_KEY|AUTH)/i.test(name))
+ refuse('CONTAINER_ENV_NOT_REVIEWED')
+ }
+ if (!envEntries.includes(`SUBSCRIPTION_IMAGE_RUN_ID=${admission.runId}`))
+ refuse('CONTAINER_ENV_RUN_BINDING')
+ if (
+ stack.kind !== 'evenfire-subscription-image-stack-marker-v1' ||
+ stack.context !== admission.context ||
+ stack.configMapName !== 'clerum-pre-gate-sync-state' ||
+ typeof stack.resourceVersion !== 'string' ||
+ !stack.resourceVersion ||
+ !Number.isFinite(Date.parse(stack.fetchedAt)) ||
+ !stack.data ||
+ typeof stack.data !== 'object' ||
+ stack.data.gitHead !== admission.gitHead ||
+ stack.data.worktreeId !== admission.stack.worktreeId ||
+ stack.data.clusterFingerprint !== admission.stack.clusterFingerprint ||
+ stack.data.imagesGeneratedAt !== admission.stack.imagesGeneratedAt ||
+ typeof stack.portsEnvRaw !== 'string' ||
+ !/^[a-f0-9]{64}$/.test(stack.portsEnvSha256 ?? '') ||
+ digest(stack.portsEnvRaw) !== stack.portsEnvSha256 ||
+ stack.portsEnvSha256 !== admission.stack.portsReceiptSha256
+ )
+ refuse('STACK_MARKER_MISMATCH')
+ const ports = parsePortsEnv(stack.portsEnvRaw)
+ if (
+ portForwards.kind !== 'evenfire-subscription-image-port-forwards-v1' ||
+ !Number.isFinite(Date.parse(portForwards.verifiedAt)) ||
+ !portForwards.entries ||
+ typeof portForwards.entries !== 'object'
+ )
+ refuse('PORT_FORWARD_RECEIPT_REQUIRED')
+ for (const [kind, expected] of Object.entries(PORT_FORWARD_SERVICES)) {
+ const entry = portForwards.entries[kind],
+ target = admission.transports?.[kind]
+ if (!entry || typeof entry.raw !== 'string' || !/^[a-f0-9]{64}$/.test(entry.recordSha256 ?? ''))
+ refuse('PORT_FORWARD_RECEIPT_REQUIRED')
+ const record = parsePortForwardRecord(entry.raw)
+ let origin
+ try {
+ origin = new URL(target?.origin)
+ } catch {
+ refuse('OWNED_TRANSPORT_REQUIRED')
+ }
+ if (
+ digest(entry.raw) !== entry.recordSha256 ||
+ entry.recordSha256 !== target.forwardBindingSha256 ||
+ record.profile !== admission.profile ||
+ record.context !== admission.context ||
+ record.namespace !== expected.namespace ||
+ record.service !== expected.service ||
+ record.remotePort !== expected.remotePort ||
+ record.localPort !== Number(origin.port) ||
+ record.address !== '127.0.0.1' ||
+ ports[expected.key] !== record.localPort
+ )
+ refuse('PORT_FORWARD_RECEIPT_MISMATCH')
+ }
+ const generatedAt = Date.parse(admission.receipts.generatedAt)
+ if (
+ Date.now() - generatedAt < 0 ||
+ Date.now() - generatedAt > (phase === 'admit' ? 600_000 : 4_200_000) ||
+ Math.abs(Date.parse(portForwards.verifiedAt) - generatedAt) > 300_000
+ )
+ refuse('MAIN_RECEIPT_STALE')
+}
+
+export function verifyMainAdmission(
+ admission,
+ physical,
+ source,
+ repoRoot,
+ env,
+ phase = 'admit',
+ receipts
+) {
+ const artifacts = admission.thirdPartyArtifacts
+ if (
+ !Array.isArray(artifacts) ||
+ artifacts.length !== 1 ||
+ artifacts[0].name !== 'sfw-free' ||
+ artifacts[0].version !== SFW_FREE_VERSION ||
+ !/^[a-f0-9]{64}$/.test(artifacts[0].sha256 ?? '')
+ )
+ refuse('THIRD_PARTY_ARTIFACT_REQUIRED')
+ if (
+ admission.kind !== MAIN_ADMISSION_KIND ||
+ !/^subscription-image-[a-f0-9]{12}$/.test(admission.runId) ||
+ typeof admission.suiteId !== 'string' ||
+ !SUITE_CONTRACTS[admission.suiteId] ||
+ admission.gitHead !== source.gitHead ||
+ admission.gitTree !== source.gitTree ||
+ admission.inputManifestSha256 !== source.inputManifestSha256 ||
+ admission.sourceManifestSha256 !== source.manifestSha256 ||
+ admission.repoRoot !== repoRoot ||
+ !/^sha256:[a-f0-9]{64}$/.test(admission.imageId) ||
+ admission.baseImage !== pinnedBaseImage(repoRoot).reference ||
+ !isDeepStrictEqual(
+ admission.uiFeatures ?? {},
+ suiteBuildArgs(resolveSuite(admission.suiteId))
+ ) ||
+ !isDeepStrictEqual(admission.observation, physical.observation) ||
+ admission.networkNamespace !== physical.networkNamespace ||
+ admission.ipcNamespace !== physical.ipcNamespace
+ )
+ refuse('MAIN_ADMISSION_IDENTITY')
+ if (
+ admission.profile !== admission.context ||
+ !/^[a-z0-9][a-z0-9-]{0,62}$/.test(admission.profile) ||
+ admission.profile === 'clerum-test' ||
+ /(^|-)(prod|production)(-|$)/i.test(admission.profile)
+ )
+ refuse('OWNED_DEVELOPMENT_PROFILE_REQUIRED')
+ const stack = admission.stack
+ if (
+ !stack ||
+ stack.gitHead !== source.gitHead ||
+ !/^[a-f0-9]{40}$/.test(stack.worktreeId) ||
+ !/^[a-f0-9]{64}$/.test(stack.clusterFingerprint) ||
+ !stack.imagesGeneratedAt ||
+ !/^[a-f0-9]{64}$/.test(stack.portsReceiptSha256)
+ )
+ refuse('EXACT_STACK_MARKER_REQUIRED')
+ const runtime = admission.runtime
+ if (
+ !runtime ||
+ runtime.readOnlyRootfs !== true ||
+ runtime.privileged !== false ||
+ runtime.pidMode !== 'private' ||
+ runtime.ipcMode !== 'private' ||
+ runtime.networkMode === 'host' ||
+ !runtime.networkMode ||
+ runtime.user !== `${physical.observation.uid}:${physical.observation.gid}` ||
+ !isDeepStrictEqual(runtime.capDrop, ['ALL']) ||
+ runtime.seccompMode !== 'filter' ||
+ !/^[a-f0-9]{64}$/.test(runtime.containerId) ||
+ !Number.isFinite(Date.parse(runtime.createdAt)) ||
+ Date.now() - Date.parse(runtime.createdAt) < 0 ||
+ !['admit', 'verify'].includes(phase) ||
+ Date.now() - Date.parse(runtime.createdAt) > (phase === 'admit' ? 600_000 : 4_200_000)
+ )
+ refuse('RUNTIME_ISOLATION_POLICY')
+ if (
+ !admission.receipts ||
+ !Number.isFinite(Date.parse(admission.receipts.generatedAt)) ||
+ !/^[a-f0-9]{64}$/.test(admission.receipts.dockerInspectSha256 ?? '') ||
+ !/^[a-f0-9]{64}$/.test(admission.receipts.stackMarkerSha256 ?? '') ||
+ !/^[a-f0-9]{64}$/.test(admission.receipts.portForwardsSha256 ?? '')
+ )
+ refuse('MAIN_RECEIPT_HASHES_REQUIRED')
+ const volume = admission.volume
+ if (
+ !volume ||
+ volume.name !==
+ `evenfire-sir-${admission.runId.slice('subscription-image-'.length)}-admission` ||
+ volume.driver !== 'local' ||
+ !Number.isFinite(Date.parse(volume.createdAt)) ||
+ !/^[a-f0-9]{64}$/.test(volume.inspectSha256 ?? '')
+ )
+ refuse('ADMISSION_VOLUME_IDENTITY')
+ if (
+ receipts?.inspect?.sha256 !== admission.receipts.dockerInspectSha256 ||
+ receipts?.stack?.sha256 !== admission.receipts.stackMarkerSha256 ||
+ receipts?.portForwards?.sha256 !== admission.receipts.portForwardsSha256
+ )
+ refuse('MAIN_RECEIPT_FILE_HASH')
+ if (
+ !['fixture', 'real'].includes(admission.mode) ||
+ !Array.isArray(admission.bindings) ||
+ admission.bindings.length !== 2 ||
+ new Set(admission.bindings.map(binding => binding.provider)).size !== 2 ||
+ !admission.bindings.some(binding => binding.provider === 'codex-subscription') ||
+ !admission.bindings.some(binding => binding.provider === 'grok-subscription')
+ )
+ refuse('PROVIDER_BINDINGS_REQUIRED')
+ verifyRunnerEnvironment(env, physical.observation)
+ const seen = new Set()
+ for (const [kind, service] of [
+ ['rest', 'external-rest-api'],
+ ['rpc', 'rpc-proxy'],
+ ]) {
+ const target = admission.transports?.[kind]
+ let url
+ try {
+ url = new URL(target?.origin)
+ } catch {
+ refuse('OWNED_TRANSPORT_REQUIRED')
+ }
+ if (
+ url.protocol !== 'http:' ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash ||
+ !['', '/'].includes(url.pathname) ||
+ !url.port ||
+ !['127.0.0.1', '[::1]', 'host.docker.internal'].includes(url.hostname) ||
+ ['3000', '8090', '8091', '8094', '8098'].includes(url.port) ||
+ target.service !== service ||
+ target.profile !== admission.profile ||
+ target.context !== admission.context ||
+ target.worktreeId !== stack.worktreeId ||
+ target.gitHead !== stack.gitHead ||
+ target.portsReceiptSha256 !== stack.portsReceiptSha256 ||
+ !/^[a-f0-9]{64}$/.test(target.forwardBindingSha256)
+ )
+ refuse('OWNED_TRANSPORT_REQUIRED')
+ if (seen.has(url.origin)) refuse('TRANSPORT_TARGETS_AMBIGUOUS')
+ seen.add(url.origin)
+ }
+ verifyRuntimeReceipts(admission, receipts, phase)
+}
+
+// In-container only: prove the sealed binary really is the pinned artifact.
+export function verifySealedArtifacts(admission) {
+ const artifact = admission.thirdPartyArtifacts?.[0]
+ if (!artifact) refuse('THIRD_PARTY_ARTIFACT_REQUIRED')
+ const stat = fs.lstatSync('/usr/local/bin/sfw')
+ if (!stat.isFile() || stat.isSymbolicLink()) refuse('THIRD_PARTY_ARTIFACT_CHANGED')
+ verifyThirdPartyArtifact({
+ bytes: fs.readFileSync('/usr/local/bin/sfw'),
+ asset: {
+ sha256: artifact.sha256,
+ bytes: artifact.bytes,
+ arch: artifact.arch,
+ machine: artifact.elfMachine,
+ },
+ })
+}
+
+export function verifySourceManifest(manifest, repoRoot) {
+ if (
+ manifest.kind !== 'evenfire-subscription-image-source-v1' ||
+ !/^[a-f0-9]{40}$/.test(manifest.gitHead) ||
+ !/^[a-f0-9]{40}$/.test(manifest.gitTree) ||
+ !/^[a-f0-9]{64}$/.test(manifest.inputManifestSha256) ||
+ !Array.isArray(manifest.files) ||
+ !manifest.files.length ||
+ manifest.files.length > 20_000
+ )
+ refuse('SOURCE_MANIFEST_REQUIRED')
+ const seen = new Set()
+ for (const file of manifest.files) {
+ if (
+ typeof file.path !== 'string' ||
+ path.isAbsolute(file.path) ||
+ file.path.split('/').includes('..') ||
+ seen.has(file.path) ||
+ !/^[a-f0-9]{64}$/.test(file.sha256) ||
+ !Number.isSafeInteger(file.bytes) ||
+ file.bytes < 0 ||
+ /(^|\/)(\.env(?:\..*)?|\.ssh|\.aws|\.gnupg|cookies?[^/]*|[^/]*credential[^/]*|[^/]*wallet[^/]*|[^/]*keystore[^/]*)($|\/)|\.(pem|key|log)$/i.test(
+ file.path
+ )
+ )
+ refuse('SOURCE_PATH_OR_IDENTITY')
+ seen.add(file.path)
+ const filename = path.resolve(repoRoot, file.path),
+ stat = fs.lstatSync(filename)
+ if (
+ !stat.isFile() ||
+ stat.isSymbolicLink() ||
+ fs.realpathSync(filename) !== filename ||
+ stat.size !== file.bytes ||
+ digest(fs.readFileSync(filename)) !== file.sha256
+ )
+ refuse('SOURCE_ARTIFACT_CHANGED')
+ }
+ for (const required of [
+ 'desktop-app/dist/main.js',
+ 'desktop-app/ui-dist/index.html',
+ 'desktop-app/package-lock.json',
+ 'mcp-host/package-lock.json',
+ 'desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts',
+ 'desktop-app/test/e2e-playwright/subscriptionImageRunContract.ts',
+ 'desktop-app/test/e2e-playwright/subscription-image-input.spec.ts',
+ 'desktop-app/test/e2e-playwright/playwright.subscription-image.config.ts',
+ 'scripts/e2e/fixtures/subscription-image-challenge.cjs',
+ 'scripts/e2e/fixtures/subscription-image-session.mjs',
+ 'scripts/e2e/fixtures/subscription-image-runner.base-image',
+ ]) {
+ if (!seen.has(required)) refuse('SOURCE_REQUIRED_ARTIFACT_MISSING')
+ }
+}
diff --git a/scripts/tests/lib/subscription-image-source-context.mjs b/scripts/tests/lib/subscription-image-source-context.mjs
new file mode 100644
index 000000000..7e6c222c3
--- /dev/null
+++ b/scripts/tests/lib/subscription-image-source-context.mjs
@@ -0,0 +1,217 @@
+// A source-only exporter. It reads one clean, real Git commit, scans its exact
+// allowlisted bytes locally, then stages a minimal Docker context. No Git repo,
+// environment file, runtime config, credential, or ignored file is copied.
+import { execFileSync, spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import path from 'node:path'
+import { pathToFileURL } from 'node:url'
+import { RunnerAdmissionError, digest } from './subscription-image-runner-contract.mjs'
+
+const refuse = code => {
+ throw new RunnerAdmissionError(code)
+}
+const fixedFiles = [
+ 'desktop-app/package.json',
+ 'desktop-app/package-lock.json',
+ 'desktop-app/tsconfig.json',
+ 'desktop-app/scripts/verify-electron-runtime.mjs',
+ 'mcp-host/package.json',
+ 'mcp-host/package-lock.json',
+ ...[
+ 'subscription-image-input.spec.ts',
+ 'playwright.subscription-image.config.ts',
+ 'subscriptionImageFixtures.ts',
+ 'subscriptionImageRunContract.ts',
+ 'subscriptionImageChallenge.ts',
+ 'codexImageChallenge.ts',
+ ].map(name => `desktop-app/test/e2e-playwright/${name}`),
+ 'scripts/e2e/run-subscription-image-journeys.mjs',
+ 'scripts/e2e/fixtures/subscription-image-runner.Dockerfile',
+ 'scripts/e2e/fixtures/subscription-image-provider.mjs',
+ 'scripts/e2e/fixtures/subscription-image-challenge.cjs',
+ 'scripts/e2e/fixtures/subscription-image-session.mjs',
+ 'scripts/e2e/fixtures/subscription-image-runner.base-image',
+ 'scripts/tests/lib/subscription-image-runner-contract.mjs',
+ 'scripts/tests/lib/subscription-image-source-context.mjs',
+]
+export function allowedSourcePath(filename, packageDirectories = []) {
+ if (
+ path.isAbsolute(filename) ||
+ filename.split('/').includes('..') ||
+ /(^|\/)(\.git|node_modules|\.env(?:\..*)?|\.ssh|\.aws|\.gnupg|[^/]*credential[^/]*|[^/]*wallet[^/]*|[^/]*keystore[^/]*|cookies?[^/]*)(\/|$)|\.(pem|key|log)$/i.test(
+ filename
+ ) ||
+ /(^|\/)(__tests__|__snapshots__)(\/|$)|\.test\./.test(filename)
+ )
+ return false
+ return (
+ fixedFiles.includes(filename) ||
+ [
+ 'desktop-app/src/',
+ 'desktop-app/ui/',
+ 'desktop-app/assets/',
+ 'desktop-app/renderer/',
+ ...packageDirectories.map(directory => `${directory}/`),
+ ].some(prefix => filename.startsWith(prefix))
+ )
+}
+
+export function verifyInputSource(manifest, contextRoot) {
+ if (
+ manifest.kind !== 'evenfire-subscription-image-input-source-v1' ||
+ !/^[a-f0-9]{40}$/.test(manifest.gitHead) ||
+ !/^[a-f0-9]{40}$/.test(manifest.gitTree) ||
+ !Array.isArray(manifest.files) ||
+ !manifest.files.length ||
+ manifest.files.length > 20_000
+ )
+ refuse('INPUT_SOURCE_IDENTITY')
+ const seen = new Set()
+ for (const row of manifest.files) {
+ if (
+ !allowedSourcePath(row.path, manifest.packageDirectories) ||
+ seen.has(row.path) ||
+ !/^[a-f0-9]{40}$/.test(row.gitBlob) ||
+ !/^[a-f0-9]{64}$/.test(row.sha256) ||
+ !Number.isSafeInteger(row.bytes) ||
+ row.bytes < 0
+ )
+ refuse('INPUT_SOURCE_PATH')
+ seen.add(row.path)
+ const filename = path.join(contextRoot, row.path),
+ stat = fs.lstatSync(filename)
+ if (
+ !stat.isFile() ||
+ stat.isSymbolicLink() ||
+ fs.realpathSync(filename) !== filename ||
+ stat.size !== row.bytes ||
+ digest(fs.readFileSync(filename)) !== row.sha256
+ )
+ refuse('INPUT_SOURCE_BYTES_CHANGED')
+ }
+ for (const filename of fixedFiles) if (!seen.has(filename)) refuse('INPUT_SOURCE_REQUIRED_FILE')
+}
+
+export function exportSourceContext(repoRoot, output, detector) {
+ repoRoot = fs.realpathSync(repoRoot)
+ if (
+ !path.isAbsolute(output) ||
+ fs.existsSync(output) ||
+ !path.isAbsolute(detector) ||
+ fs.realpathSync(detector) !== detector
+ )
+ refuse('SOURCE_EXPORT_PATH')
+ const git = (...args) =>
+ execFileSync('git', ['-C', repoRoot, ...args], {
+ maxBuffer: 64 * 1024 * 1024,
+ })
+ if (
+ git('rev-parse', '--show-toplevel').toString().trim() !== repoRoot ||
+ git('status', '--porcelain=v1', '--untracked-files=normal').length
+ )
+ refuse('SOURCE_EXPORT_REQUIRES_CLEAN_CHECKOUT')
+ const gitHead = git('rev-parse', 'HEAD').toString().trim(),
+ gitTree = git('rev-parse', 'HEAD^{tree}').toString().trim()
+ const packages = new Set(),
+ queue = ['desktop-app', 'mcp-host']
+ for (let index = 0; index < queue.length; index++) {
+ const body = JSON.parse(git('show', `${gitHead}:${queue[index]}/package.json`).toString())
+ for (const value of Object.values({
+ ...body.dependencies,
+ ...body.devDependencies,
+ ...body.optionalDependencies,
+ })) {
+ if (typeof value !== 'string' || !value.startsWith('file:')) continue
+ const directory = path.posix.normalize(path.posix.join(queue[index], value.slice(5)))
+ if (!/^packages\/[a-z0-9][a-z0-9-]*$/.test(directory)) refuse('SOURCE_PACKAGE_CLOSURE_PATH')
+ if (!packages.has(directory)) {
+ packages.add(directory)
+ queue.push(directory)
+ }
+ }
+ }
+ const directories = [...packages].sort()
+ const rows = git('ls-tree', '-r', '-z', '--full-tree', gitHead)
+ .toString()
+ .split('\0')
+ .filter(Boolean)
+ .map(row => {
+ const split = row.indexOf('\t')
+ const [mode, type, blob] = row.slice(0, split).split(' ')
+ return { mode, type, blob, path: row.slice(split + 1) }
+ })
+ .filter(row => allowedSourcePath(row.path, directories))
+ const files = []
+ // Scan before creating the destination. A RED refusal never leaves an
+ // export with sensitive source, and never retries another transport.
+ const scan =
+ "import runpy,sys; s=runpy.run_path(sys.argv[1]); raw=sys.stdin.buffer.read().decode('utf-8',errors='replace'); sys.exit(91 if s['is_red'](raw) else 0)"
+ for (const row of rows) {
+ if (row.type !== 'blob' || !['100644', '100755'].includes(row.mode))
+ refuse('SOURCE_EXPORT_SYMLINK_OR_SPECIAL')
+ const bytes = git('cat-file', 'blob', row.blob)
+ const checked = spawnSync('python3', ['-c', scan, detector], {
+ input: bytes,
+ timeout: 10_000,
+ stdio: ['pipe', 'ignore', 'ignore'],
+ })
+ if (checked.error || checked.status !== 0) refuse('SOURCE_CONTENT_SCAN_REFUSED')
+ files.push({
+ path: row.path,
+ gitBlob: row.blob,
+ sha256: digest(bytes),
+ bytes: bytes.length,
+ executable: row.mode === '100755',
+ })
+ }
+ if (
+ git('rev-parse', 'HEAD').toString().trim() !== gitHead ||
+ git('status', '--porcelain=v1', '--untracked-files=normal').length
+ )
+ refuse('SOURCE_CHANGED_DURING_EXPORT')
+ fs.mkdirSync(output, { mode: 0o700 })
+ for (const row of files) {
+ const bytes = git('cat-file', 'blob', row.gitBlob)
+ if (digest(bytes) !== row.sha256) refuse('SOURCE_BLOB_CHANGED')
+ const filename = path.join(output, row.path)
+ fs.mkdirSync(path.dirname(filename), { recursive: true, mode: 0o700 })
+ fs.writeFileSync(filename, bytes, {
+ flag: 'wx',
+ mode: row.executable ? 0o700 : 0o600,
+ })
+ }
+ const manifest = {
+ kind: 'evenfire-subscription-image-input-source-v1',
+ gitHead,
+ gitTree,
+ packageDirectories: directories,
+ files,
+ }
+ verifyInputSource(manifest, output)
+ fs.writeFileSync(
+ path.join(output, 'subscription-image-input-source.json'),
+ JSON.stringify(manifest),
+ { flag: 'wx', mode: 0o600 }
+ )
+ return {
+ gitHead,
+ gitTree,
+ fileCount: files.length,
+ inputManifestSha256: digest(JSON.stringify(manifest)),
+ }
+}
+
+if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
+ try {
+ if (process.argv.length !== 5) refuse('SOURCE_EXPORT_ARGUMENTS')
+ console.log(JSON.stringify(exportSourceContext(...process.argv.slice(2))))
+ } catch (err) {
+ console.error(
+ JSON.stringify({
+ kind: 'source-export-refused',
+ code: err instanceof RunnerAdmissionError ? err.code : 'SOURCE_EXPORT_FAILED',
+ })
+ )
+ process.exitCode = 1
+ }
+}
diff --git a/scripts/tests/measure-control-api-authorize-memory.mjs b/scripts/tests/measure-control-api-authorize-memory.mjs
new file mode 100644
index 000000000..59354ab9f
--- /dev/null
+++ b/scripts/tests/measure-control-api-authorize-memory.mjs
@@ -0,0 +1,279 @@
+#!/usr/bin/env node
+/** Experimental real Control API HTTP/PG/cgroup calibration. A complete receipt is not activation authorization. */
+import fs from 'node:fs'
+import path from 'node:path'
+import { spawn } from 'node:child_process'
+import { fileURLToPath } from 'node:url'
+import { stripTypeScriptTypes } from 'node:module'
+import { createHash } from 'node:crypto'
+import { buildAuthorizeFixture, buildRejectedFixture, buildGfsFixture, SHAPES, MIB, sha256 } from './lib/control-api-authorize-memory-fixtures.mjs'
+const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+const NAMESPACE = 'control-plane', DEPLOYMENT = 'control-api', CONTAINER = 'control-api'
+const sleepPoll = ms => new Promise(resolve => setTimeout(resolve, ms))
+const assert = (condition, code) => { if (!condition) throw new Error(code) }
+const uuid = value => /^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value)
+export function parseOptions(args, env = process.env) {
+ const fields = {}, flags = new Set(['inspect-plan', 'include-legacy-gfs'])
+ for (let index = 0; index < args.length; index++) {
+ const key = args[index]; assert(/^--[a-z-]+$/.test(key), 'INVALID_ARGUMENT')
+ const name = key.slice(2); assert(!(name in fields), 'DUPLICATE_ARGUMENT')
+ if (flags.has(name)) fields[name] = true
+ else { assert(args[index + 1] && !args[index + 1].startsWith('--'), 'MISSING_ARGUMENT_VALUE'); fields[name] = args[++index] }
+ }
+ const allowed = ['config', 'profile', 'context', 'run-id', 'host-namespace', 'budget-ids', 'gfs-parent-rid', 'operator-user', 'heap-size-mib', 'concurrency', 'read-deadline-ms', 'work-deadline-ms', 'close-grace-ms', 'runs', 'cgroup-limit-mib', 'shape', 'report', 'prepare', 'inspector-port', ...flags]
+ for (const key of Object.keys(fields)) assert(allowed.includes(key), 'UNKNOWN_ARGUMENT')
+ if (fields.config) {
+ assert(Object.keys(fields).every(key => key === 'config' || flags.has(key)), 'CONFIG_ARGUMENT_CONFLICT')
+ const stat = fs.lstatSync(fields.config); assert(stat.isFile() && !stat.isSymbolicLink() && stat.uid === process.getuid?.() && !(stat.mode & 0o077) && stat.size < 32768, 'CONFIG_NOT_PRIVATE_OWNED')
+ const input = JSON.parse(fs.readFileSync(fields.config, 'utf8'))
+ assert(input.kind === 'control-api-authorize-memory-config.v1', 'CONFIG_KIND_INVALID')
+ const converted = []
+ for (const [key, value] of Object.entries(input.arguments)) { assert(allowed.includes(key) && key !== 'config', 'CONFIG_FIELD_INVALID'); converted.push(`--${key}`); if (!flags.has(key)) converted.push(String(value)); else assert(value === true, 'CONFIG_FLAG_INVALID') }
+ if (fields['inspect-plan'] && !converted.includes('--inspect-plan')) converted.push('--inspect-plan')
+ return parseOptions(converted, env)
+ }
+ const string = (key, value = fields[key]) => { assert(typeof value === 'string' && value.trim() === value && value.length > 0, `REQUIRED_${key.toUpperCase().replaceAll('-', '_')}`); return value }
+ const integer = (key, min, max) => { const raw = string(key); assert(/^\d+$/.test(raw), 'INTEGER_ARGUMENT_INVALID'); const n = Number(raw); assert(Number.isSafeInteger(n) && n >= min && n <= max, 'INTEGER_ARGUMENT_OUT_OF_RANGE'); return n }
+ const profile = string('profile', fields.profile ?? env.MINIKUBE_PROFILE), context = string('context', fields.context ?? env.CONTROL_API_REAL_PG_CONTEXT)
+ assert(profile === context && /^[a-z0-9][a-z0-9-]{0,62}$/.test(profile) && profile !== 'clerum-test' && !/(^|[-_])(prod|production)([-_]|$)/i.test(profile), 'OWNED_DEVELOPMENT_CONTEXT_REQUIRED')
+ const runId = string('run-id'); assert(/^pr806-memory-[a-f0-9]{12}$/.test(runId), 'RUN_ID_INVALID')
+ const hostNamespace = string('host-namespace'); assert(/^[a-z0-9][a-z0-9-]{0,62}$/.test(hostNamespace), 'HOST_NAMESPACE_INVALID')
+ const budgets = string('budget-ids').split(','); assert(budgets.length === 2 && budgets.every(uuid), 'TWO_OWNED_BUDGET_IDS_REQUIRED')
+ const parentRid = string('gfs-parent-rid'); assert(/^[a-f0-9]{32}$/.test(parentRid) || uuid(parentRid), 'GFS_PARENT_RID_INVALID')
+ const shapes = string('shape').split(','); assert(new Set(shapes).size === shapes.length && shapes.every(value => SHAPES.includes(value)) && ['visual-35mib', 'worst-structure', 'wide-strings'].every(value => shapes.includes(value)), 'REPRESENTATIVE_SHAPES_REQUIRED')
+ const report = string('report'); assert(path.isAbsolute(report) && path.extname(report) === '.json', 'ABSOLUTE_JSON_REPORT_REQUIRED')
+ const prepare = string('prepare'); assert(['restart', 'build'].includes(prepare), 'PREPARE_MODE_INVALID')
+ assert(fields['include-legacy-gfs'] === true, 'LEGACY_GFS_REQUIRED')
+ const options = { profile, context, runId, hostNamespace, budgets, parentRid, shapes, report: path.resolve(report), prepare,
+ operatorUser: string('operator-user'), inspectorPort: integer('inspector-port', 1024, 65535), runs: integer('runs', 3, 3), cgroupLimitMiB: integer('cgroup-limit-mib', 768, 768), inspectPlan: fields['inspect-plan'] === true,
+ candidate: { heapSizeMiB: integer('heap-size-mib', 64, 512), concurrency: integer('concurrency', 1, 4), readDeadlineMs: integer('read-deadline-ms', 100, 60000), workDeadlineMs: integer('work-deadline-ms', 100, 120000), closeGraceMs: integer('close-grace-ms', 1, 10000) }, publicArguments: fields }
+ assert(options.candidate.closeGraceMs < options.candidate.readDeadlineMs, 'CLOCK_ARGUMENT_RELATION_INVALID')
+ return options
+}
+async function command(binary, args, { env = process.env, timeoutMs = 180000, maxBytes = 2 * MIB } = {}) {
+ return new Promise((resolve, reject) => {
+ const child = spawn(binary, args, { cwd: ROOT, env, stdio: ['ignore', 'pipe', 'pipe'] })
+ const chunks = []; let size = 0, timedOut = false
+ child.stderr.resume()
+ const timer = setTimeout(() => { timedOut = true; child.kill('SIGTERM'); setTimeout(() => child.kill('SIGKILL'), 1000).unref() }, timeoutMs)
+ child.stdout.on('data', data => { size += data.length; if (size > maxBytes) child.kill('SIGKILL'); else chunks.push(data) })
+ child.once('error', () => { clearTimeout(timer); reject(new Error('COMMAND_START_FAILED')) })
+ child.once('close', (code, signal) => { clearTimeout(timer); if (code !== 0 || timedOut || size > maxBytes) reject(new Error(`COMMAND_FAILED_${binary.toUpperCase()}_${code ?? 'SIGNAL'}`)); else resolve(Buffer.concat(chunks).toString()) })
+ })
+}
+export function buildAuthorizeMemoryCompanionBundle() {
+ const dir = path.join(ROOT, 'scripts/tests/lib')
+ const inspector = fs.readFileSync(path.join(dir, 'control-api-authorize-memory-inspector.mjs'), 'utf8').replace(/^export /gm, '')
+ const source = fs.readFileSync(path.join(dir, 'control-api-authorize-memory-companion.ts'), 'utf8').replace(/^import .* from '\.\/control-api-authorize-memory-inspector\.mjs'\n/m, '')
+ const companion = stripTypeScriptTypes(source).replace(/^export /gm, '')
+ return `${inspector}\n${companion}\nawait runCompanion()\n`
+}
+export class Channel {
+ constructor(child, timeoutMs) {
+ this.child = child; this.timeoutMs = timeoutMs; this.pending = new Map(); this.responses = new Map(); this.next = 1; this.buffer = ''; this.exit = undefined
+ child.stderr.resume(); child.stdout.setEncoding('utf8'); child.stdin.on('error', () => this.fail())
+ child.stdout.on('data', chunk => {
+ this.buffer += chunk
+ if (this.buffer.length > 256 * 1024) { this.fail(); return }
+ for (;;) { const newline = this.buffer.indexOf('\n'); if (newline < 0) break; const line = this.buffer.slice(0, newline); this.buffer = this.buffer.slice(newline + 1)
+ let message; try { message = JSON.parse(line) } catch { this.fail(); return }
+ if (message.fatal) { this.fail(); return }
+ const map = message.event === 'response' ? this.responses : this.pending, id = message.event === 'response' ? message.requestId : message.callId
+ const item = map.get(id); if (!item) continue; map.delete(id); clearTimeout(item.timer)
+ if (message.failed || message.data?.failed) item.reject(new Error('REAL_COMPANION_COMMAND_FAILED')); else item.resolve(message.data)
+ }
+ })
+ this.closed = new Promise(resolve => child.once('close', (code, signal) => { this.exit = { code, signal }; this.fail(); resolve(this.exit) }))
+ child.once('error', () => this.fail())
+ }
+ fail() { for (const map of [this.pending, this.responses]) { for (const item of map.values()) { clearTimeout(item.timer); item.reject(new Error('COMPANION_PRODUCER_FAILED')) }; map.clear() } }
+ deferred(map, id, timeout = this.timeoutMs) { return new Promise((resolve, reject) => { const timer = setTimeout(() => { map.delete(id); reject(new Error('COMPANION_DEADLINE')) }, timeout); map.set(id, { resolve, reject, timer }) }) }
+ async call(input, bytes) {
+ const callId = String(this.next++), reply = this.deferred(this.pending, callId); reply.catch(() => {})
+ const header = Buffer.from(JSON.stringify({ ...input, callId }) + '\n')
+ const packet = bytes ? Buffer.concat([header, bytes]) : header
+ const writing = new Promise((resolve, reject) => this.child.stdin.write(packet, error => error ? reject(new Error('COMPANION_INPUT_FAILED')) : resolve()))
+ await Promise.race([writing, reply.then(() => undefined)])
+ return reply
+ }
+ async open(input) { const result = this.deferred(this.responses, input.requestId); result.catch(() => {}); await this.call({ ...input, kind: 'open' }); return { requestId: input.requestId, result } }
+ async body(handle, bytes) { for (let offset = 0; offset < bytes.length; offset += 65536) { const chunk = bytes.subarray(offset, offset + 65536); await this.call({ kind: 'write', requestId: handle.requestId, length: chunk.length }, chunk) }; await this.call({ kind: 'end', requestId: handle.requestId }) }
+ async stop() { this.child.stdin.end(); const timer = setTimeout(() => { this.child.kill('SIGTERM'); setTimeout(() => this.child.kill('SIGKILL'), 1000).unref() }, 10000); const exit = await this.closed; clearTimeout(timer); assert(exit.code === 0 && !exit.signal, 'COMPANION_EXIT_NOT_ZERO'); return exit }
+}
+async function waitFor(check, predicate, timeoutMs, code) { const deadline = Date.now() + timeoutMs; while (Date.now() < deadline) { const value = await check(); if (predicate(value)) return value; await sleepPoll(25) }; throw new Error(code) }
+export function validateReceipt(report) {
+ assert(/^[a-f0-9]{40}$/.test(report.source?.head ?? '') && /^[a-f0-9]{64}$/.test(report.source?.policySha256 ?? '') && Number.isFinite(Date.parse(report.startedAt)) && Date.parse(report.finishedAt) >= Date.parse(report.startedAt), 'SOURCE_OR_REPORT_WINDOW_MISSING')
+ assert(report.status === 'complete' && report.runs.length === 3 && report.restoration?.verified === true && report.restoration.healthStatus === 200, 'INCOMPLETE_REPORT')
+ assert(new Set(report.runs.map(run => run.podUid)).size === 3 && new Set(report.runs.map(run => run.containerId)).size === 3, 'CGROUP_WINDOWS_REUSED')
+ for (const run of report.runs) {
+ assert(run.phase === 'complete' && Number.isFinite(Date.parse(run.startedAt)) && Date.parse(run.finishedAt) >= Date.parse(run.startedAt) && /^[a-f0-9]{64}$/.test(run.baseline?.compiledPolicySha256 ?? '') && run.baseline.server.applicationProcesses === 1 && run.baseline.server.nodeProcessesIncludingAuxiliary === 2 && /^24\./.test(run.baseline.server.nodeVersion), 'RUN_SOURCE_PROCESS_OR_WINDOW_MISSING')
+ assert(run.producer?.code === 0 && run.cleanup?.ownedGfsRemaining === 0, 'PRODUCER_OR_CLEANUP_INCOMPLETE')
+ const expectedIssued = 2 + report.options.shapes.length * 2 * report.options.candidate.concurrency
+ assert(run.warmup?.status === 200 && run.warmup.durableRowVerified === true && run.warmup.reservationVerified === true && run.warmup.reservationAmount === 200 && run.cleanup.lifecycle === 'pg-issued-expiry-before-host-release' && run.cleanup.releaseEndpoint === '/api/v1/internal/budgets/release' &&
+ run.warmupRelease?.lifecycle === 'pg-issued-expiry-before-host-release' && run.combined.every(phase => phase.cleanup?.lifecycle === 'pg-issued-expiry-before-host-release' && phase.cleanup.liveIssuedTickets === 0 && phase.cleanup.reservationRows === 0) && run.cleanup.total === expectedIssued && run.cleanup.retainedAuthorizedAuditRows === expectedIssued && run.cleanup.tickets === expectedIssued && run.cleanup.expiredIssuedTickets === expectedIssued && run.cleanup.liveIssuedTickets === 0 &&
+ run.cleanup.redeemedAuditRows === 0 && run.cleanup.finalizedAuditRows === 0 && run.cleanup.redeemedTickets === 0 && run.cleanup.finalizedTickets === 0 && run.cleanup.reservationRows === 0 && run.cleanup.activeReservations === 0 && run.cleanup.executionTicketExpiryRemainingMs === 0 &&
+ Number.isSafeInteger(run.baseline.executionTicketTtlMs) && run.baseline.executionTicketTtlMs > 0 && run.baseline.executionTicketTtlMs <= 120000 && Date.parse(run.cleanup.observedAt) >= Date.parse(run.startedAt) && Date.parse(run.cleanup.observedAt) <= Date.parse(run.finishedAt), 'ISSUED_TICKET_LIFECYCLE_INCOMPLETE')
+ assert(run.gc?.gc?.forced === true && run.gc.gc.kind === 'native-HeapProfiler.collectGarbage' && run.gc.gc.before.pid === run.gc.gc.after.pid && run.gc.gc.after.at >= run.gc.gc.before.at, 'FORCED_GC_UNKNOWN')
+ assert(run.causality?.excess?.status === 503 && run.causality.excess.acceptedWriteBytes === 0 && run.causality.coverage.parser === 0 && run.causality.coverage.authorizer === 0, 'PRE_PARSE_PROOF_MISSING')
+ assert(run.samples.length >= 2 && run.baseline.cgroup.events.oom === 0 && run.baseline.cgroup.events.oom_kill === 0 && run.samples.every(sample => sample.server.applicationProcesses === 1 && sample.server.nodeProcessesIncludingAuxiliary === 2 && sample.cgroup.limit === 768 * MIB && sample.cgroup.peak * 1.25 <= sample.cgroup.limit && sample.cgroup.events.oom === run.baseline.cgroup.events.oom && sample.cgroup.events.oom_kill === run.baseline.cgroup.events.oom_kill), 'CGROUP_MARGIN_OR_OOM_FAILED')
+ assert(run.combined.length === report.options.shapes.length * 2 && run.combined.every(phase => phase.authorizes.length === report.options.candidate.concurrency && phase.authorizes.every(row => row.status === 200 && row.durableRowVerified === true && row.reservationVerified === true && row.reservationAmount === 200) && phase.gfs.length === phase.gfsConcurrency && phase.gfs.every(row => row.status === 201 && row.verifiedDigest === row.expectedDigest)), 'COMBINED_WORKLOAD_INCOMPLETE')
+ assert(run.rejected.length === 2 && run.rejected.every(row => row.status === 413) && run.recovery?.status === 200 && run.health?.status === 200 && run.stalled?.status === 408 && run.closedTransaction?.physicallyQuiesced === true, 'LIFECYCLE_CONTROL_INCOMPLETE')
+ }
+ return true
+}
+async function run(options) {
+ const env = { ...process.env, MINIKUBE_PROFILE: options.profile, CONTROL_API_REAL_PG_CONTEXT: options.context }
+ const kc = args => command('kubectl', ['--context', options.context, ...args], { env, timeoutMs: args.includes('rollout') ? 150000 : 15000 })
+ const json = async args => JSON.parse(await kc(args))
+ const head = (await command('git', ['rev-parse', 'HEAD'])).trim()
+ assert((await command('git', ['status', '--porcelain'])).trim() === '', 'CLEAN_SOURCE_REQUIRED')
+ await command('bash', ['scripts/minikube/require-t2-mutation-lock.sh'], { env: { ...env, T2_PROJECT_DIR: ROOT, T2_PROFILE: options.profile, T2_CONTEXT: options.context, T2_SKIP_LOCK: 'true' }, timeoutMs: 10000 })
+ if (options.prepare === 'build') {
+ await command('make', ['--no-print-directory', 'minikube-deploy-service', 'SVC=control-api', 'NS=control-plane', 'DEPLOYMENT=control-api'], { env, timeoutMs: 300000 })
+ await command('make', ['--no-print-directory', 'minikube-pre-gate-sync'], { env, timeoutMs: 600000 })
+ }
+ const marker = (await json(['-n', NAMESPACE, 'get', 'configmap', 'clerum-pre-gate-sync-state', '-o', 'json'])).data
+ const worktreeId = (await command('bash', ['-c', 'source scripts/minikube/t2-worktree-id.sh\nt2_worktree_id "$1"', 'memory-worktree-id', ROOT])).trim(); assert(worktreeId, 'CANONICAL_WORKTREE_ID_MISSING')
+ const manifest = JSON.parse(fs.readFileSync(path.join(ROOT, 'deploy/minikube/.image-manifest.json'), 'utf8'))
+ assert(marker.gitHead === head && marker.worktreeId === worktreeId && marker.clusterFingerprint && marker.imagesGeneratedAt === manifest.generated && manifest.profile === options.profile, 'EXACT_SOURCE_IMAGE_MARKER_REQUIRED')
+ await command('bash', ['scripts/minikube/require-t2-mutation-lock.sh'], { env: { ...env, T2_PROJECT_DIR: ROOT, T2_PROFILE: options.profile, T2_CONTEXT: options.context, T2_SKIP_LOCK: 'true' }, timeoutMs: 10000 })
+ const common = (await command('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'])).trim(), canonical = path.dirname(common)
+ const allowedReports = path.join(canonical, '.local-notes/infra/runs')
+ assert(options.report.startsWith(allowedReports + path.sep) && !fs.existsSync(options.report), 'FRESH_CANONICAL_REPORT_REQUIRED')
+ fs.mkdirSync(path.dirname(options.report), { recursive: true, mode: 0o700 }); assert(fs.realpathSync(path.dirname(options.report)) === path.dirname(options.report), 'REPORT_PARENT_SYMLINK')
+ const report = { kind: 'control-api-authorize-memory.v1', status: 'running', startedAt: new Date().toISOString(), source: { head, worktreeId, policySha256: sha256(fs.readFileSync(path.join(ROOT, 'control-api/src/middleware/llmProviderAttemptAdmissionLimits.ts'))), driverSha256: sha256(fs.readFileSync(fileURLToPath(import.meta.url))), companionBundleSha256: sha256(buildAuthorizeMemoryCompanionBundle()), clusterFingerprint: marker.clusterFingerprint, imagesGeneratedAt: manifest.generated }, options, runs: [], restoration: { verified: false } }
+ const save = () => { const temporary = options.report + '.next'; fs.writeFileSync(temporary, JSON.stringify(report, null, 2), { flag: 'wx', mode: 0o600 }); fs.renameSync(temporary, options.report) }
+ const deployment = await json(['-n', NAMESPACE, 'get', 'deployment', DEPLOYMENT, '-o', 'json'])
+ assert(deployment.spec.replicas === 1, 'SINGLE_APP_REPLICA_REQUIRED')
+ const ci = deployment.spec.template.spec.containers.findIndex(container => container.name === CONTAINER)
+ assert(ci >= 0 && !deployment.spec.template.spec.hostNetwork, 'OWNED_CONTAINER_REQUIRED')
+ const original = deployment.spec.template.spec.containers[ci].env?.find(item => item.name === 'NODE_OPTIONS')
+ assert(!original?.valueFrom && (!original || /^--max-old-space-size=\d+$/.test(original.value)), 'ORIGINAL_NODE_OPTIONS_UNSUPPORTED')
+ const candidateValue = `--max-old-space-size=${options.candidate.heapSizeMiB} --inspect=127.0.0.1:${options.inspectorPort}`
+ const mutateOptions = async restore => {
+ const current = await json(['-n', NAMESPACE, 'get', 'deployment', DEPLOYMENT, '-o', 'json']); assert(current.metadata.uid === deployment.metadata.uid, 'DEPLOYMENT_OWNER_CHANGED')
+ const containers = current.spec.template.spec.containers, index = containers.findIndex(container => container.name === CONTAINER), values = containers[index].env ?? [], ei = values.findIndex(item => item.name === 'NODE_OPTIONS')
+ const base = `/spec/template/spec/containers/${index}/env`, patch = [{ op: 'test', path: '/metadata/uid', value: current.metadata.uid }, { op: 'test', path: '/metadata/resourceVersion', value: current.metadata.resourceVersion }]
+ if (restore && JSON.stringify(ei >= 0 ? values[ei] : undefined) === JSON.stringify(original)) return
+ if (restore) { assert(ei >= 0 && values[ei].value === candidateValue, 'RUNTIME_OPTION_OWNER_CHANGED'); patch.push({ op: 'test', path: `${base}/${ei}`, value: values[ei] }, ...(original ? [{ op: 'replace', path: `${base}/${ei}`, value: original }] : [{ op: 'remove', path: `${base}/${ei}` }])) }
+ else { if (!containers[index].env) patch.push({ op: 'add', path: base, value: [] }); if (ei >= 0) patch.push({ op: 'test', path: `${base}/${ei}`, value: values[ei] }); patch.push({ op: ei >= 0 ? 'replace' : 'add', path: ei >= 0 ? `${base}/${ei}` : `${base}/-`, value: { name: 'NODE_OPTIONS', value: candidateValue } }) }
+ await kc(['-n', NAMESPACE, 'patch', 'deployment', DEPLOYMENT, '--type=json', '--patch', JSON.stringify(patch)])
+ await kc(['-n', NAMESPACE, 'rollout', 'status', `deployment/${DEPLOYMENT}`, '--timeout=120s'])
+ }
+ let patched = false
+ try {
+ patched = true; await mutateOptions(false)
+ for (let index = 0; index < 3; index++) {
+ await command('make', ['--no-print-directory', 'minikube-restart-deploy', 'SVC=control-api', 'NS=control-plane', 'DEPLOYMENT=control-api'], { env, timeoutMs: 300000 })
+ const pods = (await json(['-n', NAMESPACE, 'get', 'pods', '-l', 'app=control-api', '-o', 'json'])).items.filter(pod => !pod.metadata.deletionTimestamp && pod.status.phase === 'Running' && pod.status.containerStatuses?.find(value => value.name === CONTAINER)?.ready)
+ assert(pods.length === 1 && pods[0].metadata.ownerReferences?.some(owner => owner.kind === 'ReplicaSet'), 'READY_POD_AMBIGUOUS')
+ const pod = pods[0], container = pod.status.containerStatuses.find(value => value.name === CONTAINER), spec = pod.spec.containers.find(value => value.name === CONTAINER)
+ assert(container.restartCount === 0, 'UNOBSERVED_PRIOR_CONTAINER_RESTART')
+ const replica = pod.metadata.ownerReferences.find(owner => owner.kind === 'ReplicaSet' && owner.controller === true)
+ const replicaSet = await json(['-n', NAMESPACE, 'get', 'replicaset', replica.name, '-o', 'json'])
+ assert(replicaSet.metadata.ownerReferences?.some(owner => owner.kind === 'Deployment' && owner.uid === deployment.metadata.uid && owner.controller === true), 'POD_DEPLOYMENT_OWNER_CHANGED')
+ assert(!spec.ports?.some(port => port.hostPort || port.containerPort === options.inspectorPort) && !pod.spec.hostNetwork && spec.resources?.limits?.memory === '768Mi', 'CGROUP_OR_INSPECTOR_BOUNDARY_INVALID')
+ const actualImageId = container.imageID.match(/sha256:[a-f0-9]{64}$/)?.[0], expectedImageId = manifest.images[spec.image] ?? manifest.images[`docker.io/${spec.image}`]
+ assert(actualImageId && actualImageId === expectedImageId && manifest.sourceRevisions?.[spec.image] === head, 'ACTUAL_IMAGE_SOURCE_MISMATCH')
+ assert(!report.runs.some(run => run.podUid === pod.metadata.uid || run.containerId === container.containerID), 'CGROUP_WINDOW_NOT_FRESH')
+ const bindings = []
+ for (const [hi, hostRef] of ['pr806-memory-grok-host', 'pr806-memory-grok-host-2'].entries()) {
+ const host = await json(['-n', options.hostNamespace, 'get', 'host', hostRef, '-o', 'json'])
+ assert(host.spec.model?.provider === 'grok-subscription' && host.spec.model.connectionRef?.includes(options.runId), 'HOST_ASSIGNMENT_NOT_OWNED')
+ bindings.push({ hostRef, hostUid: host.metadata.uid, connectionKey: host.spec.model.connectionRef, budgetId: options.budgets[hi] })
+ }
+ const child = spawn('kubectl', ['--context', options.context, '-n', NAMESPACE, 'exec', '-i', pod.metadata.name, '-c', CONTAINER, '--', 'env', '-u', 'NODE_OPTIONS', 'node', '--max-old-space-size=64', '--input-type=module', '-e', buildAuthorizeMemoryCompanionBundle()], { cwd: ROOT, env, stdio: ['pipe', 'pipe', 'pipe'] })
+ const channel = new Channel(child, options.candidate.readDeadlineMs + options.candidate.workDeadlineMs + 10000)
+ const row = { number: index + 1, podUid: pod.metadata.uid, containerId: container.containerID, imageId: actualImageId, image: spec.image, startedAt: new Date().toISOString(), phase: 'hello', samples: [], combined: [], rejected: [] }; report.runs.push(row); save()
+ const trialId = `pr806-memory-${sha256(options.runId + index).slice(0, 12)}`
+ let sequence = 0, sampling = false
+ const requestFixture = (shape, binding, small = false) => buildAuthorizeFixture({ shape, binding, invocationId: `${trialId}-${++sequence}`, small })
+ const execute = async (fixture, binding) => { const handle = await channel.open({ requestId: fixture.envelope.invocationId, route: 'authorize', hostRef: binding.hostRef, length: fixture.bytes.length }); await channel.body(handle, fixture.bytes); const response = await handle.result; assert(response.status === 200 && response.durableRowVerified === true && response.reservationVerified === true && response.reservationAmount === 200 && uuid(response.providerAttemptId) && response.requestHash === fixture.metadata.requestHash, 'REAL_AUTHORIZE_FAILED'); return { ...response, fixture: fixture.metadata } }
+ const settleIssued = async () => {
+ const ttl = row.baseline.executionTicketTtlMs
+ assert(Number.isSafeInteger(ttl) && ttl > 0 && ttl <= 120000, 'ACTUAL_TICKET_TTL_UNKNOWN')
+ // Query actual database time. No reservation is released while any owned
+ // issued ticket can still be redeemed, and no audit outcome is invented.
+ const observed = await waitFor(() => channel.call({ kind: 'counts' }), value => value.liveIssuedTickets === 0 && value.executionTicketExpiryRemainingMs === 0, ttl + 5000, 'ISSUED_TICKET_EXPIRY_UNOBSERVED')
+ const released = await channel.call({ kind: 'cleanup' })
+ assert(released.lifecycle === 'pg-issued-expiry-before-host-release' && released.liveIssuedTickets === 0 && released.reservationRows === 0, 'STRICT_ISSUED_CLEANUP_FAILED')
+ return { ...released, expiryObservedAt: observed.observedAt }
+ }
+ const sample = async () => { const value = await channel.call({ kind: 'sample' }); row.samples.push(value); assert(value.cgroup.peak * 1.25 <= value.cgroup.limit && value.cgroup.events.oom === row.baseline.cgroup.events.oom && value.cgroup.events.oom_kill === row.baseline.cgroup.events.oom_kill, 'MEMORY_MARGIN_OR_OOM_FAILED'); return value }
+ try {
+ const credentials = { cookie: process.env.E2E_ADMIN_TOKEN, operatorPassword: process.env.CONTROL_API_MEMORY_OPERATOR_PASSWORD }
+ row.baseline = await channel.call({ kind: 'hello', options: { candidate: options.candidate, inspectorPort: options.inspectorPort, runId: trialId, hostNamespace: options.hostNamespace, fixtureRunId: options.runId, bindings, operatorUser: options.operatorUser, ...credentials, gfsParentRid: options.parentRid } })
+ row.bindings = row.baseline.bindings
+ assert(row.baseline.server.applicationProcesses === 1 && row.baseline.server.nodeProcessesIncludingAuxiliary === 2 && row.baseline.cgroup.events.oom === 0 && row.baseline.cgroup.events.oom_kill === 0 && row.baseline.auxiliary.inputHighWaterMark <= 65536, 'CLIENT_RETAINER_BOUND_INVALID')
+ row.warmup = await execute(requestFixture('visual-35mib', row.bindings[0], true), row.bindings[0])
+ // No dispatch occurs in this benchmark. The real Host release endpoint
+ // frees the known reservation; authorized/issued audit rows are retained.
+ row.warmupRelease = await settleIssued()
+ row.phase = 'pre-parse-saturation'; await channel.call({ kind: 'coverage-start' })
+ const held = []
+ for (let n = 0; n < options.candidate.concurrency; n++) { const fixture = requestFixture('visual-35mib', row.bindings[n % 2]); held.push(await channel.open({ requestId: fixture.envelope.invocationId, route: 'authorize', hostRef: row.bindings[n % 2].hostRef, length: fixture.bytes.length })) }
+ let seen = 0; await waitFor(async () => { const coverage = await channel.call({ kind: 'coverage' }); seen += coverage.parser; return seen }, count => count >= options.candidate.concurrency, 5000, 'AUTHENTICATED_PARSER_ENTRY_UNOBSERVED')
+ const extra = await channel.open({ requestId: `${trialId}-excess`, route: 'authorize', hostRef: row.bindings[1].hostRef, length: 35 * MIB - 4096 })
+ const excess = await extra.result, coverage = await channel.call({ kind: 'coverage' })
+ assert(excess.status === 503 && excess.error === 'authorize_capacity_exceeded' && excess.acceptedWriteBytes === 0 && coverage.parser === 0 && coverage.authorizer === 0, 'PRE_PARSE_CAPACITY_PROOF_FAILED')
+ row.causality = { excess, coverage }
+ assert((await channel.call({ kind: 'counts' })).total === 1, 'EXCESS_OR_HELD_REQUEST_AUTHORIZED')
+ for (const handle of held) await channel.call({ kind: 'close', requestId: handle.requestId })
+ await channel.call({ kind: 'coverage-stop' }); await sleepPoll(100)
+ row.gc = await channel.call({ kind: 'gc' }); await sample()
+ for (const shape of options.shapes) for (const gfsConcurrency of [1, 2]) {
+ await channel.call({ kind: 'lock' })
+ row.phase = `combined-${shape}-gfs${gfsConcurrency}`
+ const phase = { shape, gfsConcurrency, authorizes: [], gfs: [] }; row.combined.push(phase)
+ const authorizes = []
+ for (let n = 0; n < options.candidate.concurrency; n++) { const binding = row.bindings[n % 2], fixture = requestFixture(shape, binding); const handle = await channel.open({ requestId: fixture.envelope.invocationId, route: 'authorize', hostRef: binding.hostRef, length: fixture.bytes.length }); await channel.body(handle, fixture.bytes); authorizes.push({ handle, fixture }) }
+ await waitFor(() => channel.call({ kind: 'waiting' }), value => value.count === options.candidate.concurrency, 5000, 'REAL_TRANSACTION_HOLD_UNOBSERVED'); await sample()
+ const gfsh = []
+ for (let n = 0; n < gfsConcurrency; n++) { const fixture = buildGfsFixture({ name: `${trialId}-${++sequence}.bin`, sequence: n + 1 }); const handle = await channel.open({ requestId: `${trialId}-gfs-${sequence}`, route: 'gfs', name: fixture.metadata.name, length: fixture.bytes.length, decodedBytes: fixture.metadata.decodedBytes }); gfsh.push({ fixture, handle }) }
+ const maxLength = Math.max(...gfsh.map(value => value.fixture.bytes.length))
+ for (let offset = 0; offset < maxLength; offset += 65536) for (const value of gfsh) { const chunk = value.fixture.bytes.subarray(offset, offset + 65536); if (chunk.length) await channel.call({ kind: 'write', requestId: value.handle.requestId, length: chunk.length }, chunk); if (!(offset % (1024 * 1024))) await sample() }
+ for (const value of gfsh) await channel.call({ kind: 'end', requestId: value.handle.requestId })
+ for (const value of gfsh) { const response = await value.handle.result; assert(response.status === 201 && response.resource?.rid, 'REAL_GFS_WRITE_FAILED'); const observed = await channel.call({ kind: 'download', rid: response.resource.rid }); assert(observed.sha256 === value.fixture.metadata.sha256 && observed.bytes === 16 * MIB, 'REAL_GFS_BYTES_MISMATCH'); phase.gfs.push({ ...response, fixture: value.fixture.metadata, verifiedDigest: observed.sha256, expectedDigest: value.fixture.metadata.sha256 }) }
+ await sample(); await channel.call({ kind: 'unlock' })
+ for (const value of authorizes) { const response = await value.handle.result; assert(response.status === 200 && response.durableRowVerified === true && response.reservationVerified === true && response.reservationAmount === 200 && uuid(response.providerAttemptId) && response.requestHash === value.fixture.metadata.requestHash, 'REAL_AUTHORIZE_FAILED'); phase.authorizes.push({ ...response, fixture: value.fixture.metadata }) }
+ phase.cleanup = await settleIssued(); await sample(); save()
+ }
+ row.phase = 'rejection-and-lifetime-controls'
+ const accepted = requestFixture('visual-35mib', row.bindings[0])
+ for (const kind of ['codex-cap', 'elements']) { const fixture = buildRejectedFixture(accepted, kind), handle = await channel.open({ requestId: `${trialId}-reject-${kind}`, route: 'authorize', hostRef: row.bindings[0].hostRef, length: fixture.bytes.length }); await channel.body(handle, fixture.bytes); const response = await handle.result; assert(response.status === 413 && response.error === 'payload_too_large', 'REAL_REJECTION_CONTROL_FAILED'); row.rejected.push({ ...response, fixture: fixture.metadata }) }
+ const stallStart = Date.now(), stalled = await channel.open({ requestId: `${trialId}-stalled`, route: 'authorize', hostRef: row.bindings[0].hostRef, length: 35 * MIB - 4096 }); row.stalled = { ...(await stalled.result), elapsedMs: Date.now() - stallStart }; assert(row.stalled.elapsedMs >= options.candidate.readDeadlineMs - 100 && row.stalled.elapsedMs <= options.candidate.readDeadlineMs + 5000 && row.stalled.status === 408, 'STALLED_READ_NOT_BOUNDED')
+ await channel.call({ kind: 'lock' }); const closing = requestFixture('visual-35mib', row.bindings[0], true), closingHandle = await channel.open({ requestId: closing.envelope.invocationId, route: 'authorize', hostRef: row.bindings[0].hostRef, length: closing.bytes.length }); await channel.body(closingHandle, closing.bytes)
+ await waitFor(() => channel.call({ kind: 'waiting' }), value => value.count >= 1, 5000, 'CLOSE_TRANSACTION_HOLD_UNOBSERVED'); await channel.call({ kind: 'close', requestId: closingHandle.requestId }); await closingHandle.result
+ await waitFor(() => channel.call({ kind: 'waiting' }), value => value.count === 0, options.candidate.workDeadlineMs + 1000, 'CLOSED_TRANSACTION_DID_NOT_UNWIND'); await channel.call({ kind: 'unlock' }); row.closedTransaction = { physicallyHeldBeforeClose: true, physicallyQuiesced: true }
+ row.recovery = await execute(requestFixture('visual-35mib', row.bindings[1], true), row.bindings[1]); row.health = await channel.call({ kind: 'health' }); assert(row.health.status === 200, 'POST_WORKLOAD_HEALTH_FAILED')
+ row.phase = 'observing-issued-ticket-expiry'; save()
+ row.cleanup = await settleIssued()
+ row.gc = await channel.call({ kind: 'gc' }); await sample(); row.producer = await channel.stop(); row.finishedAt = new Date().toISOString(); row.phase = 'complete'; save()
+ } finally { if (!row.producer) { await channel.call({ kind: 'cleanup' }).catch(() => { row.cleanupFailed = true }); channel.child.stdin.end(); await channel.stop().catch(() => { row.producer = channel.exit ?? { code: null, signal: 'unknown' } }) }; save() }
+ }
+ } catch (error) { report.status = 'failed'; report.failure = /^[A-Z0-9_]+$/.test(error.message) ? error.message : 'REAL_MEASUREMENT_OR_PREREQUISITE_FAILED' }
+ finally {
+ if (patched) { try { await mutateOptions(true); const restored = await json(['-n', NAMESPACE, 'get', 'deployment', DEPLOYMENT, '-o', 'json']); const value = restored.spec.template.spec.containers.find(item => item.name === CONTAINER).env?.find(item => item.name === 'NODE_OPTIONS'); assert(JSON.stringify(value) === JSON.stringify(original), 'RESTORATION_MISMATCH'); const restoredPods = (await json(['-n', NAMESPACE, 'get', 'pods', '-l', 'app=control-api', '-o', 'json'])).items.filter(value => !value.metadata.deletionTimestamp && value.status.containerStatuses?.some(c => c.name === CONTAINER && c.ready))
+ assert(restoredPods.length === 1, 'RESTORED_POD_AMBIGUOUS')
+ const healthCode = "const http=require('node:http'); const out=process.stdout.write.bind(process.stdout); process.stdout.write=()=>true;process.stderr.write=()=>true; const port=require('./dist/config.js').config.port; const req=http.get({hostname:'127.0.0.1',port,path:'/health'},r=>{r.resume();r.on('end',()=>{out(String(r.statusCode));process.exitCode=r.statusCode===200?0:1})});req.setTimeout(10000,()=>req.destroy());req.on('error',()=>process.exitCode=1);"
+ const health = await kc(['-n', NAMESPACE, 'exec', restoredPods[0].metadata.name, '-c', CONTAINER, '--', 'env', '-u', 'NODE_OPTIONS', 'node', '-e', healthCode])
+ assert(health.trim() === '200', 'RESTORED_HEALTH_FAILED')
+ report.restoration = { verified: true, deploymentUid: restored.metadata.uid, healthStatus: 200 } } catch { report.restoration = { verified: false }; report.status = 'failed' } }
+ report.finishedAt = new Date().toISOString(); if (report.status !== 'failed') { report.status = 'complete'; try { validateReceipt(report) } catch { report.status = 'failed'; report.failure = 'RECEIPT_HARD_GATE_FAILED' } }; save()
+ }
+ assert(report.status === 'complete', 'MEASUREMENT_FAILED_REPORT_SAVED')
+ return report
+}
+async function main() {
+ const options = parseOptions(process.argv.slice(2))
+ if (options.inspectPlan) { process.stdout.write(JSON.stringify({ mode: 'read-only-plan', profile: options.profile, context: options.context, candidate: options.candidate, shapes: options.shapes, runs: 3, gfsConcurrency: [1, 2], physicalExecution: 'NOT_RUN' }) + '\n'); return }
+ if (process.env.T2_SKIP_LOCK !== 'true' || !process.env.T2_LOCK_TOKEN) {
+ const common = (await command('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'])).trim(), dir = path.join(path.dirname(common), '.local-notes/infra/runs', options.runId)
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 }); const config = path.join(dir, 'memory-configuration.json')
+ fs.writeFileSync(config, JSON.stringify({ kind: 'control-api-authorize-memory-config.v1', arguments: options.publicArguments }), { flag: 'wx', mode: 0o600 })
+ await command('make', ['--no-print-directory', 'minikube-control-api-authorize-memory'], { env: { ...process.env, MINIKUBE_PROFILE: options.profile, CONTROL_API_REAL_PG_CONTEXT: options.context, CONTROL_API_MEMORY_CONFIG: config }, timeoutMs: 3 * (options.shapes.length * 2 + 2) * (120000 + options.candidate.readDeadlineMs + options.candidate.workDeadlineMs + 30000) + 600000, maxBytes: MIB })
+ process.stdout.write('CONTROL_API_AUTHORIZE_MEMORY_COMPLETE\n'); return
+ }
+ await run(options); process.stdout.write('CONTROL_API_AUTHORIZE_MEMORY_COMPLETE\n')
+}
+if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url)) main().catch(() => { process.stderr.write('CONTROL_API_AUTHORIZE_MEMORY_FAILED\n'); process.exitCode = 1 })
diff --git a/scripts/tests/measure-control-api-authorize-memory.test.mjs b/scripts/tests/measure-control-api-authorize-memory.test.mjs
index 6af465aa6..d490d4257 100644
--- a/scripts/tests/measure-control-api-authorize-memory.test.mjs
+++ b/scripts/tests/measure-control-api-authorize-memory.test.mjs
@@ -2,8 +2,15 @@ import assert from 'node:assert/strict'
import test from 'node:test'
import { createRequire, stripTypeScriptTypes } from 'node:module'
import fs from 'node:fs'
+import path from 'node:path'
+import os from 'node:os'
+import { spawnSync } from 'node:child_process'
+import { EventEmitter } from 'node:events'
+import { PassThrough } from 'node:stream'
+import { parseOptions, validateReceipt, Channel } from './measure-control-api-authorize-memory.mjs'
import { buildAuthorizeFixture, buildRejectedFixture, buildGfsFixture, MIB } from './lib/control-api-authorize-memory-fixtures.mjs'
import { InspectorClient, parseCgroup } from './lib/control-api-authorize-memory-inspector.mjs'
+import { ownedIssuedCleanupPlan } from './lib/control-api-authorize-memory-companion.ts'
const require = createRequire(import.meta.url)
const grok = require('../../packages/grok-provider-attempt-contract/index.cjs')
@@ -74,6 +81,161 @@ test('companion is valid native Node24 TypeScript source; it contains no role el
const source = fs.readFileSync(new URL('./lib/control-api-authorize-memory-companion.ts', import.meta.url), 'utf8')
const compiled = stripTypeScriptTypes(source)
assert(compiled.includes('issueMcpHostAccessJwt'))
- assert(compiled.includes('finalizeGrokProviderAttempt'))
+ assert(compiled.includes('/api/v1/internal/budgets/release'))
+ assert(!/finalizeGrokProviderAttempt|opaqueAttemptReceipt|markLlmProviderAttemptTicketRedeemed/.test(compiled))
assert(!/DELETE FROM llm_provider_attempt|ALTER ROLE|DROP TABLE/.test(compiled))
})
+
+// Pure controller tests use synthetic public metadata. They cannot activate a
+// runtime, mint credentials or stand in for physical measurement evidence.
+function args() {
+ return ['--profile','unit-owned','--context','unit-owned','--run-id','pr806-memory-123456abcdef',
+ '--host-namespace','mcp-host','--budget-ids','11111111-1111-1111-1111-111111111111,22222222-2222-2222-2222-222222222222',
+ '--gfs-parent-rid','33333333333333333333333333333333','--operator-user','unit-admin','--heap-size-mib','384',
+ '--concurrency','1','--read-deadline-ms','10000','--work-deadline-ms','30000','--close-grace-ms','250',
+ '--runs','3','--cgroup-limit-mib','768','--shape','visual-35mib,worst-structure,wide-strings','--report','/tmp/unit-memory-report.json',
+ '--prepare','restart','--inspector-port','9229','--include-legacy-gfs']
+}
+test('controller refuses missing/unknown/fractional/zero/partial shapes and silent required-lane omission', () => {
+ assert.equal(parseOptions(args(), {}).candidate.concurrency, 1)
+ assert.throws(() => parseOptions([], {}))
+ for (const [flag,value] of [['--runs','0'],['--concurrency','1.5'],['--shape','visual-35mib'],['--context','foreign'],['--cgroup-limit-mib','512'],['--host-namespace','--all-namespaces']]) {
+ const input=args(); input[input.indexOf(flag)+1]=value; assert.throws(() => parseOptions(input, {}))
+ }
+ assert.throws(() => parseOptions(args().filter(value => value !== '--include-legacy-gfs'), {}))
+ assert.throws(() => parseOptions([...args(),'--unknown','1'], {}))
+})
+test('actual CLI plan and rejection execute without any runtime/secret/helper activation', () => {
+ const script = new URL('./measure-control-api-authorize-memory.mjs', import.meta.url)
+ const plan = spawnSync(process.execPath, [script.pathname, ...args(),'--inspect-plan'], { env:{PATH:path.dirname(process.execPath)}, encoding:'utf8',timeout:5000 })
+ assert.equal(plan.status,0); assert.equal(JSON.parse(plan.stdout).physicalExecution,'NOT_RUN')
+ const reject = spawnSync(process.execPath, [script.pathname,'--runs','0'], {env:{PATH:path.dirname(process.execPath)},encoding:'utf8',timeout:5000})
+ assert.equal(reject.status,1); assert.equal(reject.stderr.trim(),'CONTROL_API_AUTHORIZE_MEMORY_FAILED')
+})
+function completeUnitReceipt() {
+ const start = new Date(1000).toISOString(), end = new Date(2000).toISOString()
+ const cgroup = {limit:768*MIB,current:100,peak:200,events:{oom:0,oom_kill:0}}
+ return { status:'complete', startedAt:start, finishedAt:end, source:{head:'a'.repeat(40),policySha256:'b'.repeat(64)}, restoration:{verified:true,healthStatus:200},
+ options:{candidate:{concurrency:1},shapes:['visual-35mib','worst-structure','wide-strings']}, runs:Array.from({length:3},(_,index)=>({
+ podUid:`unit-pod-${index}`,containerId:`unit-container-${index}`,phase:'complete',startedAt:start,finishedAt:end,
+ baseline:{executionTicketTtlMs:60000,compiledPolicySha256:'c'.repeat(64),server:{applicationProcesses:1,nodeProcessesIncludingAuxiliary:2,nodeVersion:'24.18.0'},cgroup},
+ producer:{code:0},warmupRelease:{lifecycle:'pg-issued-expiry-before-host-release'},warmup:{status:200,durableRowVerified:true,reservationVerified:true,reservationAmount:200},
+ cleanup:{lifecycle:'pg-issued-expiry-before-host-release',releaseEndpoint:'/api/v1/internal/budgets/release',total:8,retainedAuthorizedAuditRows:8,tickets:8,expiredIssuedTickets:8,liveIssuedTickets:0,redeemedAuditRows:0,finalizedAuditRows:0,redeemedTickets:0,finalizedTickets:0,reservationRows:0,activeReservations:0,executionTicketExpiryRemainingMs:0,observedAt:end,ownedGfsRemaining:0},
+ gc:{gc:{forced:true,kind:'native-HeapProfiler.collectGarbage',before:{pid:1,at:1000},after:{pid:1,at:2000}}},
+ causality:{excess:{status:503,acceptedWriteBytes:0},coverage:{parser:0,authorizer:0}},samples:[{server:{applicationProcesses:1,nodeProcessesIncludingAuxiliary:2},cgroup},{server:{applicationProcesses:1,nodeProcessesIncludingAuxiliary:2},cgroup}],
+ combined:Array.from({length:6},(_,i)=>({cleanup:{lifecycle:'pg-issued-expiry-before-host-release',liveIssuedTickets:0,reservationRows:0},authorizes:[{status:200,durableRowVerified:true,reservationVerified:true,reservationAmount:200}],gfsConcurrency:i%2+1,gfs:Array.from({length:i%2+1},()=>({status:201,verifiedDigest:'unit-digest',expectedDigest:'unit-digest'}))})),
+ rejected:[{status:413},{status:413}],recovery:{status:200},health:{status:200},stalled:{status:408},closedTransaction:{physicallyQuiesced:true}
+ })) }
+}
+test('complete producer/status/report windows are mandatory and unknown/partial/failed observations cannot become green', () => {
+ assert.equal(validateReceipt(completeUnitReceipt()),true)
+ for(const change of [
+ r=>r.runs.pop(),r=>r.source.policySha256=undefined,r=>r.restoration.verified=false,r=>r.runs[0].producer.code=137,
+ r=>r.runs[0].cleanup.liveIssuedTickets=1,r=>r.runs[0].gc.gc.forced=false,r=>r.runs[0].causality.coverage.parser=1,
+ r=>r.runs[0].samples[0].cgroup={...r.runs[0].samples[0].cgroup,peak:700*MIB},r=>r.runs[0].combined.pop(),
+ r=>r.runs[0].combined[0].authorizes[0].durableRowVerified=false,r=>r.runs[0].closedTransaction.physicallyQuiesced=false,
+ r=>r.runs[1].containerId=r.runs[0].containerId,r=>r.runs[0].baseline.server.applicationProcesses=2,
+ r=>r.runs[0].cleanup.expiredIssuedTickets=0,r=>r.runs[0].cleanup.retainedAuthorizedAuditRows=0,r=>r.runs[0].cleanup.finalizedTickets=8,
+ r=>r.runs[0].combined[0].authorizes[0].reservationVerified=false,r=>r.runs[0].baseline.server.nodeProcessesIncludingAuxiliary=3,r=>r.runs[0].cleanup.reservationRows=1,r=>r.runs[0].cleanup.observedAt=undefined,r=>r.runs[0].baseline.executionTicketTtlMs=undefined,
+ ]) {const receipt=completeUnitReceipt();change(receipt);assert.throws(()=>validateReceipt(receipt))}
+})
+test('Make calibration draft owns mutation lease and require-lock body; core image targets remain public entry points', () => {
+ const fragment=fs.readFileSync(new URL('../../Makefile',import.meta.url),'utf8')
+ assert(fragment.includes('with-t2-mutation-lock.sh'))
+ assert(fragment.includes('require-t2-mutation-lock.sh'))
+ assert(fragment.includes('CONTROL_API_MEMORY_READ_ONLY'))
+ assert(fragment.includes('--inspect-plan'))
+ const driver=fs.readFileSync(new URL('./measure-control-api-authorize-memory.mjs',import.meta.url),'utf8')
+ assert(driver.includes("'minikube-deploy-service'"));assert(driver.includes("'minikube-restart-deploy'"))
+ assert(!driver.includes('build-images.sh'))
+})
+
+test('a blocked producer stdin is bounded by the command deadline; no infinite wait or hidden zero exit', async () => {
+ const child = new EventEmitter()
+ child.stderr = new PassThrough(); child.stdout = new PassThrough()
+ child.stdin = Object.assign(new EventEmitter(), { write: () => true, end: () => {} })
+ child.kill = () => true
+ const channel = new Channel(child, 30)
+ await assert.rejects(() => channel.call({kind:'unit-only'}), /DEADLINE/)
+ child.emit('close', 1, null)
+})
+test('20MiB padded image is actually decodable pixels rather than declared-header-only geometry', async () => {
+ const native = createRequire(new URL('../../mcp-host/package.json',import.meta.url))('@napi-rs/canvas')
+ const fixture = buildAuthorizeFixture({shape:'visual-35mib',binding,invocationId:'unit-pixel-decode'})
+ const bytes = Buffer.from(fixture.request.messages[0].contentParts[1].data,'base64')
+ const decoded = await native.loadImage(bytes)
+ assert.equal(decoded.width,8); assert.equal(decoded.height,8)
+})
+
+test('selected Kubernetes context is explicit and canonical worktree/image schemas are consumed without ambient context mutation', () => {
+ const driver=fs.readFileSync(new URL('./measure-control-api-authorize-memory.mjs',import.meta.url),'utf8')
+ assert(driver.includes("['--context', options.context, ...args]"))
+ assert(driver.includes("['--context', options.context, '-n'"))
+ assert(!driver.includes("['config', 'current-context']"))
+ assert(!driver.includes('use-context'))
+ assert(driver.includes('t2_worktree_id'))
+ assert(!driver.includes("createHash('sha1')"))
+ const builder=fs.readFileSync(new URL('../minikube/build-images.sh',import.meta.url),'utf8')
+ assert(builder.includes('sourceRevisions'))
+ assert(builder.includes('MANIFEST_ENTRY_REVISIONS'))
+})
+
+
+test('issued cleanup retains audit and only releases known owner-bound reservations; unknown commits and dispatched states fail', () => {
+ const row = {id:'unit-attempt',invocation_id:'unit-invocation',host_ref:'unit-host',request_hash:'a'.repeat(64),connection_id:'unit-connection',status:'authorized',ticket_status:'issued',ticket_expired:true,reservation_id:'unit-reservation',reservation_host_ref:'unit-host',budget_id:'unit-budget'}
+ const bindings = [{hostRef:'unit-host',connectionId:'unit-connection',budgetId:'unit-budget'}]
+ const confirmed = new Map([['unit-attempt',{invocationId:'unit-invocation',hostRef:'unit-host',requestHash:'a'.repeat(64)}]])
+ assert.deepEqual(ownedIssuedCleanupPlan([row],bindings,confirmed), {retainedAuthorizedAuditRows:1,reservations:[{reservationId:'unit-reservation',hostRef:'unit-host'}]})
+ assert.deepEqual(ownedIssuedCleanupPlan([{...row,reservation_id:null}],bindings,confirmed), {retainedAuthorizedAuditRows:1,reservations:[]})
+ for (const patch of [{ticket_expired:false},{ticket_expired:undefined},{status:'redeemed'},{ticket_status:'redeemed'},{status:'finalized',ticket_status:'finalized'},{ticket_status:null},{connection_id:'foreign'},{reservation_host_ref:'foreign'},{budget_id:'foreign'},{request_hash:'b'.repeat(64)}]) assert.throws(() => ownedIssuedCleanupPlan([{...row,...patch}],bindings,confirmed))
+ assert.throws(() => ownedIssuedCleanupPlan([row,{...row,id:'unconfirmed-commit'}],bindings,confirmed))
+ assert.throws(() => ownedIssuedCleanupPlan([],bindings,confirmed))
+ assert.equal(ownedIssuedCleanupPlan([],bindings,new Map()).retainedAuthorizedAuditRows,0)
+})
+
+
+// Run the actual pure/state function source without importing production config
+// or bootstrap side effects. Captured SQL is a unit fake, not PostgreSQL proof.
+function actualFunction(file, start, end, name, parameters = [], values = []) {
+ const source = fs.readFileSync(new URL(file, import.meta.url), 'utf8')
+ const offset = source.indexOf(start); assert(offset >= 0)
+ const until = source.indexOf(end, offset); assert(until > offset)
+ const compiled = stripTypeScriptTypes(source.slice(offset, until)).replace(/^export /gm, '')
+ return new Function(...parameters, `${compiled}; return ${name}`)(...values)
+}
+test('actual production finalization store refuses issued and makes no audit mutation', async () => {
+ const finalize = actualFunction('../../control-api/src/services/llmProviderAttemptStore.ts', 'export async function markLlmProviderAttemptFinalized(', 'export async function getMaxLlmProviderAttemptGeneration(', 'markLlmProviderAttemptFinalized')
+ const statements = []
+ const db = {query: async text => {statements.push(text);assert.match(text.trim(), /^SELECT /);return {rows:[{status:'issued',receipt_hash:null}],rowCount:1}}}
+ assert.equal(await finalize(db,{providerAttemptId:'unit-owned-attempt',receiptHash:'a'.repeat(64),outcome:'canceled'}),'conflict')
+ assert.equal(statements.length,1)
+})
+test('actual release route binds both sentinel/recipe namespace and exact Host; scope cannot release another Host', () => {
+ const releaseBinding = actualFunction('../../control-api/src/routes/internal/budgetsCheck.ts', 'function checkReleaseClaimBinding(', 'export function createInternalBudgetsCheckRouter(', 'checkReleaseClaimBinding', ['config'], [{hostsNamespace:'unit-hosts',sandboxNamespace:'unit-sandbox'}])
+ for (const recipeNamespace of ['unit-hosts','unit-sandbox']) {
+ const claims={recipeNamespace,hostRefs:['unit-owner']}
+ assert.equal(releaseBinding('unit-owner',claims),null)
+ assert.equal(releaseBinding('foreign-host',claims),'host_ref_mismatch')
+ }
+ assert.equal(releaseBinding('unit-owner',{recipeNamespace:'foreign-namespace',hostRefs:['unit-owner']}),'unrecognized_token_binding')
+})
+class UnitOwnerSocket extends UnitSocket {
+ constructor() { super();this.instances=1;this.owner=1;this.missing=false }
+ send(raw) {
+ const request=JSON.parse(raw);this.commands.push(request.method)
+ let result={}
+ if(request.method==='Runtime.evaluate')result=this.missing?{exceptionDetails:{}}:{result:{objectId:'unit-production-prototype'}}
+ if(request.method==='Runtime.queryObjects')result={objects:{objectId:'unit-actual-owner-array'}}
+ if(request.method==='Runtime.callFunctionOn')result={result:{value:{pid:4,at:this.commands.length,instanceCount:this.instances,inFlight:this.owner}}}
+ queueMicrotask(()=>this.dispatchEvent(new MessageEvent('message',{data:JSON.stringify({id:request.id,result})})))
+ }
+}
+test('native owner projection requires unique actual singleton and releases inspection references; unavailable is not zero', async () => {
+ const socket=new UnitOwnerSocket(),inspector=new InspectorClient(socket)
+ assert.equal((await inspector.owners()).inFlight,1)
+ assert.deepEqual(socket.commands,['Runtime.evaluate','Runtime.queryObjects','Runtime.callFunctionOn','Runtime.releaseObjectGroup'])
+ for(const count of [0,2]){socket.instances=count;await assert.rejects(()=>inspector.owners(),/unknown/)}
+ socket.instances=1;socket.owner=null;await assert.rejects(()=>inspector.owners(),/unknown/)
+ socket.missing=true;await assert.rejects(()=>inspector.owners(),/unavailable/)
+ assert.equal(socket.commands.at(-1),'Runtime.releaseObjectGroup');inspector.close()
+})
diff --git a/scripts/tests/subscription-image-runner.test.mjs b/scripts/tests/subscription-image-runner.test.mjs
new file mode 100644
index 000000000..e1bcaf59f
--- /dev/null
+++ b/scripts/tests/subscription-image-runner.test.mjs
@@ -0,0 +1,702 @@
+// Metadata-only unit fixtures test admission refusals. They are not physical
+// Linux observations, a runner receipt, keychain proof, or visible E2E passes.
+import assert from 'node:assert/strict'
+import { spawnSync } from 'node:child_process'
+import fs from 'node:fs'
+import os from 'node:os'
+import path from 'node:path'
+import test from 'node:test'
+import { fileURLToPath } from 'node:url'
+import {
+ admitVendorFrame,
+ digest,
+ expectedJourneyNames,
+ isEncryptedKeyringHeader,
+ parseMountInfo,
+ privateBusPath,
+ readPrivateJson,
+ unixSocketInode,
+ verifyAccount,
+ verifyJourneyReport,
+ verifyMainAdmission,
+ verifyMountIsolation,
+ verifyPrivateIsolation,
+ verifyRunnerEnvironment,
+ verifySocketBinding,
+ sfwFreeAsset,
+ verifySourceManifest,
+ verifyThirdPartyArtifact,
+} from './lib/subscription-image-runner-contract.mjs'
+import { allowedSourcePath } from './lib/subscription-image-source-context.mjs'
+import {
+ verifyPressureMetadata,
+ verifyPressureObservation,
+} from '../e2e/fixtures/subscription-image-admission-pressure.mjs'
+
+const home = '/home/evenfire-e2e',
+ base = '/run/evenfire-e2e',
+ admissionRoot = '/runner-admission'
+const observed = {
+ platform: 'linux',
+ uid: 10001,
+ gid: 10001,
+ home,
+ mountNamespace: 'mnt:[123]',
+ pidNamespace: 'pid:[234]',
+ userNamespace: 'user:[345]',
+ mountInfoSha256: 'a'.repeat(64),
+}
+const processRow = (pid, executable) => ({
+ pid,
+ uid: observed.uid,
+ startTime: '321',
+ executable,
+ executablePath: `/usr/bin/${executable}`,
+ argvSha256: 'b'.repeat(64),
+ mountNamespace: observed.mountNamespace,
+ pidNamespace: observed.pidNamespace,
+ userNamespace: observed.userNamespace,
+})
+const isolation = {
+ homeMountId: '3',
+ runMountId: '4',
+ tmpMountId: '5',
+ admissionMountId: '6',
+ sessionBus: {
+ ...processRow(100, 'dbus-daemon'),
+ socketPath: `${home}/runtime/bus`,
+ socketInode: '700',
+ address: `unix:path=${home}/runtime/bus`,
+ },
+ display: {
+ ...processRow(101, 'Xvfb'),
+ socketPath: '/tmp/.X11-unix/X17',
+ socketInode: '701',
+ value: ':17',
+ xauthorityPath: `${home}/.Xauthority`,
+ },
+ keyring: processRow(102, 'gnome-keyring-daemon'),
+}
+const environment = {
+ HOME: home,
+ DISPLAY: isolation.display.value,
+ XAUTHORITY: isolation.display.xauthorityPath,
+ DBUS_SESSION_BUS_ADDRESS: isolation.sessionBus.address,
+}
+const rawMounts = [
+ '1 0 0:1 / / ro,relatime - overlay overlay ro',
+ '2 1 0:2 / /proc rw,nosuid,nodev,noexec - proc proc rw',
+ `3 1 0:3 / ${home} rw,nosuid,nodev - tmpfs tmpfs rw`,
+ `4 1 0:4 / ${base} rw,nosuid,nodev - tmpfs tmpfs rw`,
+ '5 1 0:5 / /tmp rw,nosuid,nodev - tmpfs tmpfs rw',
+ '6 1 0:6 /private/e2e-admission /runner-admission ro - ext4 /dev/root ro',
+].join('\n')
+
+test('mount guard requires readonly image/admission and three fresh unshadowed tmpfs mounts', () => {
+ assert.deepEqual(verifyMountIsolation(parseMountInfo(rawMounts), home, base, admissionRoot), {
+ homeMountId: '3',
+ runMountId: '4',
+ tmpMountId: '5',
+ admissionMountId: '6',
+ })
+ for (const changed of [
+ rawMounts.replace('/ / ro,relatime', '/ / rw,relatime'),
+ rawMounts.replace('/runner-admission ro', '/runner-admission rw'),
+ rawMounts.replace(`0:3 / ${home}`, `0:3 /home/personal ${home}`),
+ `${rawMounts}\n7 3 0:7 / /home/evenfire-e2e/keyring rw - tmpfs tmpfs rw`,
+ `${rawMounts}\n7 1 0:7 / /proc/private-bus rw - tmpfs tmpfs rw`,
+ `${rawMounts}\n7 1 0:7 /Users/operator /host-home ro - ext4 /dev/root ro`,
+ ])
+ assert.throws(() => verifyMountIsolation(parseMountInfo(changed), home, base, admissionRoot))
+})
+
+test('mount parser decodes paths and refuses malformed evidence', () => {
+ assert.equal(
+ parseMountInfo('1 0 0:1 / /unit\\040path ro - tmpfs tmpfs ro')[0].point,
+ '/unit path'
+ )
+ assert.throws(() => parseMountInfo('not mount evidence'))
+})
+
+test('OS account guard cannot be satisfied by HOME alone or an ambiguous passwd entry', () => {
+ const account = `evenfire-e2e:x:10001:10001::${home}:/bin/sh`
+ assert.doesNotThrow(() => verifyAccount(account, 10001, 10001, home, 'evenfire-e2e'))
+ for (const args of [
+ [account, 0, 10001, home, 'evenfire-e2e'],
+ [account, 10001, 10002, home, 'evenfire-e2e'],
+ [account, 10001, 10001, '/outside', 'evenfire-e2e'],
+ [`${account}\n${account}`, 10001, 10001, home, 'evenfire-e2e'],
+ ])
+ assert.throws(() => verifyAccount(...args))
+})
+
+test('inherited sockets, runtime path escapes and Electron sandbox overrides are refused', () => {
+ assert.doesNotThrow(() =>
+ verifyRunnerEnvironment({ HOME: home, XDG_CONFIG_HOME: `${home}/config` }, observed)
+ )
+ for (const extra of [
+ { SSH_AUTH_SOCK: '/outside/agent' },
+ { NODE_OPTIONS: '--inspect' },
+ { ELECTRON_DISABLE_SANDBOX: '1' },
+ { ELECTRON_RUN_AS_NODE: '1' },
+ { XAUTHORITY: '/outside/auth' },
+ { HOME: '/outside' },
+ ])
+ assert.throws(() => verifyRunnerEnvironment({ HOME: home, ...extra }, observed))
+})
+
+test('private bus address accepts one filesystem endpoint and its observed GUID only', () => {
+ assert.equal(
+ privateBusPath(`${isolation.sessionBus.address},guid=${'a'.repeat(32)}`),
+ isolation.sessionBus.socketPath
+ )
+ for (const address of [
+ 'unix:abstract=personal',
+ `${isolation.sessionBus.address};unix:path=/other`,
+ 'tcp:host=localhost,port=1234',
+ 'unix:path=relative',
+ ])
+ assert.throws(() => privateBusPath(address))
+})
+
+test('keyring header guard refuses plaintext and unsupported cipher/version data', () => {
+ const bytes = Buffer.from('GnomeKeyring\n\r\0\n\0\0\0\0')
+ assert.equal(isEncryptedKeyringHeader(bytes), true)
+ assert.equal(isEncryptedKeyringHeader(Buffer.from('[keyring]\ndisplay-name=unit')), false)
+ const other = Buffer.from(bytes)
+ other[18] = 1
+ assert.equal(isEncryptedKeyringHeader(other), false)
+})
+
+test('socket proof requires exactly one kernel inode and one FD held by the named live process', () => {
+ const table = `Num RefCount Protocol Flags Type St Inode Path\n0000: 0002 0000 00010000 0001 01 700 ${isolation.sessionBus.socketPath}`
+ assert.equal(unixSocketInode(table, isolation.sessionBus.socketPath), '700')
+ assert.doesNotThrow(() => verifySocketBinding('700', ['socket:[700]', '/dev/null']))
+ assert.throws(() =>
+ unixSocketInode(
+ `${table}\n0001: 0002 0000 00010000 0001 01 701 ${isolation.sessionBus.socketPath}`,
+ isolation.sessionBus.socketPath
+ )
+ )
+ assert.throws(() => verifySocketBinding('700', ['socket:[701]']))
+ assert.throws(() => verifySocketBinding('700', ['socket:[700]', 'socket:[700]']))
+})
+
+test('private isolation metadata refuses changed PID lifetime, UID, namespace, socket or keyring', () => {
+ assert.doesNotThrow(() =>
+ verifyPrivateIsolation(isolation, structuredClone(isolation), observed, environment, base)
+ )
+ for (const patch of [
+ { startTime: '322' },
+ { uid: 10002 },
+ { mountNamespace: 'mnt:[other]' },
+ { socketInode: 'other' },
+ { socketPath: '/outside/bus' },
+ ]) {
+ const changed = structuredClone(isolation)
+ Object.assign(changed.sessionBus, patch)
+ assert.throws(() => verifyPrivateIsolation(isolation, changed, observed, environment, base))
+ }
+ const changed = structuredClone(isolation)
+ changed.keyring.executablePath = `${home}/gnome-keyring-daemon`
+ assert.throws(() => verifyPrivateIsolation(changed, changed, observed, environment, base))
+ assert.throws(() =>
+ verifyPrivateIsolation(
+ isolation,
+ isolation,
+ observed,
+ { ...environment, DBUS_SESSION_BUS_ADDRESS: 'unix:path=/outside/bus' },
+ base
+ )
+ )
+})
+
+const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+const pinnedBase = JSON.parse(
+ fs.readFileSync(path.join(repoRoot, 'scripts/e2e/fixtures/subscription-image-runner.base-image'), 'utf8')
+)
+const forwardRecord = (service, namespace, localPort, remotePort) =>
+ `1000\nPORT_FORWARD_OWNER_VERSION=1\nPID=1000\nPROCESS_START=Thu Oct 2 00:00:00 2026\n` +
+ `PROFILE=unit-owned\nCONTEXT=unit-owned\nWORKTREE=/unit/worktree\nNAMESPACE=${namespace}\n` +
+ `SERVICE=${service}\nLOCAL_PORT=${localPort}\nREMOTE_PORT=${remotePort}\nADDRESS=127.0.0.1\n`
+
+function mainMetadata() {
+ const createdAt = new Date(Date.now() - 1000).toISOString()
+ const source = {
+ gitHead: 'a'.repeat(40),
+ gitTree: 'b'.repeat(40),
+ inputManifestSha256: 'c'.repeat(64),
+ manifestSha256: 'd'.repeat(64),
+ }
+ const stack = {
+ gitHead: source.gitHead,
+ worktreeId: 'e'.repeat(40),
+ clusterFingerprint: 'f'.repeat(64),
+ imagesGeneratedAt: '2026-10-02T00:00:00Z',
+ portsReceiptSha256: '1'.repeat(64),
+ }
+ const portsEnvRaw = 'EXTERNAL_REST_API_PORT=34051\nRPC_PROXY_PORT=34052\n'
+ const stackReceipt = {
+ kind: 'evenfire-subscription-image-stack-marker-v1',
+ context: 'unit-owned',
+ configMapName: 'clerum-pre-gate-sync-state',
+ resourceVersion: '12345',
+ fetchedAt: createdAt,
+ profile: 'unit-owned',
+ portsEnvRaw,
+ portsEnvSha256: digest(portsEnvRaw),
+ data: {
+ gitHead: source.gitHead,
+ worktreeId: stack.worktreeId,
+ clusterFingerprint: stack.clusterFingerprint,
+ imagesGeneratedAt: stack.imagesGeneratedAt,
+ imageSource: 'local',
+ imageTag: 'unit',
+ },
+ }
+ const restRaw = forwardRecord('external-rest-api', 'profiles', 34051, 8091)
+ const rpcRaw = forwardRecord('rpc-proxy', 'rpc-proxy', 34052, 8094)
+ const portForwardsReceipt = {
+ kind: 'evenfire-subscription-image-port-forwards-v1',
+ profile: 'unit-owned',
+ context: 'unit-owned',
+ verifiedAt: createdAt,
+ entries: {
+ rest: { raw: restRaw, recordSha256: digest(restRaw), pid: 1000, processStart: 'unit-start' },
+ rpc: { raw: rpcRaw, recordSha256: digest(rpcRaw), pid: 1000, processStart: 'unit-start' },
+ },
+ }
+ const inspectReceipt = {
+ container: {
+ Id: '9'.repeat(64),
+ Image: `sha256:${'2'.repeat(64)}`,
+ Created: createdAt,
+ Config: {
+ User: '10001:10001',
+ Env: ['HOME=/home/evenfire-e2e', 'SUBSCRIPTION_IMAGE_RUN_ID=subscription-image-123456abcdef'],
+ },
+ State: { Running: true },
+ HostConfig: {
+ ReadonlyRootfs: true,
+ Privileged: false,
+ PidMode: 'private',
+ IpcMode: 'private',
+ NetworkMode: 'bridge',
+ CapDrop: ['ALL'],
+ SecurityOpt: [],
+ },
+ Mounts: [
+ { Type: 'bind', Source: '/private/e2e-admission', Destination: '/runner-admission', RW: false },
+ { Type: 'tmpfs', Source: 'tmpfs', Destination: home, RW: true },
+ { Type: 'tmpfs', Source: 'tmpfs', Destination: '/run/evenfire-e2e', RW: true },
+ { Type: 'tmpfs', Source: 'tmpfs', Destination: '/tmp', RW: true },
+ ],
+ },
+ securityOptions: ['name=seccomp,profile=builtin'],
+ }
+ const admission = {
+ kind: 'evenfire-subscription-image-main-admission-v2',
+ runId: 'subscription-image-123456abcdef',
+ suiteId: 'subscription-image-input',
+ mode: 'fixture',
+ ...source,
+ sourceManifestSha256: source.manifestSha256,
+ repoRoot,
+ imageId: `sha256:${'2'.repeat(64)}`,
+ baseImage: pinnedBase.reference,
+ uiFeatures: {},
+ observation: observed,
+ networkNamespace: 'net:[456]',
+ ipcNamespace: 'ipc:[567]',
+ profile: 'unit-owned',
+ context: 'unit-owned',
+ stack: { ...stack, portsReceiptSha256: stackReceipt.portsEnvSha256 },
+ runtime: {
+ readOnlyRootfs: true,
+ privileged: false,
+ pidMode: 'private',
+ ipcMode: 'private',
+ networkMode: 'unit-owned-bridge',
+ user: '10001:10001',
+ capDrop: ['ALL'],
+ seccompMode: 'filter',
+ containerId: '9'.repeat(64),
+ createdAt,
+ },
+ receipts: {
+ generatedAt: createdAt,
+ dockerInspectSha256: digest(JSON.stringify(inspectReceipt)),
+ stackMarkerSha256: digest(JSON.stringify(stackReceipt)),
+ portForwardsSha256: digest(JSON.stringify(portForwardsReceipt)),
+ },
+ volume: {
+ name: 'evenfire-sir-123456abcdef-admission',
+ driver: 'local',
+ createdAt,
+ inspectSha256: '7'.repeat(64),
+ },
+ thirdPartyArtifacts: [
+ {
+ name: 'sfw-free',
+ version: '1.15.1',
+ arch: 'arm64',
+ sha256: '8'.repeat(64),
+ bytes: 136907904,
+ elfMachine: 0xb7,
+ },
+ ],
+ bindings: [{ provider: 'grok-subscription' }, { provider: 'codex-subscription' }],
+ transports: Object.fromEntries(
+ [
+ ['rest', 'external-rest-api', '34051'],
+ ['rpc', 'rpc-proxy', '34052'],
+ ].map(([kind, service, port]) => [
+ kind,
+ {
+ origin: `http://host.docker.internal:${port}`,
+ service,
+ profile: 'unit-owned',
+ context: 'unit-owned',
+ worktreeId: stack.worktreeId,
+ gitHead: stack.gitHead,
+ portsReceiptSha256: stack.portsReceiptSha256,
+ forwardBindingSha256: '6'.repeat(64),
+ },
+ ])
+ ),
+ }
+ admission.transports.rest.forwardBindingSha256 = digest(restRaw)
+ admission.transports.rpc.forwardBindingSha256 = digest(rpcRaw)
+ admission.transports.rest.portsReceiptSha256 = stackReceipt.portsEnvSha256
+ admission.transports.rpc.portsReceiptSha256 = stackReceipt.portsEnvSha256
+ const physical = {
+ observation: observed,
+ networkNamespace: 'net:[456]',
+ ipcNamespace: 'ipc:[567]',
+ }
+ const receipts = {
+ inspect: { value: inspectReceipt, sha256: digest(JSON.stringify(inspectReceipt)) },
+ stack: { value: stackReceipt, sha256: digest(JSON.stringify(stackReceipt)) },
+ portForwards: { value: portForwardsReceipt, sha256: digest(JSON.stringify(portForwardsReceipt)) },
+ }
+ return { source, admission, physical, receipts }
+}
+test('main admission binds the real source manifest, stack marker, private runtime and both forward records', () => {
+ const { source, admission, physical, receipts } = mainMetadata()
+ assert.doesNotThrow(() =>
+ verifyMainAdmission(admission, physical, source, repoRoot, { HOME: home }, 'admit', receipts)
+ )
+ for (const change of [
+ value => {
+ value.gitHead = '7'.repeat(40)
+ },
+ value => {
+ value.gitTree = '7'.repeat(40)
+ },
+ value => {
+ value.context = 'different'
+ },
+ value => {
+ value.runtime.privileged = true
+ },
+ value => {
+ value.runtime.networkMode = 'host'
+ },
+ value => {
+ value.runtime.pidMode = 'host'
+ },
+ value => {
+ value.stack.portsReceiptSha256 = '7'.repeat(64)
+ },
+ value => {
+ value.transports.rpc.origin = value.transports.rest.origin
+ },
+ value => {
+ value.transports.rpc.origin = 'http://127.0.0.1:8091'
+ },
+ value => {
+ value.transports.rest.worktreeId = '7'.repeat(40)
+ },
+ ]) {
+ const changed = structuredClone(admission)
+ change(changed)
+ assert.throws(() =>
+ verifyMainAdmission(changed, physical, source, repoRoot, { HOME: home }, 'admit', receipts)
+ )
+ }
+ const stale = structuredClone(admission)
+ stale.runtime.createdAt = new Date(Date.now() - 700_000).toISOString()
+ assert.throws(() =>
+ verifyMainAdmission(stale, physical, source, repoRoot, { HOME: home }, 'admit', receipts)
+ )
+ const swapped = structuredClone(admission)
+ swapped.uiFeatures = { VITE_SHOW_GLOBAL_FILE_SYSTEM_COMPOSER_ITEM: 'true' }
+ assert.throws(() =>
+ verifyMainAdmission(swapped, physical, source, repoRoot, { HOME: home }, 'admit', receipts)
+ )
+})
+
+test('private JSON refuses wrong mode, symlink and hardlink without accepting an environment assertion', () => {
+ const root = fs.mkdtempSync(path.join(fs.realpathSync(os.tmpdir()), 'subscription-runner-unit-'))
+ try {
+ const filename = path.join(root, 'unit-admission.json')
+ fs.writeFileSync(filename, JSON.stringify({ kind: 'unit-only-json' }), {
+ mode: 0o600,
+ })
+ assert.equal(readPrivateJson(filename).kind, 'unit-only-json')
+ fs.chmodSync(filename, 0o644)
+ assert.throws(() => readPrivateJson(filename))
+ fs.chmodSync(filename, 0o600)
+ fs.symlinkSync(filename, path.join(root, 'link.json'))
+ assert.throws(() => readPrivateJson(path.join(root, 'link.json')))
+ fs.linkSync(filename, path.join(root, 'hard.json'))
+ assert.throws(() => readPrivateJson(filename))
+ } finally {
+ fs.rmSync(root, { recursive: true })
+ }
+})
+
+test('minimal source context excludes ignored/private/Git files and unrelated repository paths', () => {
+ const packages = ['packages/llm-provider-attempt-contract']
+ for (const filename of [
+ 'desktop-app/src/main.ts',
+ 'desktop-app/ui/src/App.tsx',
+ 'packages/llm-provider-attempt-contract/testImageFixtures.cjs',
+ ])
+ assert.equal(allowedSourcePath(filename, packages), true)
+ for (const filename of [
+ '.git/HEAD',
+ 'desktop-app/.env',
+ 'desktop-app/src/session.key',
+ 'desktop-app/src/__tests__/personal.test.ts',
+ 'control-api/src/main.ts',
+ 'packages/not-in-closure/index.js',
+ '../escape',
+ '/outside',
+ ])
+ assert.equal(allowedSourcePath(filename, packages), false)
+ assert.throws(() =>
+ verifySourceManifest(
+ {
+ kind: 'evenfire-subscription-image-source-v1',
+ gitHead: 'a'.repeat(40),
+ files: [],
+ },
+ '/unit'
+ )
+ )
+})
+
+test('vendor frames require the sealed physical proxy identity and an unchanged bounded history', () => {
+ const binding = {
+ provider: 'grok-subscription',
+ modelId: 'unit-vision',
+ unsupportedModelId: 'unit-text',
+ }
+ const source = {
+ profile: 'unit-owned',
+ podUid: 'unit-pod',
+ imageId: `sha256:${'a'.repeat(64)}`,
+ }
+ const row = {
+ sequence: 1,
+ provider: binding.provider,
+ model: binding.modelId,
+ receiptId: '11111111-1111-4111-8111-111111111111',
+ imageSha256: ['b'.repeat(64)],
+ mimeTypes: ['image/png'],
+ requestSha256: 'c'.repeat(64),
+ responseKind: 'pixels',
+ outputSha256: 'd'.repeat(64),
+ }
+ const frame = {
+ kind: 'evenfire-subscription-image-vendor-frame-v1',
+ runId: 'unit-run',
+ provider: binding.provider,
+ source,
+ ledger: {
+ kind: 'evenfire-subscription-image-vendor-v1',
+ runId: 'unit-run',
+ attempts: [row],
+ },
+ }
+ assert.equal(admitVendorFrame(frame, 'unit-run', binding, source, []).attempts.length, 1)
+ for (const change of [
+ value => {
+ value.source.podUid = 'other'
+ },
+ value => {
+ value.ledger.attempts[0].sequence = 2
+ },
+ value => {
+ value.ledger.attempts[0].rawBody = 'forbidden extra field'
+ },
+ value => {
+ value.ledger.attempts[0].model = 'unowned'
+ },
+ ]) {
+ const changed = structuredClone(frame)
+ change(changed)
+ assert.throws(() => admitVendorFrame(changed, 'unit-run', binding, source, []))
+ }
+ const changed = structuredClone(frame)
+ changed.ledger.attempts[0].outputSha256 = 'e'.repeat(64)
+ assert.throws(() => admitVendorFrame(changed, 'unit-run', binding, source, [row]))
+})
+
+test('named journey reporter rejects missing, skipped, duplicate or foreign-file cases even with producer exit zero', () => {
+ // This synthetic reporter tests only the status guard, never an E2E pass.
+ const file = '/unit/subscription-image-input.spec.ts'
+ const cases = expectedJourneyNames('fixture')
+ const report = {
+ config: { rootDir: '/unit' },
+ errors: [],
+ stats: { expected: 14, unexpected: 0, flaky: 0, skipped: 0 },
+ suites: [
+ {
+ title: path.basename(file),
+ specs: cases.map(title => ({
+ title,
+ file: path.basename(file),
+ ok: true,
+ tests: [
+ {
+ projectName: 'subscription-image-input',
+ expectedStatus: 'passed',
+ status: 'expected',
+ results: [{ status: 'passed' }],
+ },
+ ],
+ })),
+ },
+ ],
+ }
+ assert.equal(verifyJourneyReport(report, 'fixture', file).executed, 14)
+ for (const change of [
+ value => {
+ value.stats.expected = 0
+ },
+ value => {
+ value.suites[0].specs.pop()
+ },
+ value => {
+ value.suites[0].specs[0].tests[0].results[0].status = 'skipped'
+ },
+ value => {
+ value.suites[0].specs[0].file = 'unrelated.spec.ts'
+ },
+ value => {
+ value.suites[0].specs[0].title = value.suites[0].specs[1].title
+ },
+ ]) {
+ const changed = structuredClone(report)
+ change(changed)
+ assert.throws(() => verifyJourneyReport(changed, 'fixture', file))
+ }
+})
+
+test('runner defaults to refusal; explicit plan never launches or produces a runtime receipt', () => {
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+ const runner = path.join(root, 'scripts/e2e/run-subscription-image-journeys.mjs')
+ const options = {
+ encoding: 'utf8',
+ timeout: 5_000,
+ env: { PATH: path.dirname(process.execPath) },
+ }
+ const defaultRun = spawnSync(process.execPath, [runner], options)
+ assert.equal(defaultRun.status, 1)
+ assert.match(defaultRun.stderr, /runner-refused/)
+ const plan = spawnSync(process.execPath, [runner, 'plan'], options)
+ assert.equal(plan.status, 0)
+ assert.equal(JSON.parse(plan.stdout).sourceOnly, true)
+ assert.doesNotMatch(plan.stdout, /runner-admitted|runner-v2/)
+})
+
+test('runner image uses only staged explicit copies, locked sfw installs and the nonroot account', () => {
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')
+ const dockerfile = fs.readFileSync(
+ path.join(root, 'scripts/e2e/fixtures/subscription-image-runner.Dockerfile'),
+ 'utf8'
+ )
+ assert.doesNotMatch(
+ dockerfile,
+ /^COPY\s+\.\s|source-git|\.git\/HEAD|--ignore-scripts|--no-sandbox|--privileged|--network=host|apt-get\s+(upgrade|dist-upgrade)/m
+ )
+ assert.match(dockerfile, /apt-get install -y --no-install-recommends/)
+ assert.match(dockerfile, /sfw npm ci --prefix desktop-app/)
+ assert.match(dockerfile, /sfw npm ci --prefix mcp-host/)
+ assert.match(dockerfile, /USER 10001:10001/)
+ assert.match(dockerfile, /verifyInputSource/)
+})
+
+test('third-party sfw-free assets stay pinned and artifact drift is refused', () => {
+ const arm = sfwFreeAsset('arm64'),
+ x64 = sfwFreeAsset('x64')
+ assert.equal(
+ arm.url,
+ 'https://github.com/SocketDev/sfw-free/releases/download/v1.15.1/sfw-free-linux-arm64'
+ )
+ assert.equal(arm.sha256, '4d02d1c1f5d6b6444721b0a67bd0e80aab182fe7f22d692570d1c14797602c47')
+ assert.equal(arm.bytes, 136907904)
+ assert.equal(
+ x64.url,
+ 'https://github.com/SocketDev/sfw-free/releases/download/v1.15.1/sfw-free-linux-x86_64'
+ )
+ assert.equal(x64.sha256, '8898d0667c2165aecd695ca797473ec3a429d2ed807d4d0bf9e67c45817ea809')
+ assert.throws(() => sfwFreeAsset('ia32'))
+ const body = Buffer.alloc(20)
+ body.writeUInt32LE(0x464c457f, 0)
+ body[4] = 2
+ body[5] = 1
+ body.writeUInt16LE(0xb7, 18)
+ const asset = { sha256: digest(body), bytes: body.length, arch: 'arm64', machine: 0xb7 }
+ assert.equal(verifyThirdPartyArtifact({ bytes: body, asset }).elfMachine, 0xb7)
+ assert.throws(() =>
+ verifyThirdPartyArtifact({ bytes: body, asset: { ...asset, sha256: 'a'.repeat(64) } })
+ )
+ assert.throws(() => verifyThirdPartyArtifact({ bytes: body, asset: { ...asset, machine: 0x3e } }))
+ const text = Buffer.from('not-an-elf')
+ assert.throws(() =>
+ verifyThirdPartyArtifact({ bytes: text, asset: { ...asset, bytes: text.length, sha256: digest(text) } })
+ )
+})
+
+test('pressure metadata and native owner observations refuse drift', () => {
+ const metadata = {
+ kind: 'evenfire-subscription-image-pressure-metadata-v1',
+ profile: 'unit-owned',
+ context: 'unit-owned',
+ worktreeId: 'a'.repeat(40),
+ sourceManifestSha256: 'b'.repeat(64),
+ podUid: 'unit-pod',
+ imageId: `sha256:${'c'.repeat(64)}`,
+ pressureRunId: 'subscription-image-pressure-123456abcdef',
+ hostRefs: ['unit-grok', 'unit-codex'],
+ maxInFlight: 2,
+ socketPath: '/run/evenfire-e2e/pressure.sock',
+ }
+ assert.doesNotThrow(() => verifyPressureMetadata(metadata))
+ assert.throws(() => verifyPressureMetadata({ ...metadata, hostRefs: ['unit-grok', 'unit-grok'] }))
+ assert.throws(() => verifyPressureMetadata({ ...metadata, socketPath: 'relative.sock' }))
+ const value = {
+ ok: true,
+ pressureRunId: metadata.pressureRunId,
+ maxInFlight: 2,
+ owners: { baseline: 0, held: 2, drained: 0 },
+ counts: { sameRunAttempts: 0, sameRunTickets: 0, reservations: 0 },
+ pids: [42],
+ inspector: { pid: 42, startTime: 'unit-start' },
+ }
+ assert.equal(verifyPressureObservation(value, { held: 2, drained: 0 }, metadata).owners.held, 2)
+ assert.throws(() => verifyPressureObservation({ ...value, pids: [43] }, {}, metadata))
+ assert.throws(() =>
+ verifyPressureObservation({ ...value, counts: { ...value.counts, reservations: 1 } }, {}, metadata)
+ )
+ assert.throws(() =>
+ verifyPressureObservation(
+ { ...value, pressureRunId: 'subscription-image-pressure-ffffffffffff' },
+ {},
+ metadata
+ )
+ )
+})