Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(codex): complete owned fixture setup and restoration
Alfredo Lopez09bb5f1ef719
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 4482c76ba..89acc163a 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -140,6 +140,10 @@ jobs:scripts/e2e/desktop-login-seed.test.mjs \scripts/e2e/approved-tools-image-proof.test.mjs \scripts/e2e/approved-tools-restoration.test.mjs \+ scripts/e2e/approved-tools-control-api-lifecycle.test.mjs \+ scripts/e2e/approved-tools-connection-journal.test.mjs \+ tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.test.mjs \+ tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.test.mjs \scripts/e2e/approved-tools-resource-cleanup.test.mjs \tests/e2e/fixtures/codex-subscription/approved-tools-workflow/index.test.mjsdiff --git a/Makefile b/Makefileindex da9f35eaa..6e57d83c5 100644--- a/Makefile+++ b/Makefile@@ -276,6 +276,8 @@ minikube-build-codex-approved-tools-fixtures: ## Acquire optional Codex tools fiminikube-build-codex-approved-tools-fixtures-body:@bash scripts/minikube/require-t2-mutation-lock.sh+ @MINIKUBE_PROFILE="$(MINIKUBE_PROFILE)" scripts/minikube/build-images.sh --only=control-api+ @MINIKUBE_PROFILE="$(MINIKUBE_PROFILE)" scripts/minikube/build-images.sh --only=codex-approved-tools-control-api-e2e@MINIKUBE_PROFILE="$(MINIKUBE_PROFILE)" scripts/minikube/build-images.sh --only=codex-llm-proxy@MINIKUBE_PROFILE="$(MINIKUBE_PROFILE)" scripts/minikube/build-images.sh --only=codex-approved-tools-proxy-e2e@MINIKUBE_PROFILE="$(MINIKUBE_PROFILE)" scripts/minikube/build-images.sh --only=codex-approved-tools-mcp-e2ediff --git a/deploy/images.json b/deploy/images.jsonindex f11e801b9..4cf52cbf3 100644--- a/deploy/images.json+++ b/deploy/images.json@@ -306,6 +306,13 @@"published": true,"deployed_to_minikube": true},+ {+ "name": "codex-approved-tools-control-api-e2e",+ "path": "tests/e2e/fixtures/codex-subscription/approved-tools-oauth",+ "rooted": true,+ "published": false,+ "deployed_to_minikube": false+ },{"name": "codex-approved-tools-mcp-e2e","path": "tests/e2e/fixtures/codex-subscription/approved-tools",diff --git a/docs/architecture/codex-subscription-transport-contract.md b/docs/architecture/codex-subscription-transport-contract.mdindex 75a03a947..86e3e24a2 100644--- a/docs/architecture/codex-subscription-transport-contract.md+++ b/docs/architecture/codex-subscription-transport-contract.md@@ -119,13 +119,18 @@ ordinary unknown names retain the Host registry's authorization checks.### Selected MCP argument validation-For tasks whose provider chain includes Codex, the Host validates selected MCP+For interactive task tool loops whose provider chain includes Codex, the Host validates selected MCParguments before approval and rechecks the live schema immediately beforedispatch. Other provider chains retain server-side argument validation. Missing `$schema` uses JSON Schema 2020-12;explicit draft-07 and 2019-09 are also supported, including HTTP/HTTPS URI aliases. Unsupported dialects andunresolved references fail explicitly. Validation never coerces types, appliesdefaults, removes arguments, or loads remote references.+This validation applies to the task adapter path, including resolved discovery+calls. Workflow steps that call MCP directly retain their existing server-side+validation. The adapter checks the manager's registered catalog schema; it does+not claim to validate a distinct schema returned only by a per-user OAuth client.+Compilation and evaluation run in disposable Node workers, outside the Hostevent loop. Each operation has a two-second deadline and V8 heap/stack limits;these are not a total-process RSS guarantee. Inputs are bounded to 256 KiB perdiff --git a/docs/testing/minikube-t2-runbook.md b/docs/testing/minikube-t2-runbook.mdindex 788a18a22..2b117d869 100644--- a/docs/testing/minikube-t2-runbook.md+++ b/docs/testing/minikube-t2-runbook.md@@ -166,6 +166,37 @@ branch-profile/context variables; it never defaults to the sharedretries to 1-10, and retry delay to 0-300 seconds; empty successful`minikube docker-env` output is a hard failure.+### Codex approved-tools test fixture lifecycle++These four targets are development-only and require Node 24, the verified+branch-owned `MINIKUBE_PROFILE`, and matching explicit+`CONTROL_API_REAL_PG_CONTEXT`. Each target acquires or validates the same+mutation lease. They must not target production, staging, or a shared profile.+Use the [setup instructions](../../tests/e2e/fixtures/codex-subscription/approved-tools-setup/README.md)+for the required environment and a fresh evidence directory under the canonical+checkout's ignored `.local-notes/infra/runs/` path.++1. `make minikube-build-codex-approved-tools-fixtures` acquires seven images:+ the normal Control API, Codex proxy and custom-workflow SDK bases, plus the+ Control API OAuth, proxy, MCP and workflow test fixtures. The private body+ validates the inherited lease before building. Fixture tags never replace+ production tags. Acquisition changes the manifest timestamp, so complete the+ supported reconcile and exact-HEAD validation sequence before preparation.+2. `make minikube-run-codex-approved-tools` prepares the isolated resources,+ runs the visible deterministic Playwright journey, and restores the recorded+ Control API/proxy images and environments and cleans up owned resources and+ forwards. It can run as the T2 Playwright command after image acquisition and+ reconciliation; a successful hermetic test alone is not a runtime verdict.+3. For investigation, `make minikube-prepare-codex-approved-tools` leaves the+ test fixtures active. Finish with `make minikube-restore-codex-approved-tools`+ using the same evidence directory. Restoration verifies run ownership;+ incomplete cleanup must be resolved before another run or T2 certification.++The synthetic lane requires deterministic upstream mode. It does not establish+real-subscription interoperability or authorize real account use. The four+public targets and the guarded build body have hermetic boundary coverage in+`scripts/tests/test-minikube-mutation-boundary.sh`.+### Orphaned lock recoveryIf `PROFILE_BUSY` reports that the lock has no valid owner PID, or that a stalediff --git a/mcp-host/package-lock.json b/mcp-host/package-lock.jsonindex 6849e34da..f1f03d41c 100644--- a/mcp-host/package-lock.json+++ b/mcp-host/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-mcp-host",- "version": "0.1.327",+ "version": "0.1.328","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-mcp-host",- "version": "0.1.327",+ "version": "0.1.328","license": "SEE LICENSE IN LICENSE","dependencies": {"@anthropic-ai/sdk": "^0.32.0",diff --git a/mcp-host/package.json b/mcp-host/package.jsonindex 597b71568..5798accc1 100644--- a/mcp-host/package.json+++ b/mcp-host/package.json@@ -1,6 +1,6 @@{"name": "clerum-mcp-host",- "version": "0.1.327",+ "version": "0.1.328","description": "MCP Host - reads Host CRD and provides LLM access via OpenAI/Claude","main": "dist/main.js","engines": {diff --git a/mcp-host/src/config.codexToolPresentation.test.ts b/mcp-host/src/config.codexToolPresentation.test.tsnew file mode 100644index 000000000..5fac89362--- /dev/null+++ b/mcp-host/src/config.codexToolPresentation.test.ts@@ -0,0 +1,35 @@+import { afterEach, describe, expect, it, vi } from 'vitest'++const originalEnv = process.env++async function loadConfig(value: string | undefined) {+ vi.resetModules()+ process.env = { ...originalEnv }+ if (value === undefined) delete process.env.CODEX_TOOL_PRESENTATION+ else process.env.CODEX_TOOL_PRESENTATION = value+ return (await import('./config')).config+}++afterEach(() => {+ process.env = originalEnv+ vi.resetModules()+})++describe('CODEX_TOOL_PRESENTATION import-time configuration', () => {+ it('defaults to auto when unset', async () => {+ expect((await loadConfig(undefined)).codexToolPresentation).toBe('auto')+ })++ it.each(['auto', 'direct', 'discovery'] as const)('loads explicit %s', async value => {+ expect((await loadConfig(value)).codexToolPresentation).toBe(value)+ })++ it.each(['', 'AUTO', 'unknown', ' auto'])(+ 'refuses to import configuration with invalid mode %j',+ async value => {+ await expect(loadConfig(value)).rejects.toThrow(+ 'CODEX_TOOL_PRESENTATION must be auto, direct, or discovery'+ )+ }+ )+})diff --git a/scripts/e2e/approved-tools-connection-journal.d.mts b/scripts/e2e/approved-tools-connection-journal.d.mtsnew file mode 100644index 000000000..081480e0b--- /dev/null+++ b/scripts/e2e/approved-tools-connection-journal.d.mts@@ -0,0 +1,24 @@+export type ConnectionCaptureBinding = {+ run: string+ profile: string+ context: string+ scenario: string+ fixtureUserId: string+}+export function beginConnectionCapture(+ root: string,+ binding: ConnectionCaptureBinding+): {+ record(body: {+ id?: unknown+ connectionKey?: unknown+ displayName?: unknown+ createdBy?: unknown+ }): void+ close(): void+}+export function connectionCaptureName(scenario: string): string+export function validateConnectionCapture(+ value: unknown,+ binding: ConnectionCaptureBinding+): unknowndiff --git a/scripts/e2e/approved-tools-connection-journal.mjs b/scripts/e2e/approved-tools-connection-journal.mjsnew file mode 100644index 000000000..7b389c353--- /dev/null+++ b/scripts/e2e/approved-tools-connection-journal.mjs@@ -0,0 +1,110 @@+import fs from 'node:fs'+import path from 'node:path'++export function connectionCaptureName(scenario) {+ if (!['83', '150', '250', 'workflow'].includes(scenario))+ throw new Error('Invalid connection scenario')+ return `created-connection-${scenario}.json`+}+function validateBinding(binding) {+ if (+ Object.keys(binding).sort().join(',') !== 'context,fixtureUserId,profile,run,scenario' ||+ !/^approved-tools-[a-f0-9]{12}$/.test(binding.run) ||+ !/^clerum-[a-z0-9-]+-[a-f0-9]{7,8}$/.test(binding.profile) ||+ binding.context !== binding.profile ||+ !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(binding.fixtureUserId)+ )+ throw new Error('Invalid connection capture binding')+ connectionCaptureName(binding.scenario)+}+export function validateConnectionCapture(value, binding) {+ validateBinding(binding)+ if (+ JSON.stringify(value.binding) !== JSON.stringify(binding) ||+ value.version !== 1 ||+ value.status !== 'created' ||+ Object.keys(value).sort().join(',') !== 'binding,evidence,status,version'+ )+ throw new Error('Incomplete or foreign connection capture')+ const e = value.evidence+ if (+ !e ||+ Object.keys(e).sort().join(',') !==+ 'connectionKey,createdBy,displayName,fixtureUserId,id,scenario' ||+ e.scenario !== binding.scenario ||+ e.fixtureUserId !== binding.fixtureUserId ||+ !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(e.id) ||+ !/^codex-[a-f0-9]{16}$/.test(e.connectionKey) ||+ e.displayName !== `Codex fixture ${binding.scenario} ${binding.run}` ||+ e.createdBy !== null+ )+ throw new Error('Invalid public connection evidence')+ return e+}+export function beginConnectionCapture(root, binding) {+ validateBinding(binding)+ if (fs.realpathSync(root) !== path.resolve(root))+ throw new Error('Connection evidence path must be canonical')+ const parent = fs.lstatSync(root)+ if (+ !parent.isDirectory() ||+ parent.isSymbolicLink() ||+ parent.uid !== process.getuid() ||+ parent.mode & 0o022+ )+ throw new Error('Unsafe connection evidence directory')+ const fd = fs.openSync(+ path.join(root, connectionCaptureName(binding.scenario)),+ fs.constants.O_RDWR |+ fs.constants.O_CREAT |+ fs.constants.O_EXCL |+ fs.constants.O_NOFOLLOW |+ fs.constants.O_NONBLOCK,+ 0o600+ )+ const inode = fs.fstatSync(fd)+ const write = value => {+ const stat = fs.fstatSync(fd)+ if (+ !stat.isFile() ||+ stat.uid !== process.getuid() ||+ stat.nlink !== 1 ||+ (stat.mode & 0o777) !== 0o600 ||+ stat.dev !== inode.dev ||+ stat.ino !== inode.ino+ )+ throw new Error('Unsafe connection capture file')+ const data = Buffer.from(JSON.stringify(value) + '\n')+ if (data.length > 4096) throw new Error('Connection capture exceeds limit')+ fs.ftruncateSync(fd, 0)+ fs.writeSync(fd, data, 0, data.length, 0)+ fs.fsyncSync(fd)+ }+ try {+ write({ version: 1, binding, status: 'creation-pending' })+ } catch (error) {+ fs.closeSync(fd)+ throw error+ }+ let recorded = false+ return {+ record(body) {+ if (recorded) throw new Error('Connection already captured')+ const evidence = {+ scenario: binding.scenario,+ fixtureUserId: binding.fixtureUserId,+ id: body.id,+ connectionKey: body.connectionKey,+ displayName: body.displayName,+ createdBy: body.createdBy,+ }+ const value = { version: 1, binding, status: 'created', evidence }+ validateConnectionCapture(value, binding)+ write(value)+ recorded = true+ },+ close() {+ fs.closeSync(fd)+ },+ }+}diff --git a/scripts/e2e/approved-tools-connection-journal.test.mjs b/scripts/e2e/approved-tools-connection-journal.test.mjsnew file mode 100644index 000000000..a6bb0d7ca--- /dev/null+++ b/scripts/e2e/approved-tools-connection-journal.test.mjs@@ -0,0 +1,154 @@+import assert from 'node:assert/strict'+import fs from 'node:fs'+import { stripTypeScriptTypes } from 'node:module'+import os from 'node:os'+import path from 'node:path'+import test from 'node:test'+import { createFixtureIdentityJournal } from '../../tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.mjs'+import {+ beginConnectionCapture,+ connectionCaptureName,+ validateConnectionCapture,+} from './approved-tools-connection-journal.mjs'+import {+ ingestFixtureConnections,+ makeScenarios,+ makeWorkflowScenario,+} from './prepare-codex-approved-tools.mjs'++const run = 'approved-tools-a1b2c3d4e5f6'+const profile = 'clerum-approved-tools-a1b2c3d4'+const env = {+ NODE_ENV: 'test',+ EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE: '1',+ APPROVED_TOOLS_RUN_ID: run,+ MINIKUBE_PROFILE: profile,+ CONTROL_API_REAL_PG_CONTEXT: profile,+}+const binding = {+ run,+ profile,+ context: profile,+ scenario: '83',+ fixtureUserId: '11111111-1111-1111-1111-111111111111',+}+const body = {+ id: '22222222-2222-2222-2222-222222222222',+ connectionKey: 'codex-1234567890abcdef',+ displayName: `Codex fixture 83 ${run}`,+ createdBy: null,+}+function directory() {+ return fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), 'connection-journal-')))+}+test('intent is durable before UI creation; only public response fields survive in mode 0600', () => {+ const root = directory()+ try {+ const capture = beginConnectionCapture(root, binding)+ const filename = path.join(root, connectionCaptureName('83'))+ assert.equal(JSON.parse(fs.readFileSync(filename)).status, 'creation-pending')+ capture.record({ ...body, accessToken: 'must-not-persist' })+ capture.close()+ const raw = fs.readFileSync(filename, 'utf8')+ assert.equal(raw.includes('must-not-persist'), false)+ assert.equal(fs.statSync(filename).mode & 0o777, 0o600)+ assert.equal(validateConnectionCapture(JSON.parse(raw), binding).id, body.id)+ assert.throws(() => beginConnectionCapture(root, binding), /EEXIST/)+ assert.throws(() =>+ validateConnectionCapture(JSON.parse(raw), { ...binding, run: 'approved-tools-000000000000' })+ )+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})+test('invalid response, symlink and replaced file never supply cleanup authority', () => {+ const root = directory()+ try {+ const capture = beginConnectionCapture(root, binding)+ const filename = path.join(root, connectionCaptureName('83'))+ assert.throws(() => capture.record({ ...body, createdBy: 'foreign' }))+ assert.equal(JSON.parse(fs.readFileSync(filename)).status, 'creation-pending')+ fs.unlinkSync(filename)+ fs.writeFileSync(filename, 'replacement', { mode: 0o600 })+ assert.throws(() => capture.record(body), /Unsafe/)+ capture.close()+ assert.equal(fs.readFileSync(filename, 'utf8'), 'replacement')+ fs.unlinkSync(filename)+ fs.symlinkSync(path.join(root, 'missing'), filename)+ assert.throws(() => beginConnectionCapture(root, binding))+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})+test('restore ingests exact response once and blocks pending, foreign and conflicting evidence', () => {+ const scenarios = makeScenarios(run, [43101, 43102, 43103], 43105)+ const workflowScenario = makeWorkflowScenario(run, 43104, 43105)+ const input = {+ mode: 'deterministic',+ run,+ profile,+ context: profile,+ scenarios: [...scenarios, workflowScenario],+ }+ const journal = createFixtureIdentityJournal(input, { env })+ journal.status = 'created'+ const state = { run, profile, scenarios, workflowScenario, identityJournal: journal }+ const bound = { ...binding, fixtureUserId: journal.users[0].id }+ const evidence = { scenario: '83', fixtureUserId: bound.fixtureUserId, ...body }+ const value = { version: 1, binding: bound, status: 'created', evidence }+ let saves = 0+ const read = name => (name === connectionCaptureName('83') ? JSON.stringify(value) : null)+ ingestFixtureConnections(state, read, () => saves++)+ ingestFixtureConnections(state, read, () => saves++)+ assert.equal(saves, 1)+ assert.deepEqual(journal.connections, [evidence])+ value.evidence.id = '33333333-3333-3333-3333-333333333333'+ assert.throws(() => ingestFixtureConnections(state, read, () => saves++), /Conflicting/)+ value.status = 'creation-pending'+ assert.throws(() => ingestFixtureConnections(state, read, () => saves++), /Incomplete/)+ assert.equal(saves, 1)+})+test('real page createGrant callback persists the response before later UI assertions and retains string return', async () => {+ const filename = path.resolve('tests/e2e/playwright/pages/codex-subscription.ts')+ // Execute the real method with unit adapters; no browser or Playwright dependency+ // is needed in the mcp-host CI lane that owns these lifecycle contracts.+ const source = fs.readFileSync(filename, 'utf8')+ const method = source.slice(+ source.indexOf(' async createGrant('),+ source.indexOf(' async openGrant(')+ )+ assert.ok(method.includes('onCreated'))+ const stripped = stripTypeScriptTypes(`class SecretsLlmSubscriptionsPage { ${method} }`)+ const SecretsLlmSubscriptionsPage = new Function(+ 'expect',+ `${stripped}; return SecretsLlmSubscriptionsPage`+ )(value => ({+ toBe: expected => assert.equal(value, expected),+ toBeTruthy: () => assert.ok(value),+ }))+ const root = directory()+ try {+ const capture = beginConnectionCapture(root, binding)+ const page = {+ getByRole: () => ({ click: async () => {} }),+ getByLabel: () => ({ fill: async () => {} }),+ waitForResponse: () => Promise.resolve({ status: () => 201, json: async () => body }),+ }+ const subscriptions = new SecretsLlmSubscriptionsPage()+ subscriptions.page = page+ subscriptions.expectConnectModal = async () => {+ const stored = JSON.parse(fs.readFileSync(path.join(root, connectionCaptureName('83'))))+ assert.equal(stored.evidence.id, body.id)+ throw Error('later UI assertion failed')+ }+ await assert.rejects(+ subscriptions.createGrant(body.displayName, metadata => capture.record(metadata)),+ /later UI assertion failed/+ )+ capture.close()+ subscriptions.expectConnectModal = async () => {}+ assert.equal(await subscriptions.createGrant(body.displayName), body.connectionKey)+ } finally {+ fs.rmSync(root, { recursive: true, force: true })+ }+})diff --git a/scripts/e2e/approved-tools-control-api-lifecycle.mjs b/scripts/e2e/approved-tools-control-api-lifecycle.mjsnew file mode 100644index 000000000..5d3226d00--- /dev/null+++ b/scripts/e2e/approved-tools-control-api-lifecycle.mjs@@ -0,0 +1,213 @@+export const controlApiFixtureImage = 'clerum/codex-approved-tools-control-api-e2e:test'+export const controlApiRunAnnotation = 'evenfire.ai/codex-tools-fixture-run'+export const controlApiFlags = [+ 'NODE_ENV',+ 'EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE',+ 'APPROVED_TOOLS_RUN_ID',+ 'MINIKUBE_PROFILE',+ 'CONTROL_API_REAL_PG_CONTEXT',+]+const runPattern = /^approved-tools-[a-f0-9]{12}$/++function validateImage(image, policy) {+ if (+ !(+ image === controlApiFixtureImage ||+ /^(clerum\/control-api|ghcr\.io\/evenfire-ai\/control-api)(:[a-zA-Z0-9._-]+|@sha256:[a-f0-9]{64})$/.test(+ image+ )+ ) ||+ !['Always', 'Never', 'IfNotPresent'].includes(policy)+ )+ throw new Error('Invalid Control API image')+}+function validateEnv(env, profile) {+ if (+ !Array.isArray(env) ||+ env.length !== controlApiFlags.length ||+ new Set(env.map(e => e.name)).size !== controlApiFlags.length+ )+ throw new Error('Invalid Control API environment')+ for (const e of env) {+ if (+ !controlApiFlags.includes(e.name) ||+ Object.keys(e).length !== 2 ||+ !(+ e.$patch === 'delete' ||+ (e.name === 'NODE_ENV'+ ? ['test', 'production', 'development'].includes(e.value)+ : e.name === 'EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE'+ ? e.value === '1'+ : e.name === 'APPROVED_TOOLS_RUN_ID'+ ? runPattern.test(e.value)+ : e.value === profile)+ )+ )+ throw new Error('Invalid Control API environment')+ }+}+export function controlApiPatch({ metadata, image, imagePullPolicy, env, run }) {+ return {+ metadata: { uid: metadata.uid, resourceVersion: metadata.resourceVersion },+ spec: {+ template: {+ metadata: { annotations: { [controlApiRunAnnotation]: run } },+ spec: { containers: [{ name: 'control-api', image, imagePullPolicy, env }] },+ },+ },+ }+}+export function validateControlApiPatch(patch, profile) {+ if (+ !/^[a-zA-Z0-9-]{1,128}$/.test(patch?.metadata?.uid ?? '') ||+ !/^[0-9]{1,32}$/.test(patch?.metadata?.resourceVersion ?? '')+ )+ throw new Error('Invalid Control API object binding')+ const c = patch?.spec?.template?.spec?.containers?.[0]+ const run = patch?.spec?.template?.metadata?.annotations?.[controlApiRunAnnotation]+ if (!(run === null || runPattern.test(run))) throw new Error('Invalid Control API run binding')+ validateImage(c?.image, c?.imagePullPolicy)+ validateEnv(c?.env, profile)+ if (+ JSON.stringify(patch) !==+ JSON.stringify(controlApiPatch({ metadata: patch.metadata, ...c, run }))+ )+ throw new Error('Unexpected Control API patch fields')+ if (+ c.image === controlApiFixtureImage &&+ (run === null ||+ c.imagePullPolicy !== 'Never' ||+ JSON.stringify(c.env) !== JSON.stringify(controlApiFixtureEnv(run, profile)))+ )+ throw new Error('Incomplete Control API fixture guards')+ if (c.image !== controlApiFixtureImage && run !== null)+ throw new Error('Unexpected original Control API run binding')+}+export function controlApiFixtureEnv(run, profile) {+ return controlApiFlags.map(name => ({+ name,+ value:+ name === 'NODE_ENV'+ ? 'test'+ : name === 'EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE'+ ? '1'+ : name === 'APPROVED_TOOLS_RUN_ID'+ ? run+ : profile,+ }))+}+export function captureControlApi(deployment, profile) {+ const c = deployment?.spec?.template?.spec?.containers?.find(c => c.name === 'control-api')+ if (+ !c ||+ c.image === controlApiFixtureImage ||+ deployment.spec.template.metadata?.annotations?.[controlApiRunAnnotation] !== undefined ||+ (c.env ?? []).some(e =>+ ['EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE', 'APPROVED_TOOLS_RUN_ID'].includes(e.name)+ )+ )+ throw new Error('Control API already has test ownership')+ const affected = (c.env ?? []).filter(e => controlApiFlags.includes(e.name))+ if (new Set(affected.map(e => e.name)).size !== affected.length)+ throw new Error('Duplicate Control API environment binding')+ const snapshot = {+ metadata: {+ uid: deployment.metadata.uid,+ resourceVersion: deployment.metadata.resourceVersion,+ },+ image: c.image,+ imagePullPolicy: c.imagePullPolicy,+ env: controlApiFlags.map(+ name => c.env?.find(e => e.name === name) ?? { name, $patch: 'delete' }+ ),+ }+ validateControlApiPatch(controlApiPatch({ ...snapshot, run: null }), profile)+ return snapshot+}+export async function restoreControlApi({ state, profile, get, patch, wait }) {+ const original = state.controlApi+ if (!original) throw new Error('Missing original Control API snapshot')+ validateControlApiPatch(controlApiPatch({ ...original, run: null }), profile)+ const live = await get()+ const c = live?.spec?.template?.spec?.containers?.find(c => c.name === 'control-api')+ const run = live?.spec?.template?.metadata?.annotations?.[controlApiRunAnnotation]+ if (live?.metadata?.uid !== original.metadata.uid || !c)+ throw new Error('Control API deployment ownership changed')+ if (c.image === controlApiFixtureImage) {+ if (run !== state.run) throw new Error('Control API fixture run binding changed')+ await patch(controlApiPatch({ ...original, metadata: live.metadata, run: null }))+ } else {+ if (+ c.image !== original.image ||+ c.imagePullPolicy !== original.imagePullPolicy ||+ run !== undefined+ )+ throw new Error('Control API original deployment does not match')+ const env = controlApiFlags.map(+ name => c.env?.find(e => e.name === name) ?? { name, $patch: 'delete' }+ )+ if (JSON.stringify(env) !== JSON.stringify(original.env))+ throw new Error('Control API original environment does not match')+ }+ await wait()+}++// A failed identity cleanup must not leave the fixture API installed. A later+// owned restore may reinstall it temporarily, but only over the recorded+// original deployment after resource cleanup has completed.+export async function recoverControlApiForCleanup({ state, profile, get, patch, wait, verify }) {+ if (+ !state.identitySeedStarted ||+ state.profile !== profile ||+ !runPattern.test(state.run) ||+ !state.controlApi ||+ !state.identityJournal ||+ state.identityJournal.run !== state.run ||+ state.identityJournal.profile !== profile ||+ state.identityJournal.context !== profile ||+ !['creation-pending', 'created', 'cleanup-pending', 'recovery-required', 'cleaned'].includes(+ state.identityJournal.status+ )+ )+ throw new Error('Invalid identity cleanup recovery binding')+ if (!Array.isArray(state.resources) || state.resources.some(entry => entry.status !== 'deleted'))+ throw new Error('Resources remain before API cleanup recovery')+ if (state.identityJournal.status === 'cleaned') return false+ validateControlApiPatch(controlApiPatch({ ...state.controlApi, run: null }), profile)+ const live = await get()+ const c = live?.spec?.template?.spec?.containers?.find(c => c.name === 'control-api')+ if (live?.metadata?.uid !== state.controlApi.metadata.uid || !c)+ throw new Error('Control API deployment ownership changed')+ const run = live.spec.template.metadata?.annotations?.[controlApiRunAnnotation]+ if (c.image === controlApiFixtureImage) {+ if (run !== state.run) throw new Error('Control API fixture run binding changed')+ const affected = (c.env ?? []).filter(e => controlApiFlags.includes(e.name))+ const ordered = controlApiFlags.map(name => affected.find(e => e.name === name))+ if (+ affected.length !== controlApiFlags.length ||+ JSON.stringify(ordered) !== JSON.stringify(controlApiFixtureEnv(state.run, profile)) ||+ c.imagePullPolicy !== 'Never'+ )+ throw new Error('Control API fixture environment changed')+ } else {+ const current = captureControlApi(live, profile)+ if (+ current.image !== state.controlApi.image ||+ current.imagePullPolicy !== state.controlApi.imagePullPolicy ||+ JSON.stringify(current.env) !== JSON.stringify(state.controlApi.env)+ )+ throw new Error('Control API original deployment does not match cleanup recovery snapshot')+ const request = controlApiPatch({+ metadata: live.metadata,+ image: controlApiFixtureImage,+ imagePullPolicy: 'Never',+ env: controlApiFixtureEnv(state.run, profile),+ run: state.run,+ })+ validateControlApiPatch(request, profile)+ await patch(request)+ }+ await wait()+ await verify()+ return true+}diff --git a/scripts/e2e/approved-tools-control-api-lifecycle.test.mjs b/scripts/e2e/approved-tools-control-api-lifecycle.test.mjsnew file mode 100644index 000000000..b342eb697--- /dev/null+++ b/scripts/e2e/approved-tools-control-api-lifecycle.test.mjs@@ -0,0 +1,364 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import {+ captureControlApi,+ controlApiFixtureEnv,+ controlApiFixtureImage,+ controlApiPatch,+ controlApiRunAnnotation,+ recoverControlApiForCleanup,+ restoreControlApi,+ validateControlApiPatch,+} from './approved-tools-control-api-lifecycle.mjs'+import {+ controlApiMarkerCheck,+ restoreOwnedFixture,+ validateKubectlArgs,+} from './prepare-codex-approved-tools.mjs'++const profile = 'clerum-approved-tools-a1b2c3d4'+const run = 'approved-tools-a1b2c3d4e5f6'+function deployment() {+ return {+ metadata: { uid: 'api-uid', resourceVersion: '123' },+ spec: {+ template: {+ spec: {+ containers: [+ {+ name: 'control-api',+ image: 'clerum/control-api:test',+ imagePullPolicy: 'Never',+ env: [+ { name: 'NODE_ENV', value: 'production' },+ { name: 'UNRELATED', value: 'preserved' },+ ],+ },+ ],+ },+ },+ },+ }+}+function fixture() {+ const d = deployment()+ d.spec.template.metadata = { annotations: { [controlApiRunAnnotation]: run } }+ d.spec.template.spec.containers[0].image = controlApiFixtureImage+ d.spec.template.spec.containers[0].env = controlApiFixtureEnv(run, profile)+ return d+}+test('snapshot captures only restorable affected bindings and refuses unsafe originals', () => {+ const original = captureControlApi(deployment(), profile)+ assert.equal(JSON.stringify(original).includes('UNRELATED'), false)+ for (const mutate of [+ d => {+ d.spec.template.spec.containers[0].image = 'foreign/image:test'+ },+ d => {+ d.spec.template.spec.containers[0].env[0] = {+ name: 'NODE_ENV',+ valueFrom: { secretKeyRef: { name: 'secret', key: 'env' } },+ }+ },+ d => {+ d.metadata.resourceVersion = ''+ },+ ]) {+ const d = deployment()+ mutate(d)+ assert.throws(() => captureControlApi(d, profile))+ }+})+test('kubectl permits only the exact guarded Control API patch', () => {+ const patch = controlApiPatch({+ metadata: deployment().metadata,+ image: controlApiFixtureImage,+ imagePullPolicy: 'Never',+ env: controlApiFixtureEnv(run, profile),+ run,+ })+ const args = p => [+ `--context=${profile}`,+ '--request-timeout=30s',+ '-n',+ 'control-plane',+ 'patch',+ 'deployment/control-api',+ '--type=strategic',+ '-p',+ JSON.stringify(p),+ ]+ assert.doesNotThrow(() => validateKubectlArgs(args(patch), profile))+ for (const mutate of [+ p => {+ p.metadata.resourceVersion = ''+ },+ p => {+ p.spec.replicas = 0+ },+ p => {+ p.spec.template.spec.containers[0].env.pop()+ },+ p => {+ p.spec.template.spec.containers[0].env[0].value = 'production'+ },+ p => {+ p.spec.template.metadata.annotations[controlApiRunAnnotation] = null+ },+ ]) {+ const p = structuredClone(patch)+ mutate(p)+ assert.throws(() => validateKubectlArgs(args(p), profile))+ }+})+test('restore uses current resourceVersion, original affected env, and waits for Ready', async () => {+ const original = captureControlApi(deployment(), profile)+ const live = fixture()+ live.metadata.resourceVersion = '124'+ const calls = []+ await restoreControlApi({+ state: { run, controlApi: original },+ profile,+ get: () => live,+ patch: p => {+ validateControlApiPatch(p, profile)+ calls.push(p)+ },+ wait: () => calls.push('ready'),+ })+ assert.equal(calls[0].metadata.resourceVersion, '124')+ assert.deepEqual(calls[0].spec.template.spec.containers[0].env, original.env)+ assert.equal(calls[1], 'ready')+ live.spec.template.metadata.annotations[controlApiRunAnnotation] = 'approved-tools-000000000000'+ await assert.rejects(+ restoreControlApi({+ state: { run, controlApi: original },+ profile,+ get: () => live,+ patch: () => assert.fail(),+ wait: () => assert.fail(),+ }),+ /binding changed/+ )+})+test('cleanup orders resources then identities then API and restores API despite failures', async () => {+ for (const fail of [null, 'resources', 'identities', 'api']) {+ const calls = []+ const state = {+ profile,+ worktree: '/owned',+ head: 'head',+ run,+ proxyUid: 'proxy',+ originalProxyImage: 'clerum/codex-llm-proxy:test',+ identitySeedStarted: true,+ identityJournal: { status: 'created' },+ controlApi: {},+ resources: [{}],+ forwards: [],+ }+ const adapters = {+ state,+ profile,+ worktree: '/owned',+ head: 'head',+ getDeployment: () => ({+ metadata: { uid: 'proxy' },+ spec: {+ template: {+ spec: { containers: [{ name: 'codex-llm-proxy', image: state.originalProxyImage }] },+ },+ },+ }),+ waitProxyRollout: () => {},+ cleanupResources: () => {+ calls.push('resources')+ if (fail === 'resources') throw Error('resources')+ },+ cleanupIdentities: () => {+ calls.push('identities')+ if (fail === 'identities') throw Error('identities')+ state.identityJournal.status = 'cleaned'+ },+ restoreApi: () => {+ calls.push('api')+ if (fail === 'api') throw Error('api')+ },+ }+ if (fail) await assert.rejects(restoreOwnedFixture(adapters))+ else await restoreOwnedFixture(adapters)+ assert.deepEqual(+ calls,+ fail === 'resources' ? ['resources', 'api'] : ['resources', 'identities', 'api']+ )+ assert.equal(state.restored, fail === null)+ }+})++test('live marker probe is allowlisted exactly and validates the active run and process', () => {+ const args = source => [+ `--context=${profile}`,+ '--request-timeout=30s',+ '-n',+ 'control-plane',+ 'exec',+ 'deployment/control-api',+ '--',+ 'node',+ '-e',+ source,+ ]+ assert.doesNotThrow(() => validateKubectlArgs(args(controlApiMarkerCheck), profile))+ assert.throws(() =>+ validateKubectlArgs(args(controlApiMarkerCheck + ';process.exit(0)'), profile)+ )+ const probe = new Function('require', 'process', controlApiMarkerCheck)+ const marker = { run, profile, pid: 1 }+ const env = Object.fromEntries(controlApiFixtureEnv(run, profile).map(e => [e.name, e.value]))+ env.KUBERNETES_SERVICE_HOST = '10.0.0.1'+ let output+ const proc = {+ env,+ kill: pid => assert.equal(pid, 1),+ stdout: {+ write: value => {+ output = JSON.parse(value)+ },+ },+ }+ const requireFixture = () => ({+ readFileSync: filename => {+ assert.equal(filename, '/tmp/approved-tools-oauth-active.json')+ return JSON.stringify(marker)+ },+ })+ probe(requireFixture, proc)+ assert.deepEqual(output, marker)+ marker.run = 'approved-tools-000000000000'+ assert.throws(() => probe(requireFixture, proc), /Invalid fixture marker/)+ marker.run = run+ marker.pid = 2+ assert.throws(() => probe(requireFixture, proc), /Invalid fixture marker/)+})++function recoveryState() {+ return {+ profile,+ worktree: '/owned',+ head: 'head',+ run,+ proxyUid: 'proxy',+ originalProxyImage: 'clerum/codex-llm-proxy:test',+ identitySeedStarted: true,+ identityJournal: { run, profile, context: profile, status: 'created' },+ controlApi: captureControlApi(deployment(), profile),+ resources: [],+ forwards: [],+ }+}+test('identity cleanup retry reinstalls the guarded API and restores it after both failed and successful attempts', async () => {+ const state = recoveryState()+ let live = fixture()+ let attempt = 0+ const mutations = []+ const api = {+ state,+ profile,+ get: () => live,+ patch: p => {+ validateControlApiPatch(p, profile)+ assert.equal(p.metadata.resourceVersion, live.metadata.resourceVersion)+ mutations.push(p.spec.template.spec.containers[0].image)+ live = {+ metadata: {+ ...p.metadata,+ resourceVersion: String(Number(p.metadata.resourceVersion) + 1),+ },+ spec: structuredClone(p.spec),+ }+ const c = live.spec.template.spec.containers[0]+ c.env = c.env.filter(e => e.$patch !== 'delete')+ if (live.spec.template.metadata.annotations[controlApiRunAnnotation] === null)+ delete live.spec.template.metadata.annotations[controlApiRunAnnotation]+ },+ wait: () => {},+ verify: () => assert.equal(live.spec.template.spec.containers[0].image, controlApiFixtureImage),+ }+ const adapters = {+ state,+ profile,+ worktree: '/owned',+ head: 'head',+ getDeployment: () => ({+ metadata: { uid: 'proxy' },+ spec: {+ template: {+ spec: { containers: [{ name: 'codex-llm-proxy', image: state.originalProxyImage }] },+ },+ },+ }),+ waitProxyRollout: () => {},+ cleanupResources: () => {},+ cleanupIdentities: async () => {+ if (!(await recoverControlApiForCleanup(api))) return+ if (attempt++ === 0) throw Error('identity cleanup interrupted')+ state.identityJournal.status = 'cleaned'+ },+ restoreApi: () => restoreControlApi(api),+ }+ await assert.rejects(restoreOwnedFixture(adapters), /identity cleanup interrupted/)+ assert.equal(state.restored, false)+ assert.equal(live.spec.template.spec.containers[0].image, state.controlApi.image)+ await restoreOwnedFixture(adapters)+ assert.equal(state.restored, true)+ assert.deepEqual(mutations, [+ state.controlApi.image,+ controlApiFixtureImage,+ state.controlApi.image,+ ])+ await restoreOwnedFixture(adapters)+ assert.equal(mutations.length, 3)+})+test('recovery refuses changed original deployment, foreign run and unfinished resources before mutation', async () => {+ for (const mutate of [+ (s, d) => {+ d.metadata.uid = 'foreign'+ },+ (s, d) => {+ d.spec.template.spec.containers[0].image = 'clerum/control-api:other'+ },+ (s, d) => {+ d.spec.template.spec.containers[0].imagePullPolicy = 'Always'+ },+ (s, d) => {+ d.spec.template.spec.containers[0].env[0].value = 'development'+ },+ (s, d) => {+ d.spec.template.metadata = {+ annotations: { [controlApiRunAnnotation]: 'approved-tools-000000000000' },+ }+ },+ s => {+ s.resources = [{ status: 'created' }]+ },+ s => {+ s.identityJournal.run = 'approved-tools-000000000000'+ },+ ]) {+ const state = recoveryState()+ const live = deployment()+ mutate(state, live)+ const calls = []+ await assert.rejects(+ recoverControlApiForCleanup({+ state,+ profile,+ get: () => live,+ patch: () => calls.push('patch'),+ wait: () => calls.push('wait'),+ verify: () => calls.push('verify'),+ })+ )+ assert.deepEqual(calls, [])+ }+})diff --git a/scripts/e2e/approved-tools-image-proof.mjs b/scripts/e2e/approved-tools-image-proof.mjsindex fe89c591e..8676b5acd 100644--- a/scripts/e2e/approved-tools-image-proof.mjs+++ b/scripts/e2e/approved-tools-image-proof.mjs@@ -1,13 +1,8 @@// Provenance proof for the optional Codex approved-tools fixture images.//-// The fixture lane swaps the running codex-llm-proxy Deployment onto a locally-// built fixture image, and the workflow scenario runs a locally built-// coordinator fixture. Those refs are acquired by-// `make minikube-build-codex-approved-tools-fixtures`, which runs-// scripts/minikube/build-images.sh five times with --only. Each run rewrites-// deploy/minikube/.image-manifest.json, two of the fixtures are BUILT FROM the-// normal proxy image and the normal workflow coordinator image, and any of the-// five can still be the one an earlier commit built.+// The fixture lane uses locally built Control API, proxy, MCP and coordinator+// images. The acquisition target builds each base and fixture with --only,+// preserving source revisions and exact derived-base IDs across partial builds.//// A ref that merely EXISTS is not proof that the delegation test exercised the// code under review, and a fixture built from a stale base embeds that stale@@ -47,17 +42,18 @@ function localImageRef(name) {return localRef(entry)}-// The three fixture refs the prepare step swaps in, and the two normal images-// they are built from. All five must belong to the reviewed commit.+// Every fixture and its base must belong to the reviewed commit.export const FIXTURE_IMAGES = Object.freeze([localImageRef('codex-approved-tools-mcp-e2e'),localImageRef('codex-approved-tools-proxy-e2e'),localImageRef('codex-approved-tools-workflow-e2e'),+ localImageRef('codex-approved-tools-control-api-e2e'),])export const BASE_IMAGES = Object.freeze([localImageRef('codex-llm-proxy'),localImageRef('workflow-custom-sdk-e2e'),+ localImageRef('control-api'),])export const EXPECTED_IMAGES = Object.freeze([...FIXTURE_IMAGES, ...BASE_IMAGES])@@ -72,6 +68,7 @@ export const DERIVED_FIXTURES = Object.freeze([ref: localImageRef('codex-approved-tools-workflow-e2e'),base: localImageRef('workflow-custom-sdk-e2e'),},+ { ref: localImageRef('codex-approved-tools-control-api-e2e'), base: localImageRef('control-api') },])function isRecord(value) {diff --git a/scripts/e2e/approved-tools-image-proof.test.mjs b/scripts/e2e/approved-tools-image-proof.test.mjsindex 4a5870804..f37d59188 100644--- a/scripts/e2e/approved-tools-image-proof.test.mjs+++ b/scripts/e2e/approved-tools-image-proof.test.mjs@@ -6,12 +6,13 @@// digest is generated, not copied.//// Real-builder coverage lives in scripts/tests/test-minikube-docker-cli-env.sh:-// sequential partial builds, both derived-image bindings, stale/missing images,+// sequential partial builds, derived-image bindings, stale/missing images,// profile mismatch, malformed prior JSON, and preservation of a good manifest// when late inventory queries fail. Neither suite certifies a live deployment.import assert from 'node:assert/strict'import { createHash } from 'node:crypto'import test from 'node:test'+import { publishedImages, pullInGhcrMode, minikubeVerifyRefs } from '../release/images-manifest.mjs'import {BASE_IMAGES,DERIVED_FIXTURES,@@ -61,7 +62,7 @@ function certify({ profile = PROFILE, sourceHead = HEAD, manifest, images }) {return buildApprovedToolsImageProof({ profile, sourceHead, manifest, images })}-test('certifies the three fixture refs and both base refs at the reviewed commit', () => {+test('certifies every fixture and base ref at the reviewed commit', () => {const images = recordedImages()const proof = certify({ manifest: manifestFor(images), images: observedEntries(images) })assert.deepEqual(Object.keys(proof.images).sort(), [...EXPECTED_IMAGES].sort())@@ -239,7 +240,7 @@ test('refuses a ref with no recorded source revision', () => {test('refuses a fixture or a base that was built at a different commit', () => {const images = recordedImages()- for (const stale of [PROXY_FIXTURE, WORKFLOW_FIXTURE, PROXY_BASE, WORKFLOW_BASE]) {+ for (const stale of EXPECTED_IMAGES) {const manifest = manifestFor(images)manifest.sourceRevisions[stale] = OTHER_HEADassert.throws(@@ -274,3 +275,34 @@ test('refuses a fixture whose recorded base is absent, different or no longer cu/IMAGE_PROOF_BASE_MISMATCH/)})++// The OAuth image is an optional derived fixture, but mandatory for this lane.+test('requires the Control API OAuth fixture and its current exact base', () => {+ const ref = 'clerum/codex-approved-tools-control-api-e2e:test'+ const base = 'clerum/control-api:test'+ assert.ok(FIXTURE_IMAGES.includes(ref))+ assert.ok(BASE_IMAGES.includes(base))+ assert.ok(DERIVED_FIXTURES.some(entry => entry.ref === ref && entry.base === base))+ const images = recordedImages()+ for (const missing of [ref, base]) {+ assert.throws(+ () => certify({ manifest: manifestFor(images), images: observedEntries(images).filter(entry => entry.ref !== missing) }),+ /IMAGE_PROOF_IMAGE_MISSING/+ )+ }+ const manifest = manifestFor(images)+ manifest.derivedFrom[ref].id = digest('previous-control-api-base')+ assert.throws(+ () => certify({ manifest, images: observedEntries(images) }),+ /IMAGE_PROOF_BASE_MISMATCH/+ )+})++test('keeps the OAuth fixture out of publication, pulls and default runtime verification', () => {+ const name = 'codex-approved-tools-control-api-e2e'+ const ref = `clerum/${name}:test`+ assert.ok(!publishedImages().some(image => image.name === name))+ assert.ok(!pullInGhcrMode().some(image => image.name === name))+ assert.ok(!minikubeVerifyRefs({ mode: 'local' }).includes(ref))+ assert.ok(!minikubeVerifyRefs({ mode: 'ghcr', tag: HEAD, includeE2eFixtures: true }).includes(ref))+})diff --git a/scripts/e2e/approved-tools-restoration.test.mjs b/scripts/e2e/approved-tools-restoration.test.mjsindex 49d11029c..6a7f30f08 100644--- a/scripts/e2e/approved-tools-restoration.test.mjs+++ b/scripts/e2e/approved-tools-restoration.test.mjs@@ -1,8 +1,39 @@import assert from 'node:assert/strict'import { test } from 'node:test'-import { restoreOwnedFixture, runnerPhaseBudgetMs } from './prepare-codex-approved-tools.mjs'+import {+ parseIdentityJournal,+ restoreOwnedFixture,+ runnerPhaseBudgetMs,+} from './prepare-codex-approved-tools.mjs'const run = 'approved-tools-123456789abc'+test('identity response must match the durable intent and expected terminal status', () => {+ const expected = {+ version: 1,+ mode: 'deterministic',+ run,+ profile: 'owned',+ context: 'owned',+ users: [{ id: 'user' }],+ team: { id: 'team' },+ grants: { agents: ['agent'] },+ status: 'creation-pending',+ }+ const result = { ...expected, status: 'created' }+ const output = `service startup\n${JSON.stringify({ e2eIdentity: result })}\n`+ assert.deepEqual(parseIdentityJournal(output, expected, 'created'), result)+ for (const changed of [+ { ...result, run: 'foreign' },+ { ...result, users: [] },+ { ...result, status: 'recovery-required' },+ { ...result, extra: 'unexpected' },+ ])+ assert.throws(+ () => parseIdentityJournal(JSON.stringify({ e2eIdentity: changed }), expected, 'created'),+ /does not match/+ )+ assert.throws(() => parseIdentityJournal('no result', expected, 'created'), /does not match/)+})function fixture() {const state = {profile: 'test-profile',@@ -56,6 +87,22 @@ test('same owned run restores after a commit change and keeps an audit record',assert.deepEqual(f.state.headAudit, { createdHead: 'old', restoredAtHead: 'new' })})+test('a started identity seed prevents restored success until its cleanup completes', async () => {+ const f = fixture()+ f.state.identitySeedStarted = true+ f.state.identityJournal = { status: 'creation-pending' }+ await assert.rejects(restoreOwnedFixture(f.options), /Identity cleanup adapter is required/)+ assert.equal(f.state.restored, false)+ assert.ok(f.events.includes('cleanup2'))+ await restoreOwnedFixture({+ ...f.options,+ cleanupIdentities: () => {+ f.state.identityJournal.status = 'cleaned'+ },+ })+ assert.equal(f.state.restored, true)+})+for (const mismatch of ['uid', 'run', 'missing-run', 'image']) {test(`a ${mismatch} mismatch refuses the proxy write but cleans every owned forward`, async () => {const f = fixture()diff --git a/scripts/e2e/prepare-codex-approved-tools.mjs b/scripts/e2e/prepare-codex-approved-tools.mjsindex a6e2149ec..e4342694c 100644--- a/scripts/e2e/prepare-codex-approved-tools.mjs+++ b/scripts/e2e/prepare-codex-approved-tools.mjs@@ -4,6 +4,23 @@ import fs from 'node:fs'import net from 'node:net'import path from 'node:path'import { fileURLToPath, pathToFileURL } from 'node:url'+import {+ createFixtureIdentityJournal,+ recordFixtureConnection,+} from '../../tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.mjs'+import {+ connectionCaptureName,+ validateConnectionCapture,+} from './approved-tools-connection-journal.mjs'+import {+ captureControlApi,+ controlApiFixtureEnv,+ controlApiFixtureImage,+ controlApiPatch,+ recoverControlApiForCleanup,+ restoreControlApi,+ validateControlApiPatch,+} from './approved-tools-control-api-lifecycle.mjs'import { buildApprovedToolsImageProof } from './approved-tools-image-proof.mjs'import {cleanupJournaledFixtureResources,@@ -17,6 +34,7 @@ const repo = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..')const sizes = [83, 150, 250]const fixtureImage = 'clerum/codex-approved-tools-mcp-e2e:test'const proxyImage = 'clerum/codex-approved-tools-proxy-e2e:test'+export const controlApiMarkerCheck = `const fs = require('node:fs'); const marker = JSON.parse(fs.readFileSync('/tmp/approved-tools-oauth-active.json', 'utf8')); if (marker.pid !== 1 || process.env.NODE_ENV !== 'test' || process.env.EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE !== '1' || marker.run !== process.env.APPROVED_TOOLS_RUN_ID || marker.profile !== process.env.MINIKUBE_PROFILE || marker.profile !== process.env.CONTROL_API_REAL_PG_CONTEXT || !process.env.KUBERNETES_SERVICE_HOST) throw Error('Invalid fixture marker'); process.kill(marker.pid, 0); process.stdout.write(JSON.stringify(marker))`const proxyRunAnnotation = 'evenfire.ai/codex-tools-fixture-run'const workflowImage = 'clerum/workflow-custom-sdk-e2e:approved-tools-test'const workflowFeatureCheck = `process.stdout.write(JSON.stringify(process.env.WRC_ENABLE_CUSTOM_COORDINATOR_IMAGE === 'true' && process.env.WRC_REQUIRE_COORDINATOR_IMAGE_DIGEST === 'false' && (process.env.WRC_ALLOWED_COORDINATOR_IMAGE_PREFIXES || '').split(',').some(prefix => prefix.trim() && '${workflowImage}'.startsWith(prefix.trim()))))`@@ -438,7 +456,9 @@ export function validateKubectlArgs(args, profile, { input, resourceCleanup } =operation[4] === '-o' &&operation[5] === 'json' &&((namespace === 'control-plane' &&- ['deployment/codex-llm-proxy', 'service/codex-llm-proxy'].includes(resource)) ||+ ['deployment/codex-llm-proxy', 'service/codex-llm-proxy', 'deployment/control-api'].includes(+ resource+ )) ||(namespace === 'mcp-host' && resource === 'configmap/mcp-host-config')))return args@@ -447,11 +467,23 @@ export function validateKubectlArgs(args, profile, { input, resourceCleanup } =operation[5] === '--timeout=180s' &&((verb === 'rollout' && resource === 'status') ||(verb === 'wait' && resource === '--for=create')) &&- ((namespace === 'control-plane' && operation[4] === 'deployment/codex-llm-proxy') ||+ ((namespace === 'control-plane' &&+ ['deployment/codex-llm-proxy', 'deployment/control-api'].includes(operation[4])) ||(namespace === 'mcp-server' &&/^deployment\/approved-tools-[a-f0-9]{12}-mcp-(83|150|250|workflow)$/.test(operation[4]))))return args+ if (+ namespace === 'control-plane' &&+ verb === 'patch' &&+ resource === 'deployment/control-api' &&+ operation.length === 7 &&+ operation[4] === '--type=strategic' &&+ operation[5] === '-p'+ ) {+ validateControlApiPatch(JSON.parse(operation[6]), profile)+ return args+ }if (namespace === 'control-plane' &&verb === 'patch' &&@@ -533,6 +565,8 @@ export function validateKubectlArgs(args, profile, { input, resourceCleanup } =operation[5] === 'node' &&operation[6] === '-e') {+ if (resource === 'deployment/control-api' && operation[7] === controlApiMarkerCheck)+ return argsif (resource === 'deployment/workflow-recipes' && operation[7] === workflowFeatureCheck)return argsconst keys =@@ -709,6 +743,72 @@ async function waitHttp(url, accept) {// state.headAudit. Proxy patching keeps its UID/image guards; forward cleanup// uses the ownership-checked cleanup path and runs even when the proxy step// fails. restored is set only when proxy and every cleanup complete.+export function parseIdentityJournal(output, expected, status) {+ if (typeof output !== 'string' || Buffer.byteLength(output) > 256 * 1024)+ throw new Error('Invalid identity result size')+ let result+ for (const line of output.split('\n')) {+ try {+ const value = JSON.parse(line)+ if (value?.e2eIdentity) result = value.e2eIdentity+ } catch {+ /* Service logs are not identity operation results. */+ }+ }+ const fields = [+ 'version',+ 'mode',+ 'run',+ 'profile',+ 'context',+ 'users',+ 'team',+ 'grants',+ 'connections',+ ]+ if (+ !result ||+ result.status !== status ||+ fields.some(key => JSON.stringify(result[key]) !== JSON.stringify(expected[key])) ||+ Object.keys(result).some(key => ![...fields, 'status', 'cleanupOutcome'].includes(key))+ )+ throw new Error('Identity operation result does not match recorded intent')+ return result+}++export function ingestFixtureConnections(state, read, save) {+ const input = {+ mode: 'deterministic',+ run: state.run,+ profile: state.profile,+ context: state.profile,+ scenarios: [...state.scenarios, state.workflowScenario],+ }+ const env = Object.fromEntries(+ controlApiFixtureEnv(state.run, state.profile).map(e => [e.name, e.value])+ )+ for (const scenario of ['83', '150', '250', 'workflow']) {+ const raw = read(connectionCaptureName(scenario))+ if (raw === null) continue+ const binding = {+ run: state.run,+ profile: state.profile,+ context: state.profile,+ scenario,+ fixtureUserId: state.identityJournal.users[0].id,+ }+ const evidence = validateConnectionCapture(JSON.parse(raw), binding)+ const existing = state.identityJournal.connections.find(entry => entry.scenario === scenario)+ if (existing) {+ if (JSON.stringify(existing) !== JSON.stringify(evidence))+ throw new Error('Conflicting recorded connection capture')+ continue+ }+ recordFixtureConnection(input, state.identityJournal, { env }, evidence)+ save()+ }+}+export async function restoreOwnedFixture({state,profile,@@ -719,6 +819,8 @@ export async function restoreOwnedFixture({waitProxyRollout,cleanupForward,cleanupResources,+ cleanupIdentities,+ restoreApi,}) {if (!state || state.profile !== profile || state.worktree !== worktree)throw new Error('Fixture ownership mismatch')@@ -768,13 +870,34 @@ export async function restoreOwnedFixture({cleanupErrors.push(error)}}+ let resourcesFailed = falsetry {if (state.resources?.length && !cleanupResources)throw new Error('Resource cleanup adapter is required')if (cleanupResources) await cleanupResources()} catch (error) {+ resourcesFailed = truecleanupErrors.push(error)}+ if (state.identitySeedStarted) {+ try {+ if (resourcesFailed) throw new Error('Resources remain; identity cleanup deferred')+ if (!cleanupIdentities) throw new Error('Identity cleanup adapter is required')+ await cleanupIdentities()+ if (state.identityJournal?.status !== 'cleaned')+ throw new Error('Fixture identity cleanup is incomplete')+ } catch (error) {+ cleanupErrors.push(error)+ }+ }+ if (state.controlApi) {+ try {+ if (!restoreApi) throw new Error('Control API restore adapter is required')+ await restoreApi()+ } catch (error) {+ cleanupErrors.push(error)+ }+ }if (proxyError || cleanupErrors.length > 0) {throw proxyError ?? cleanupErrors[0]}@@ -854,12 +977,82 @@ async function main() {fs.writeSync(stateFile.fd, data, 0, data.length, 0)fs.fsyncSync(stateFile.fd)}+ const verifyApiMarker = () => {+ const marker = JSON.parse(+ kubectl([+ '-n',+ 'control-plane',+ 'exec',+ 'deployment/control-api',+ '--',+ 'node',+ '-e',+ controlApiMarkerCheck,+ ])+ )+ if (marker.run !== state.run || marker.profile !== profile || marker.pid !== 1)+ throw new Error('Control API live fixture marker mismatch')+ const live = getApi()+ if (+ live.metadata.uid !== state.controlApi.metadata.uid ||+ live.spec.template.metadata?.annotations?.[proxyRunAnnotation] !== state.run ||+ live.spec.template.spec.containers.find(c => c.name === 'control-api')?.image !==+ controlApiFixtureImage+ )+ throw new Error('Control API live fixture deployment mismatch')+ }+ const runIdentityOperation = input => {+ verifyApiMarker()+ const source = readOwnedFile(+ path.join(repo, 'tests/e2e/fixtures/codex-subscription/approved-tools-setup'),+ 'seed.mjs',+ 128 * 1024+ )+ const output = kubectl(+ [+ '-n',+ 'control-plane',+ 'exec',+ '-i',+ 'deployment/control-api',+ '--',+ 'node',+ '--input-type=module',+ '--eval',+ source,+ ],+ { input: JSON.stringify(input), timeout: 90_000 }+ )+ state.identityJournal = parseIdentityJournal(+ output,+ state.identityJournal,+ input.action === 'create' ? 'created' : 'cleaned'+ )+ save()+ }const getOwnedResource = entry => {const output = kubectl(fixtureResourceGetArgs(entry, state.run), {resourceCleanup: { entry, run: state.run },}).trim()return output === '' ? null : JSON.parse(output)}+ const getApi = () =>+ JSON.parse(kubectl(['-n', 'control-plane', 'get', 'deployment/control-api', '-o', 'json']))+ const patchApi = patch =>+ kubectl([+ '-n',+ 'control-plane',+ 'patch',+ 'deployment/control-api',+ '--type=strategic',+ '-p',+ JSON.stringify(patch),+ ])+ const waitApi = () =>+ kubectl(+ ['-n', 'control-plane', 'rollout', 'status', 'deployment/control-api', '--timeout=180s'],+ { timeout: 190_000 }+ )async function restore() {try {await restoreOwnedFixture({@@ -914,6 +1107,48 @@ async function main() {String(binding.localPort),String(binding.remotePort),]),+ restoreApi: () =>+ restoreControlApi({ state, profile, get: getApi, patch: patchApi, wait: waitApi }),+ cleanupIdentities: async () => {+ ingestFixtureConnections(+ state,+ name => {+ let file+ try {+ file = openOwnedFile(evidence, name, { maxBytes: 4096 })+ } catch (error) {+ if (error.code === 'ENOENT') return null+ throw error+ }+ try {+ if ((fs.fstatSync(file.fd).mode & 0o777) !== 0o600)+ throw new Error('Connection capture must have mode 0600')+ return readOwnedDescriptor(file)+ } finally {+ fs.closeSync(file.fd)+ }+ },+ save+ )+ const pending = await recoverControlApiForCleanup({+ state,+ profile,+ get: getApi,+ patch: patchApi,+ wait: waitApi,+ verify: verifyApiMarker,+ })+ if (!pending) return+ runIdentityOperation({+ action: 'cleanup',+ mode: 'deterministic',+ run: state.run,+ profile,+ context: profile,+ scenarios: [...state.scenarios, state.workflowScenario],+ initialJournal: state.identityJournal,+ })+ },cleanupResources: () =>cleanupJournaledFixtureResources({journal: state.resources,@@ -963,25 +1198,25 @@ async function main() {throw new Error('Synthetic preparation is deterministic-only; real accounts require separate authorized preconditions')+ // Both sources are mandatory before any fixture mutation. A seed alone+ // cannot provide the external consent flow exercised by the browser.+ readOwnedFile(+ path.join(repo, 'tests/e2e/fixtures/codex-subscription/approved-tools-oauth'),+ 'provider.mjs',+ 128 * 1024+ )const seedFile = path.join(repo,'tests/e2e/fixtures/codex-subscription/approved-tools-setup/seed.mjs')- const seedSource = readOwnedFile(path.dirname(seedFile), path.basename(seedFile), 128 * 1024)+ readOwnedFile(path.dirname(seedFile), path.basename(seedFile), 128 * 1024)for (const name of ['TEST_ADMIN_USERNAME','TEST_ADMIN_PASSWORD',- 'TEST_USER_EMAIL','TEST_USER_PASSWORD',- 'APPROVED_TOOLS_UNAUTHORIZED_EMAIL','APPROVED_TOOLS_UNAUTHORIZED_PASSWORD',])required(name)- if (- required('TEST_USER_EMAIL').trim().toLowerCase() ===- required('APPROVED_TOOLS_UNAUTHORIZED_EMAIL').trim().toLowerCase()- )- throw new Error('Unauthorized login fixture must be a distinct fresh identity')// The supported Minikube overlays enable these already. Refuse a stale or// differently configured runtime; fixture setup must not weaken feature gates.for (const [deploymentName, keys] of [@@ -1045,6 +1280,9 @@ async function main() {images: observedImages,})const run = 'approved-tools-' + randomBytes(6).toString('hex')+ // The same fresh identity names feed both setup and the visible login runner.+ process.env.TEST_USER_EMAIL = `${run}@example.test`+ process.env.APPROVED_TOOLS_UNAUTHORIZED_EMAIL = `${run}[email protected]`const ports = []while (ports.length < 5) {const port = await freePort()@@ -1082,6 +1320,23 @@ async function main() {throw new Error('Unsupported explicit NODE_ENV binding')// Refuse an unsupported original image before any fixture resource is created.validateProxyImage(container.image, container.imagePullPolicy)+ const controlApi = captureControlApi(getApi(), profile)+ const identityBinding = {+ mode: 'deterministic',+ run,+ profile,+ context: profile,+ scenarios: allScenarios,+ }+ const identityJournal = createFixtureIdentityJournal(identityBinding, {+ env: {+ NODE_ENV: 'test',+ EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE: '1',+ APPROVED_TOOLS_RUN_ID: run,+ MINIKUBE_PROFILE: profile,+ CONTROL_API_REAL_PG_CONTEXT: profile,+ },+ })state = {profile,worktree: repo,@@ -1092,6 +1347,9 @@ async function main() {workflowScenario,forwards: [],resources: [],+ identityJournal,+ identitySeedStarted: false,+ controlApi,originalProxyImage: container.image,originalImagePullPolicy: container.imagePullPolicy,originalNodeEnv,@@ -1151,6 +1409,17 @@ async function main() {validateForward(binding)}try {+ patchApi(+ controlApiPatch({+ metadata: controlApi.metadata,+ image: controlApiFixtureImage,+ imagePullPolicy: 'Never',+ env: controlApiFixtureEnv(run, profile),+ run,+ })+ )+ waitApi()+ verifyApiMarker()await createJournaledFixtureResources({resources,run,@@ -1245,6 +1514,9 @@ async function main() {)}const seedInput = {+ action: 'create',+ ...identityBinding,+ initialJournal: state.identityJournal,mode: 'deterministic',profile,scenarios: allScenarios,@@ -1257,21 +1529,9 @@ async function main() {unauthorizedEmail: required('APPROVED_TOOLS_UNAUTHORIZED_EMAIL'),unauthorizedPassword: required('APPROVED_TOOLS_UNAUTHORIZED_PASSWORD'),}- kubectl(- [- '-n',- 'control-plane',- 'exec',- '-i',- 'deployment/control-api',- '--',- 'node',- '--input-type=module',- '--eval',- seedSource,- ],- { input: JSON.stringify(seedInput), timeout: 90_000 }- )+ state.identitySeedStarted = true+ save()+ runIdentityOperation(seedInput)fs.writeFileSync(path.join(evidence, 'scenarios.json'),JSON.stringify(scenarios, null, 2) + '\n',@@ -1285,6 +1545,7 @@ async function main() {state.ready = truesave()if (action === 'run') {+ process.env.APPROVED_TOOLS_FIXTURE_USER_ID = state.identityJournal.users[0].idprocess.env.APPROVED_TOOLS_SCENARIOS = JSON.stringify(scenarios)process.env.APPROVED_TOOLS_WORKFLOW_SCENARIO = JSON.stringify(workflowScenario)command('runner', [], {diff --git a/scripts/e2e/prepare-codex-approved-tools.test.mjs b/scripts/e2e/prepare-codex-approved-tools.test.mjsindex 98d7b00d9..4e325cb56 100644--- a/scripts/e2e/prepare-codex-approved-tools.test.mjs+++ b/scripts/e2e/prepare-codex-approved-tools.test.mjs@@ -207,7 +207,9 @@ test('missing seed and lease fail before first cluster mutation; no image acquis)const mutation = source.indexOf("kubectl(['create'")const lease = source.indexOf("command('lease', [])")- const seedRead = source.indexOf('const seedSource = readOwnedFile(')+ const seedRead = source.indexOf(+ 'readOwnedFile(path.dirname(seedFile), path.basename(seedFile), 128 * 1024)'+ )assert.ok(lease >= 0 && lease < mutation)assert.ok(seedRead >= 0 && seedRead < mutation)assert.equal(source.includes('build-images.sh'), false)diff --git a/scripts/minikube/build-images.sh b/scripts/minikube/build-images.shindex f8c30067f..fd29f75ff 100755--- a/scripts/minikube/build-images.sh+++ b/scripts/minikube/build-images.sh@@ -358,6 +358,10 @@ KNOWN_BUILD_NAMES=(# These isolated test images are opt-in only. Their acquisition must happen# before T2 reconciliation, never inside the final Playwright command.+if [ "$ONLY_SVC" = codex-approved-tools-control-api-e2e ]; then+ ALL_IMAGES+=("clerum/codex-approved-tools-control-api-e2e:test")+ KNOWN_BUILD_NAMES+=(codex-approved-tools-control-api-e2e)+fiif [ "$ONLY_SVC" = codex-approved-tools-mcp-e2e ]; thenALL_IMAGES+=("clerum/codex-approved-tools-mcp-e2e:test")KNOWN_BUILD_NAMES+=(codex-approved-tools-mcp-e2e)@@ -992,6 +996,10 @@ build_image() {if [ -n "$dockerfile" ]; thendocker_args+=(-f "$dockerfile")fi+ if [ "$name" = codex-approved-tools-control-api-e2e ]; then+ docker_args+=(--build-arg CONTROL_API_IMAGE=clerum/control-api:test)+ derived_base="clerum/control-api:test"+ fiif [ "$name" = codex-approved-tools-proxy-e2e ]; then# The public target builds this production tag immediately beforehand under# the same profile lease. The test image never replaces that tag.@@ -1206,6 +1214,11 @@ build_image "codex-llm-proxy" \"clerum/codex-llm-proxy:test" \"${PROJECT_DIR}/codex-llm-proxy/Dockerfile"+if [ "$ONLY_SVC" = codex-approved-tools-control-api-e2e ]; then+ build_image codex-approved-tools-control-api-e2e "${PROJECT_DIR}" \+ clerum/codex-approved-tools-control-api-e2e:test \+ "${PROJECT_DIR}/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/Dockerfile"+fiif [ "$ONLY_SVC" = codex-approved-tools-mcp-e2e ]; thenbuild_image codex-approved-tools-mcp-e2e "${PROJECT_DIR}" \clerum/codex-approved-tools-mcp-e2e:test \@@ -1599,7 +1612,7 @@ done# ---- Carry verified records forward from the previous manifest ----## This writer replaces the whole file, and a partial run stages only the refs in-# its own ALL_IMAGES. Without carrying, the fixture target -- five --only+# its own ALL_IMAGES. Without carrying, the fixture target -- sequential --only# invocations in a row -- would leave a manifest holding only the last fixture,# and the prepare step that swaps the proxy onto a fixture would have nothing to# verify against.diff --git a/scripts/minikube/t2-common.sh b/scripts/minikube/t2-common.shindex 66b04074f..cb2c4f134 100755--- a/scripts/minikube/t2-common.sh+++ b/scripts/minikube/t2-common.sh@@ -652,36 +652,40 @@ PYfi}-# Readiness alone does not prove that a journey restored the production proxy.+# Readiness alone does not prove that a journey restored its production images.# The planner may reconcile; certifying preflight requires the live baseline.-t2_proxy_runtime_check() {+t2_restored_runtime_check() {[ "$T2_PLAN_MODE" != true ] && [ "$T2_BOOTSTRAP_REQUIRED" != true ] || return 0- local deployments="$1" pods inventory pod_names pod_name environment_check- if ! pods="$(t2_kc -n "$T2_CONTROL_NAMESPACE" get pods -l app=codex-llm-proxy -o json)"; then- t2_fail PROXY_RUNTIME_MISMATCH 'unable to observe running proxy identity'+ local deployments="$1" service="$2" failure_code="$3" fixture_flags="$4" marker_file="$5"+ local pods inventory pod_names pod_name environment_check+ if ! pods="$(t2_kc -n "$T2_CONTROL_NAMESPACE" get pods -l app="$service" -o json)"; then+ t2_fail "$failure_code" "unable to observe running $service identity"return 1fiif ! inventory="$(t2_mk image ls --format=json)"; then- t2_fail PROXY_RUNTIME_MISMATCH 'unable to observe profile image inventory'+ t2_fail "$failure_code" 'unable to observe profile image inventory'return 1fi- if ! pod_names="$(python3 - "$T2_IMAGE_MANIFEST" "$T2_PROFILE" "$T2_CONTROL_NAMESPACE" "$deployments" "$pods" "$inventory" <<'PY_PROXY'+ if ! pod_names="$(python3 - "$T2_IMAGE_MANIFEST" "$T2_PROFILE" "$T2_CONTROL_NAMESPACE" "$deployments" "$pods" "$inventory" "$service" "$fixture_flags" <<'PY_RUNTIME'import jsonimport reimport sysfrom pathlib import Path+service = sys.argv[7]+fixture_flags = set(sys.argv[8].split())+def require(condition):if not condition:- raise ValueError("unproven production proxy")+ raise ValueError("unproven production service")def clean(template):require("evenfire.ai/codex-tools-fixture-run" not in (template.get("metadata", {}).get("annotations") or {}))- containers = [c for c in template["spec"]["containers"] if c.get("name") == "codex-llm-proxy"]+ containers = [c for c in template["spec"]["containers"] if c.get("name") == service]require(len(containers) == 1)container = containers[0]for entry in container.get("env", []):- require(entry.get("name") not in {"CODEX_APPROVED_TOOLS_TEST_ONLY", "CODEX_APPROVED_TOOLS_MINIKUBE_PROFILE"})+ require(entry.get("name") not in fixture_flags)require(entry.get("name") != "NODE_ENV" or entry.get("value") != "test")return container@@ -690,7 +694,7 @@ try:require(manifest.get("profile") == sys.argv[2])images = manifest["images"]# Both acquisition modes record this production alias and Docker config ID.- baseline = images["clerum/codex-llm-proxy:test"]+ baseline = images[f"clerum/{service}:test"]require(isinstance(baseline, str) and re.fullmatch(r"sha256:[0-9a-f]{64}", baseline))inventory = json.loads(sys.argv[6])require(isinstance(inventory, list))@@ -705,7 +709,7 @@ try:observed[ref] = identitydeployments = [d for d in json.loads(sys.argv[4])["items"] ifd.get("metadata", {}).get("namespace") == sys.argv[3] and- d.get("metadata", {}).get("name") == "codex-llm-proxy"]+ d.get("metadata", {}).get("name") == service]require(len(deployments) == 1)deployment = deployments[0]desired = deployment["spec"].get("replicas", 1)@@ -713,6 +717,8 @@ try:target = clean(deployment["spec"]["template"])require(images.get(target["image"]) == baseline)ref = target["image"]+ require(re.fullmatch(r"(?:clerum/|ghcr\.io/evenfire-ai/)" + re.escape(service) ++ r"(?::[A-Za-z0-9._-]+|@sha256:[0-9a-f]{64})", ref))canonical = "docker.io/" + ref if ref.startswith("clerum/") else refrequire(observed.get(canonical) == baseline)pods = json.loads(sys.argv[5])["items"]@@ -723,7 +729,7 @@ try:require(pod["metadata"].get("namespace") == sys.argv[3])container = clean(pod)require(container["image"] == target["image"])- statuses = [c for c in pod["status"]["containerStatuses"] if c.get("name") == "codex-llm-proxy"]+ statuses = [c for c in pod["status"]["containerStatuses"] if c.get("name") == service]require(len(statuses) == 1 and statuses[0].get("ready") is True)require(bool(statuses[0].get("state", {}).get("running")))# Resolve a repository digest through the owned profile inventory;@@ -741,25 +747,37 @@ try:names.append(name)print("\n".join(names))except (OSError, ValueError, KeyError, TypeError, AttributeError):- raise SystemExit("production proxy identity, fixture markers, or baseline evidence did not match")-PY_PROXY+ raise SystemExit("production service identity, fixture markers, or baseline evidence did not match")+PY_RUNTIME)"; then- T2_NEXT_COMMAND="restore the production proxy and retry MINIKUBE_PROFILE=$T2_PROFILE make minikube-t2-runtime"- t2_fail PROXY_RUNTIME_MISMATCH 'live proxy does not prove the recorded production baseline'+ T2_NEXT_COMMAND="restore production $service and retry MINIKUBE_PROFILE=$T2_PROFILE make minikube-t2-runtime"+ t2_fail "$failure_code" "live $service does not prove the recorded production baseline"return 1fi# Read only fixture predicates, including envFrom/image-level variables;# never emit the environment or secret-bearing objects as evidence.while IFS= read -r pod_name; do- if ! environment_check="$(t2_kc -n "$T2_CONTROL_NAMESPACE" exec "$pod_name" -c codex-llm-proxy -- node -e \- 'process.stdout.write(String(!("CODEX_APPROVED_TOOLS_TEST_ONLY" in process.env) && !("CODEX_APPROVED_TOOLS_MINIKUBE_PROFILE" in process.env) && process.env.NODE_ENV !== "test"))')" ||+ if ! environment_check="$(t2_kc -n "$T2_CONTROL_NAMESPACE" exec "$pod_name" -c "$service" -- node -e \+ 'const [flags, marker] = process.argv.slice(1); process.stdout.write(String(flags.split(" ").every(name => !(name in process.env)) && process.env.NODE_ENV !== "test" && (!marker || !require("node:fs").existsSync(marker))))' "$fixture_flags" "$marker_file")" ||[ "$environment_check" != true ]; then- t2_fail PROXY_RUNTIME_MISMATCH 'running proxy environment is unknown or retains fixture configuration'+ t2_fail "$failure_code" "running $service environment is unknown or retains fixture configuration"return 1fidone <<< "$pod_names"}+# Keep callers explicit about which production workload they certify.+t2_proxy_runtime_check() {+ t2_restored_runtime_check "$1" codex-llm-proxy PROXY_RUNTIME_MISMATCH \+ 'CODEX_APPROVED_TOOLS_TEST_ONLY CODEX_APPROVED_TOOLS_MINIKUBE_PROFILE' ''+}++t2_control_api_runtime_check() {+ t2_restored_runtime_check "$1" control-api CONTROL_API_RUNTIME_MISMATCH \+ 'EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE APPROVED_TOOLS_RUN_ID' \+ '/tmp/approved-tools-oauth-active.json'+}+t2_deployment_check() {local deployment_json unreadydeployment_json="$(t2_kc get deployments -A -o json 2>/dev/null || true)"diff --git a/scripts/minikube/t2-preflight.sh b/scripts/minikube/t2-preflight.shindex 5bff3987c..4da2d634e 100755--- a/scripts/minikube/t2-preflight.sh+++ b/scripts/minikube/t2-preflight.sh@@ -52,6 +52,7 @@ main() {t2_postgres_checkt2_deployment_checkt2_proxy_runtime_check "$T2_DEPLOYMENT_JSON"+ t2_control_api_runtime_check "$T2_DEPLOYMENT_JSON"t2_process_checkt2_classify_transitiont2_write_plan "$T2_PLAN_FILE"diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.shindex abeee53cc..893588383 100755--- a/scripts/tests/test-codex-subscription-t0.sh+++ b/scripts/tests/test-codex-subscription-t0.sh@@ -204,6 +204,10 @@ run_node_group "approved-tools-fixtures-and-runner" \"scripts/e2e/desktop-login-seed.test.mjs" \"scripts/e2e/approved-tools-image-proof.test.mjs" \"scripts/e2e/approved-tools-restoration.test.mjs" \+ "scripts/e2e/approved-tools-control-api-lifecycle.test.mjs" \+ "scripts/e2e/approved-tools-connection-journal.test.mjs" \+ "tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.test.mjs" \+ "tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.test.mjs" \"scripts/e2e/approved-tools-resource-cleanup.test.mjs" \"tests/e2e/fixtures/codex-subscription/approved-tools-workflow/index.test.mjs"diff --git a/scripts/tests/test-minikube-docker-cli-env.sh b/scripts/tests/test-minikube-docker-cli-env.shindex d718e8a29..d44034b73 100755--- a/scripts/tests/test-minikube-docker-cli-env.sh+++ b/scripts/tests/test-minikube-docker-cli-env.sh@@ -467,7 +467,8 @@ assert_sequential_build_manifest_provenance() {printf '{}\n' >"$state"revision_before="$(git -C "$fixture" rev-parse HEAD)"- for selector in codex-llm-proxy codex-approved-tools-proxy-e2e \+ for selector in control-api codex-approved-tools-control-api-e2e \+ codex-llm-proxy codex-approved-tools-proxy-e2e \workflow-custom-sdk-e2e codex-approved-tools-workflow-e2e; doif ! FAKE_DOCKER_IMAGE_STATE="$state" MINIKUBE_PRELOAD_BASE_IMAGES=false \bash "$fixture/scripts/minikube/build-images.sh" "--only=$selector" \@@ -505,9 +506,15 @@ assert.equal(m.sourceRevisions[workflowBase], before)assert.equal(m.sourceRevisions[workflowDerived], before)assert.match(m.images[workflowDerived], /^sha256:[0-9a-f]{64}$/)assert.deepEqual(m.derivedFrom[workflowDerived], { ref: workflowBase, id: m.images[workflowBase] })+const controlBase = 'clerum/control-api:test'+const controlDerived = 'clerum/codex-approved-tools-control-api-e2e:test'+assert.equal(m.sourceRevisions[controlBase], before)+assert.equal(m.sourceRevisions[controlDerived], before)+assert.match(m.images[controlDerived], /^sha256:[0-9a-f]{64}$/)+assert.deepEqual(m.derivedFrom[controlDerived], { ref: controlBase, id: m.images[controlBase] })NODEthen- pass "five sequential --only builds preserve prior revisions and both exact derived-base bindings"+ pass "seven sequential --only builds preserve prior revisions and all exact derived-base bindings"elsefail "sequential --only builds lost or restamped prior provenance"returndiff --git a/scripts/tests/test-minikube-mutation-boundary.sh b/scripts/tests/test-minikube-mutation-boundary.shindex 98214483a..dd308c1c1 100755--- a/scripts/tests/test-minikube-mutation-boundary.sh+++ b/scripts/tests/test-minikube-mutation-boundary.sh@@ -265,17 +265,20 @@ NODEprintf 'PASS: WRC direct entry, pending journal and dedicated recovery enforce the real inherited lease\n'}-# The #627 real-tool targets are the only mutation targets whose recipes call a-# reviewed external builder directly. They must forward the same explicit+# The #627 real-tool and approved-tools targets must forward the same explicit# profile/context/lease passthrough as every sibling target; without it a# makefile-variable profile (`MINIKUBE_PROFILE ?=`, never exported) never# reaches the wrapper and the transition fails before it can run.assert_627_targets_forward_the_profile_and_lease() {- local target plan problem=""+ local target plan before_build problem=""for target in \minikube-install-627-real-tools \minikube-build-627-worktracker \- minikube-build-627-github; do+ minikube-build-627-github \+ minikube-build-codex-approved-tools-fixtures \+ minikube-prepare-codex-approved-tools \+ minikube-run-codex-approved-tools \+ minikube-restore-codex-approved-tools; do# Inspect the rendered boundary with a known Make value. Explicit recipe# assignments also support values defined by included Makefiles, which are# not automatically exported like command-line assignments are.@@ -296,11 +299,15 @@ assert_627_targets_forward_the_profile_and_lease() {[[ "${plan}" == *"T2_LOCK_TOKEN="* ]] \|| problem+="${target} does not forward T2_LOCK_TOKEN; "done+ plan="$(dry_run_make minikube-build-codex-approved-tools-fixtures-body MINIKUBE_PROFILE="${PROFILE}")"+ before_build="${plan%%build-images.sh*}"+ [[ "${plan}" == *"build-images.sh"* && "${before_build}" == *"require-t2-mutation-lock.sh"* ]] \+ || problem+='approved-tools fixture body does not validate its inherited lease before image builds; 'if [[ -n "${problem}" ]]; thenprintf 'FAIL: #627 mutation targets: %s\n' "${problem}" >&2exit 1fi- printf 'PASS: the #627 real-tool targets forward the explicit profile, context and inherited lease\n'+ printf 'PASS: the #627 real-tool and four approved-tools targets forward profile/context/lease; fixture body guards its builds\n'}diff --git a/scripts/tests/test-minikube-t2-contract.sh b/scripts/tests/test-minikube-t2-contract.shindex 5f870b69d..f84267a92 100755--- a/scripts/tests/test-minikube-t2-contract.sh+++ b/scripts/tests/test-minikube-t2-contract.sh@@ -27,6 +27,7 @@ for file in "$MINIKUBE_DIR/profile-readiness.sh" "$ROOT/scripts/tests/test-minik"$ROOT/scripts/tests/test-minikube-t2-public-boundary.sh" \"$ROOT/scripts/tests/test-minikube-t2-scenarios.sh" \"$ROOT/scripts/tests/test-minikube-t2-proxy-runtime.sh" \+ "$ROOT/scripts/tests/test-minikube-t2-control-api-runtime.sh" \"$ROOT/scripts/tests/test-minikube-settle-gfs-reader-rollout.sh" \"$ROOT/scripts/tests/test-minikube-gfs-rollout-shim.sh" \"$ROOT/scripts/tests/test-minikube-gfs-provision-order.sh" \@@ -646,6 +647,7 @@ if T2_PUBLIC_ROOT="$public_repo" T2_PUBLIC_BASE_REF="$public_base" \fibash "$ROOT/scripts/tests/test-minikube-t2-scenarios.sh"bash "$ROOT/scripts/tests/test-minikube-t2-proxy-runtime.sh"+bash "$ROOT/scripts/tests/test-minikube-t2-control-api-runtime.sh"bash "$ROOT/scripts/tests/test-minikube-profile-readiness.sh"bash "$ROOT/scripts/tests/test-minikube-settle-gfs-reader-rollout.sh"bash "$ROOT/scripts/tests/test-minikube-gfs-rollout-shim.sh"diff --git a/scripts/tests/test-minikube-t2-control-api-runtime.sh b/scripts/tests/test-minikube-t2-control-api-runtime.shnew file mode 100644index 000000000..5f689c6e2--- /dev/null+++ b/scripts/tests/test-minikube-t2-control-api-runtime.sh@@ -0,0 +1,138 @@+#!/usr/bin/env bash+# Hermetic Control API restoration checks for certifying preflight.+# shellcheck disable=SC2034+set -euo pipefail+ROOT="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd -P)"+source "$ROOT/scripts/tests/lib/minikube-fixture-repo.sh"+tmp="$(mktemp -d)"+cleanup() {+ local status=$?+ minikube_test_assert_host_unchanged || status=1+ rm -rf "$tmp"+ exit "$status"+}+minikube_test_fixture_repo_init "$ROOT" "$tmp"+trap cleanup EXIT+export T2_PROJECT_DIR="$MINIKUBE_TEST_PROJECT_DIR"+export T2_BRANCH="$MINIKUBE_TEST_BRANCH" T2_HEAD="$MINIKUBE_TEST_HEAD"+export T2_WORKTREE_ID="$MINIKUBE_TEST_WORKTREE_ID"+export T2_PROFILE=fake T2_CONTEXT=fake T2_LOCK_ROOT="$tmp/locks"+source "$ROOT/scripts/minikube/t2-common.sh"+T2_IMAGE_MANIFEST="$tmp/manifest.json"+T2_CONTROL_NAMESPACE=control-plane+T2_REQUIRED_DEPLOYMENTS=control-plane/control-api+T2_PLAN_MODE=false+T2_BOOTSTRAP_REQUIRED=false+t2_fail() { printf '%s: %s\n' "$1" "$2" >&2; return 1; }+# Every runtime entry point is replaced; no cluster or container is contacted.+t2_kc() {+ case "$*" in+ 'get deployments -A -o json') cat "$tmp/deployments.json" ;;+ '-n control-plane get pods -l app=control-api -o json') cat "$tmp/pods.json" ;;+ '-n control-plane exec api-1 -c control-api -- node -e '*)+ [ "${11}" = 'EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE APPROVED_TOOLS_RUN_ID' ] || return 1+ [ "${12}" = '/tmp/approved-tools-oauth-active.json' ] || return 1+ [ "$runtime_environment" != unknown ] || return 1+ local environment=(env -u EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE -u APPROVED_TOOLS_RUN_ID NODE_ENV=production)+ case "$runtime_environment" in+ fixture) environment+=(EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE=1) ;;+ run) environment+=(APPROVED_TOOLS_RUN_ID=approved-tools-aabbccddeeff) ;;+ test) environment+=(NODE_ENV=test) ;;+ esac+ "${environment[@]}" node -e "${10}" "${11}" "$tmp/active.json"+ ;;+ *) printf 'unexpected cluster command\n' >&2; return 1 ;;+ esac+}+t2_mk() {+ [ "$*" = 'image ls --format=json' ] || return 1+ cat "$tmp/inventory.json"+}+make_case() {+ runtime_environment=clean+ rm -f "$tmp/active.json"+ python3 - "$tmp" "$1" <<'PY'+import copy, json, sys+from pathlib import Path+root, case = Path(sys.argv[1]), sys.argv[2]+base, other = 'sha256:' + 'a'*64, 'sha256:' + 'b'*64+ref = 'clerum/control-api:test'+digest_ref = 'ghcr.io/evenfire-ai/control-api@sha256:' + 'c'*64+manifest = {'profile': 'fake', 'images': {ref: base}}+container = {'name': 'control-api', 'image': ref, 'env': []}+template = {'metadata': {}, 'spec': {'containers': [container]}}+deployment = {'metadata': {'name': 'control-api', 'namespace': 'control-plane', 'generation': 1},+ 'spec': {'replicas': 1, 'template': template},+ 'status': {'observedGeneration': 1, 'updatedReplicas': 1, 'readyReplicas': 1, 'availableReplicas': 1}}+pod = copy.deepcopy(template)+pod['metadata'] = {'name': 'api-1', 'namespace': 'control-plane'}+status = {'name': 'control-api', 'imageID': 'docker://' + base, 'ready': True, 'state': {'running': {'startedAt': '2026-01-01'}}}+pod['status'] = {'containerStatuses': [status]}+inventory = [{'id': base[7:], 'repoTags': ['docker.io/' + ref], 'repoDigests': [digest_ref]}]+if case == 'fixture-image':+ container['image'] = 'clerum/codex-approved-tools-control-api-e2e:test'+ manifest['images'][container['image']] = other+if case == 'fixture-run-env': container['env'] = [{'name': 'APPROVED_TOOLS_RUN_ID', 'value': 'approved-tools-aabbccddeeff'}]+if case == 'fixture-node-env': container['env'] = [{'name': 'NODE_ENV', 'value': 'test'}]+if case == 'fixture-env': container['env'] = [{'name': 'EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE', 'value': '1'}]+if case == 'fixture-marker': template['metadata']['annotations'] = {'evenfire.ai/codex-tools-fixture-run': 'approved-tools-aabbccddeeff'}+if case == 'old-fixture-pod': pod['spec']['containers'][0]['env'] = [{'name': 'APPROVED_TOOLS_RUN_ID', 'value': 'fake'}]+if case == 'old-fixture-marker': pod['metadata']['annotations'] = {'evenfire.ai/codex-tools-fixture-run': 'approved-tools-aabbccddeeff'}+if case == 'fixture-image-alias':+ alias = 'clerum/codex-approved-tools-control-api-e2e:test'+ container['image'] = alias+ pod['spec']['containers'][0]['image'] = alias+ manifest['images'][alias] = base+ inventory[0]['repoTags'].append('docker.io/' + alias)+if case == 'wrong-id': status['imageID'] = 'docker://' + other+if case == 'unknown-id': status['imageID'] = 'unknown'+if case == 'missing-id': del status['imageID']+if case == 'missing-baseline': manifest['images'] = {}+if case == 'missing-api': deployment = None+if case == 'wrong-profile': manifest['profile'] = 'other'+if case == 'missing-pods': pod = None+if case == 'missing-inventory': inventory = []+if case == 'ghcr':+ ghcr = 'ghcr.io/evenfire-ai/control-api:v1'+ manifest['images'][ghcr] = base+ container['image'] = ghcr+ pod['spec']['containers'][0]['image'] = ghcr+ inventory[0]['repoTags'].append(ghcr)+ status['imageID'] = 'docker-pullable://' + digest_ref+if case == 'unknown-repo-digest': status['imageID'] = 'docker-pullable://' + digest_ref + 'd'+for name, data in [('manifest', manifest), ('deployments', {'items': [deployment] if deployment else []}),+ ('pods', {'items': [pod] if pod else []}), ('inventory', inventory)]:+ (root / (name + '.json')).write_text(json.dumps(data))+PY+}+for scenario in restored ghcr; do+ make_case "$scenario"+ t2_deployment_check+ t2_control_api_runtime_check "$T2_DEPLOYMENT_JSON"+done+# Keep the production preflight integration under regression coverage.+# The contract checks literal shell source, not an expanded value.+# shellcheck disable=SC2016+grep -Fq 't2_control_api_runtime_check "$T2_DEPLOYMENT_JSON"' "$ROOT/scripts/minikube/t2-preflight.sh"+for scenario in fixture-image fixture-image-alias fixture-env fixture-run-env fixture-node-env fixture-marker old-fixture-pod old-fixture-marker wrong-id unknown-id missing-id missing-baseline missing-api wrong-profile missing-pods missing-inventory unknown-repo-digest runtime-fixture runtime-run runtime-test runtime-marker runtime-unknown; do+ make_case "$scenario"+ case "$scenario" in+ runtime-fixture) runtime_environment=fixture ;;+ runtime-run) runtime_environment=run ;;+ runtime-test) runtime_environment='test' ;;+ runtime-marker) printf '{}\n' >"$tmp/active.json" ;;+ runtime-unknown) runtime_environment=unknown ;;+ esac+ if t2_control_api_runtime_check "$(cat "$tmp/deployments.json")" >"$tmp/result" 2>&1; then+ printf 'unexpected PASS: %s\n' "$scenario" >&2; exit 1+ fi+ grep -q CONTROL_API_RUNTIME_MISMATCH "$tmp/result"+done+# Planning/bootstrap never certify this runtime baseline.+make_case missing-api+T2_PLAN_MODE=true+t2_control_api_runtime_check "$(cat "$tmp/deployments.json")"+T2_PLAN_MODE=false+T2_BOOTSTRAP_REQUIRED=true+t2_control_api_runtime_check "$(cat "$tmp/deployments.json")"+printf 'PASS: Control API production baseline, fixture markers and runtime environment regressions\n'diff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/Dockerfile b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/Dockerfilenew file mode 100644index 000000000..f4f5bdb0a--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/Dockerfile@@ -0,0 +1,6 @@+ARG CONTROL_API_IMAGE+FROM ${CONTROL_API_IMAGE}+LABEL ai.evenfire.test-only="approved-tools-minikube"+COPY tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.mjs tests/e2e/fixtures/codex-subscription/approved-tools-oauth/entrypoint.mjs /app/approved-tools-oauth/+COPY tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.mjs /app/approved-tools-setup/identity-lifecycle.mjs+CMD ["node", "/app/approved-tools-oauth/entrypoint.mjs"]diff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/entrypoint.mjs b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/entrypoint.mjsnew file mode 100644index 000000000..5dc22955c--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/entrypoint.mjs@@ -0,0 +1,15 @@+import { writeFile } from 'node:fs/promises'+import { createOAuthFixtureFetch, validateFixtureEnvironment } from './provider.mjs'++validateFixtureEnvironment(process.env)+globalThis.fetch = createOAuthFixtureFetch(globalThis.fetch.bind(globalThis))+await writeFile(+ '/tmp/approved-tools-oauth-active.json',+ JSON.stringify({+ run: process.env.APPROVED_TOOLS_RUN_ID,+ profile: process.env.MINIKUBE_PROFILE,+ pid: process.pid,+ }),+ { flag: 'wx', mode: 0o600 }+)+await import('/app/control-api/dist/main.js')diff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.mjs b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.mjsnew file mode 100644index 000000000..50ad1d5b6--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.mjs@@ -0,0 +1,108 @@+import { randomBytes } from 'node:crypto'++const origin = 'https://auth.openai.com'+const device = '/api/accounts/deviceauth/'+const paths = new Set([`${device}usercode`, `${device}token`, '/oauth/token'])+const opaque = () => randomBytes(24).toString('hex')+const reply = (body, status = 200) => Response.json(body, { status })+const invalid = () => reply({ error: 'invalid_grant' }, 400)++export function validateFixtureEnvironment(env) {+ if (+ env.NODE_ENV !== 'test' ||+ env.EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE !== '1' ||+ !/^approved-tools-[a-f0-9]{12}$/.test(env.APPROVED_TOOLS_RUN_ID ?? '') ||+ !/^[a-z0-9][a-z0-9-]{0,62}$/.test(env.MINIKUBE_PROFILE ?? '') ||+ env.MINIKUBE_PROFILE !== env.CONTROL_API_REAL_PG_CONTEXT ||+ !env.KUBERNETES_SERVICE_HOST+ )+ throw new Error('OAuth fixture requires its isolated test environment')+}++// Only the external device OAuth boundary is synthetic. All application routes,+// permissions, persistence and subscription selection remain real.+export function createOAuthFixtureFetch(delegate, { now = Date.now } = {}) {+ const sessions = new Map()+ return async (input, init = {}) => {+ const url = new URL(input instanceof Request ? input.url : input)+ if (url.origin !== origin) return delegate(input, init)+ // Unsupported OAuth operations must never send fixture credentials to the+ // real provider (including revoke or refresh paths outside this journey).+ if (!paths.has(url.pathname)) return invalid()+ // The production caller uses URL + init with a string body. Reject other+ // forms instead of reading an unbounded stream or reaching the real provider.+ if (+ input instanceof Request ||+ init.method !== 'POST' ||+ url.search ||+ url.hash ||+ typeof init.body !== 'string' ||+ Buffer.byteLength(init.body) > 16384+ )+ return invalid()+ for (const [id, session] of sessions) if (session.expires <= now()) sessions.delete(id)+ let body+ try {+ body =+ url.pathname === '/oauth/token'+ ? Object.fromEntries(new URLSearchParams(init.body))+ : JSON.parse(init.body)+ } catch {+ return invalid()+ }+ if (!body || typeof body !== 'object' || Array.isArray(body)) return invalid()+ if (url.pathname === `${device}usercode`) {+ if (typeof body.client_id !== 'string' || !body.client_id || sessions.size >= 32)+ return invalid()+ const id = opaque()+ const session = {+ client: body.client_id,+ user: opaque(),+ code: opaque(),+ verifier: opaque(),+ expires: now() + 300000,+ polled: false,+ issued: false,+ }+ sessions.set(id, session)+ return reply({ device_auth_id: id, user_code: session.user, interval: 1, expires_in: 300 })+ }+ if (url.pathname === `${device}token`) {+ const session = sessions.get(body.device_auth_id)+ if (!session || session.user !== body.user_code) return invalid()+ if (!session.polled) {+ session.polled = true+ return reply({ error: 'authorization_pending' }, 403)+ }+ session.issued = true+ return reply({ authorization_code: session.code, code_verifier: session.verifier })+ }+ const entry = [...sessions].find(([, session]) => session.code === body.code)+ if (!entry) return invalid()+ const [id, session] = entry+ if (+ !session.issued ||+ body.grant_type !== 'authorization_code' ||+ body.client_id !== session.client ||+ body.code_verifier !== session.verifier ||+ body.redirect_uri !== `${origin}/deviceauth/callback`+ )+ return invalid()+ sessions.delete(id)+ const subject = `fixture-${opaque()}`+ const encode = value => Buffer.from(JSON.stringify(value)).toString('base64url')+ // Deliberately not an OpenAI credential; only this isolated external fixture+ // produces it, and the deterministic proxy supplies the model boundary.+ const idToken = `${encode({ alg: 'none', typ: 'JWT' })}.${encode({+ sub: subject,+ exp: Math.floor(now() / 1000) + 3600,+ 'https://api.openai.com/auth': { chatgpt_account_id: subject },+ })}.fixture`+ return reply({+ access_token: `fixture-${opaque()}`,+ refresh_token: `fixture-${opaque()}`,+ expires_in: 3600,+ id_token: idToken,+ })+ }+}diff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.test.mjs b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.test.mjsnew file mode 100644index 000000000..5d54625c9--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-oauth/provider.test.mjs@@ -0,0 +1,117 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { createOAuthFixtureFetch, validateFixtureEnvironment } from './provider.mjs'++const base = 'https://auth.openai.com'+const env = {+ NODE_ENV: 'test',+ EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE: '1',+ APPROVED_TOOLS_RUN_ID: 'approved-tools-123456abcdef',+ MINIKUBE_PROFILE: 'owned-test',+ CONTROL_API_REAL_PG_CONTEXT: 'owned-test',+ KUBERNETES_SERVICE_HOST: 'test-cluster',+}+function harness() {+ let time = 1000+ const delegated = []+ const fetch = createOAuthFixtureFetch(+ (...args) => {+ delegated.push(args)+ return 'delegated'+ },+ { now: () => time }+ )+ const post = (path, data) =>+ fetch(`${base}${path}`, {+ method: 'POST',+ body: path === '/oauth/token' ? new URLSearchParams(data).toString() : JSON.stringify(data),+ })+ return {+ fetch,+ post,+ delegated,+ expire: () => {+ time += 300001+ },+ }+}+async function device(h) {+ return (await h.post('/api/accounts/deviceauth/usercode', { client_id: 'fixture-client' })).json()+}+async function exchange(h, start) {+ const poll = { device_auth_id: start.device_auth_id, user_code: start.user_code }+ assert.equal((await h.post('/api/accounts/deviceauth/token', poll)).status, 403)+ const code = await (await h.post('/api/accounts/deviceauth/token', poll)).json()+ return {+ grant_type: 'authorization_code',+ client_id: 'fixture-client',+ code: code.authorization_code,+ code_verifier: code.code_verifier,+ redirect_uri: `${base}/deviceauth/callback`,+ }+}+test('requires every isolated runtime binding', () => {+ validateFixtureEnvironment(env)+ for (const key of Object.keys(env))+ assert.throws(() => validateFixtureEnvironment({ ...env, [key]: '' }))+ assert.throws(() => validateFixtureEnvironment({ ...env, NODE_ENV: 'production' }))+ assert.throws(() =>+ validateFixtureEnvironment({ ...env, CONTROL_API_REAL_PG_CONTEXT: 'different' })+ )+})+test('pending, successful exchange, unique accounts and replay rejection', async () => {+ const h = harness()+ const subjects = new Set()+ for (let i = 0; i < 2; i++) {+ const body = await exchange(h, await device(h))+ const response = await h.post('/oauth/token', body)+ assert.equal(response.status, 200)+ const result = await response.json()+ const claims = JSON.parse(Buffer.from(result.id_token.split('.')[1], 'base64url'))+ assert.equal(claims.sub, claims['https://api.openai.com/auth'].chatgpt_account_id)+ subjects.add(claims.sub)+ assert.equal((await h.post('/oauth/token', body)).status, 400)+ }+ assert.equal(subjects.size, 2)+ assert.equal(h.delegated.length, 0)+})+test('rejects wrong bindings without consuming the valid exchange', async () => {+ const h = harness()+ const body = await exchange(h, await device(h))+ for (const key of Object.keys(body))+ assert.equal((await h.post('/oauth/token', { ...body, [key]: 'wrong' })).status, 400)+ assert.equal((await h.post('/oauth/token', body)).status, 200)+})+test('expired devices and exhausted capacity fail locally', async () => {+ const h = harness()+ const first = await device(h)+ for (let i = 1; i < 32; i++) await device(h)+ assert.equal(+ (await h.post('/api/accounts/deviceauth/usercode', { client_id: 'fixture-client' })).status,+ 400+ )+ h.expire()+ assert.equal((await h.post('/api/accounts/deviceauth/token', first)).status, 400)+ assert.equal(+ (await h.post('/api/accounts/deviceauth/usercode', { client_id: 'fixture-client' })).status,+ 200+ )+})+test('intercepts only the exact boundary and rejects unsupported input forms', async () => {+ const h = harness()+ const init = { method: 'POST', body: '{}' }+ assert.equal(await h.fetch('https://application.test/api/login', init), 'delegated')+ assert.deepEqual(h.delegated, [['https://application.test/api/login', init]])+ const url = `${base}/oauth/token`+ assert.equal((await h.fetch(`${base}/oauth/revoke`, init)).status, 400)+ assert.equal((await h.fetch(`${base}/oauth/authorize`, init)).status, 400)+ for (const [input, options] of [+ [url, {}],+ [url, { ...init, body: 'a'.repeat(16385) }],+ [`${url}?extra=1`, init],+ [new Request(url, init), {}],+ ]) {+ assert.equal((await h.fetch(input, options)).status, 400)+ }+ assert.equal(h.delegated.length, 1)+})diff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-setup/README.md b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/README.mdindex 795b30532..e8a3f7c40 100644--- a/tests/e2e/fixtures/codex-subscription/approved-tools-setup/README.md+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/README.md@@ -1,44 +1,45 @@# Owned Minikube setup for Codex approved tools-The setup source for synthetic subscription consent (`seed.mjs`) is currently-blocked by the local content-control hook. It is deliberately absent. The-prepare command checks that file before any cluster mutation; this harness-must not be reported as runnable or certified until the blocked source is-reviewed and installed. No runtime, account or E2E success is implied by the-hermetic manifest tests.+The deterministic setup uses a separate Control API image with a guarded external+OAuth provider fixture. It creates fresh test identities with parameterized transactional SQL and the+existing audit adapter, without changing the production OAuth implementation.+The browser still performs login, consent, connector approvals, subscription+binding and execution. Hermetic lifecycle checks alone do not certify that journey.-The intended seed uses existing Control API services to create a fresh Desktop-user/team, encrypted synthetic subscription consent, and the real proxy catalog-sync. It must not approve connectors, bind subscriptions to Hosts or manufacture-business results. Those actions belong to the visible browser journey.+The fixture requires `NODE_ENV=test`, `EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE=1`,+a fresh `APPROVED_TOOLS_RUN_ID`, matching branch-owned `MINIKUBE_PROFILE` and+`CONTROL_API_REAL_PG_CONTEXT`, and the pod's `KUBERNETES_SERVICE_HOST`. Preparation+waits for the fixture API rollout and checks its live process marker against the+run, profile, deployment UID and fixture image before creating or cleaning identities.## Entry pointsAll commands use the verified `MINIKUBE_PROFILE`, matching explicit`CONTROL_API_REAL_PG_CONTEXT` and the canonical branch mutation lease. Use Node24.-1. `make minikube-build-codex-approved-tools-fixtures` performs five image builds:- the normal Codex proxy, the deterministic proxy fixture, the MCP fixture,- the custom-coordinator SDK base, and the approved-tools workflow variant.+1. `make minikube-build-codex-approved-tools-fixtures` builds the normal Control API and Codex proxy, their deterministic fixture+ variants, the MCP fixture, the custom-coordinator SDK base, and the+ approved-tools workflow variant.Fixture tags do not replace production image tags. Run before reconcilebecause image acquisition updates the manifest timestamp. Preparation checks- the live image IDs, each image's recorded source revision, and both derived+ the live image IDs, each image's recorded source revision, and all three derivedbase-image bindings before changing cluster resources.2. Complete the supported profile reconcile and exact-HEAD validation sequence.3. `make minikube-run-codex-approved-tools` prepares isolated resources, runs the- visible Playwright runner and restores the original proxy image/environment.+ visible Playwright runner and restores the original proxy and Control API images/environments.It can be the required Playwright command inside T2 after image acquisition.4. Alternatively, `make minikube-prepare-codex-approved-tools` leaves the fixtureactive for investigation. Use `make minikube-restore-codex-approved-tools` with- the same evidence directory to restore the recorded proxy and stop only this+ the same evidence directory to restore the recorded API/proxy and stop only thisrun's owned forwards.Required environment: `APPROVED_TOOLS_CANONICAL_ROOT`, fresh existing childdirectory `APPROVED_TOOLS_EVIDENCE_DIR` under canonical `.local-notes/infra/runs`,`APPROVED_TOOLS_UPSTREAM_MODE=deterministic`, existing admin login variables-`TEST_ADMIN_USERNAME`/`TEST_ADMIN_PASSWORD`, fresh isolated member-`TEST_USER_EMAIL`/`TEST_USER_PASSWORD`, and the owned Control UI/REST/RPC URLs-required by the Playwright runner. Credentials stay in the process environment+`TEST_ADMIN_USERNAME`/`TEST_ADMIN_PASSWORD`, isolated member and unauthorized-user passwords+`TEST_USER_PASSWORD`/`APPROVED_TOOLS_UNAUTHORIZED_PASSWORD`, and the owned Control UI/REST/RPC URLs+required by the Playwright runner. Preparation assigns fresh `${run}@example.test` and `${run}[email protected]`+identities to both setup and the runner. Credentials stay in the process environmentand stdin; never put them in scenario metadata, logs or command arguments.The normal Minikube overlay already enables the Control API, proxy and Host Codex@@ -46,7 +47,7 @@ feature gates. Preparation checks effective running Control API/proxy flags andthe Host config map, and refuses disabled/stale workloads. Apply the supportedoverlay/reconcile if those preconditions fail; preparation does not weaken gates.-The three Contexts start with empty connector lists. Hosts have an unassigned+The four Contexts start with empty connector lists. Hosts have an unassignedCodex subscription and no fallback provider. McpServer CRDs are available butnot granted; HCC builds their deployments and network boundaries. Server dry-runand creation roundtrip check that fields survive the installed CRD schemas.@@ -58,18 +59,44 @@ revalidate the same live process identity. Existing profile `ports.env` staysunchanged. Restoration rejects foreign worktrees, deployments, images andfixture-run markers. A later commit in the same owned worktree is recorded inthe restoration audit; it does not prevent cleanup of verified owned forwards.-The proxy update checks its live object version and run marker. A refused proxy+Both deployment updates check the live object version and run marker. Original+API image, pull policy and only affected environment keys are captured and+validated for restoration before the first mutation. A refused proxyrestore still attempts owned-forward cleanup and never reports restored=true.Scenario metadata is written to `scenarios.json` and passed directly to the runnerin `run` mode. It contains no credentials. State records retain only fixture-identity, ports, original image/pull policy and the non-sensitive NODE_ENV value.+identity, ports, original image/pull policies and the affected, validated non-sensitive environment values.Created Kubernetes resources are journaled individually with their server UIDand version. Restoration deletes them in dependency order after checking thecurrent run labels and UID, using UID/version preconditions. Ambiguous creationand legacy journals fail closed and require explicit recovery; they are never-deleted by name alone. Database fixture cleanup remains pending with the absent-seed implementation, so this does not certify a complete E2E cleanup.+deleted by name alone. Each visible subscription creation first reserves `created-connection-<scenario>.json`+in the owned evidence directory. Its optional page callback records only the public+response ID, connection key, display name and creator metadata, bound to the run,+profile, scenario and fixture user, in a flushed `0600` file before subsequent+assertions. It never records credentials. Restoration validates and incorporates+those captures into the identity journal; exact repeated entries are idempotent,+while pending, replaced, foreign or conflicting captures block identity cleanup.+The fixture user binding identifies the run; it does not claim that the fixture+user created the administrative connection (`createdBy` is null). Real mode uses+its existing connection and never opens a capture file.++After owned resources are removed, identity cleanup runs while the fixture API+is still active. Recorded subscriptions are revoked through the normal connection+service, preserving tombstones and audit history. After the database transaction,+the existing allowlist writer must successfully publish the updated runtime+ConfigMap before cleanup reports success. A publication failure remains+recoverable even when the database deletion already committed.+The original API is restored and awaited even if another cleanup+step fails. On a later restore, pending identity cleanup may temporarily reinstall+the fixture only when the live API UID, original image, pull policy and affected+environment still match the recorded snapshot and resource cleanup is complete.+The reinstall uses the current resource version and the same run binding, waits+for Ready and verifies the live marker. Cleanup then retries, and the original API+is restored again even if that attempt fails. Completed identity cleanup does not+reinstall the fixture. A failed resource, identity, deployment or forward cleanup prevents+`restored=true`; its recorded evidence must be resolved before another run.Real subscription tests do not use this synthetic prepare path. They require theseparately approved account/preconditions and production proxy image. Refusingdiff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.mjs b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.mjsnew file mode 100644index 000000000..62b046099--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.mjs@@ -0,0 +1,646 @@+import { randomUUID } from 'node:crypto'++const labels = ['83', '150', '250', 'workflow']+const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/++function requireValue(condition, message) {+ if (!condition) throw new Error(message)+}++function binding(input, env) {+ requireValue(/^approved-tools-[a-f0-9]{12}$/.test(input?.run ?? ''), 'Invalid fixture run')+ requireValue(+ input.mode === 'deterministic' &&+ env.NODE_ENV === 'test' &&+ env.EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE === '1' &&+ env.APPROVED_TOOLS_RUN_ID === input.run &&+ /^[a-z0-9][a-z0-9-]{0,62}$/.test(input.profile ?? '') &&+ input.context === input.profile &&+ env.MINIKUBE_PROFILE === input.profile &&+ env.CONTROL_API_REAL_PG_CONTEXT === input.context,+ 'Fixture environment binding mismatch'+ )+ return { mode: input.mode, run: input.run, profile: input.profile, context: input.context }+}++function identities(run) {+ return [run, `${run}-unauthorized`].map(name => ({ name, email: `${name}@example.test` }))+}++function scenarioGrants(input) {+ requireValue(+ Array.isArray(input.scenarios) && input.scenarios.length === 4,+ 'Expected four scenarios'+ )+ const expected = labels.map(label => ({+ runId: `${input.run}-${label}`,+ agentName: `${input.run}-agent-${label}`,+ contextName: `${input.run}-context-${label}`,+ }))+ for (const [index, value] of expected.entries()) {+ requireValue(+ Object.entries(value).every(([key, item]) => input.scenarios[index]?.[key] === item),+ 'Scenario ownership mismatch'+ )+ }+ return {+ agents: expected.map(value => value.agentName),+ contexts: expected.map(value => value.contextName),+ workflow: { namespace: 'sandbox-recipes', name: `${input.run}-recipe` },+ }+}++function validateJournal(journal, input, env) {+ const scope = binding(input, env)+ requireValue(+ journal &&+ Object.keys(journal).every(key =>+ [+ 'version',+ 'mode',+ 'run',+ 'profile',+ 'context',+ 'status',+ 'users',+ 'team',+ 'grants',+ 'connections',+ 'cleanupOutcome',+ ].includes(key)+ ),+ 'Unexpected identity journal fields'+ )+ requireValue(+ journal?.version === 1 && Object.entries(scope).every(([key, value]) => journal[key] === value),+ 'Identity journal binding mismatch'+ )+ const expected = identities(input.run)+ requireValue(+ Array.isArray(journal.users) &&+ journal.users.length === 2 &&+ journal.users.every(+ (user, index) =>+ Object.keys(user).length === 3 &&+ uuid.test(user.id ?? '') &&+ user.name === expected[index].name &&+ user.email === expected[index].email+ ) &&+ uuid.test(journal.team?.id ?? '') &&+ Object.keys(journal.team).length === 2 &&+ journal.team.name === `${input.run}-team` &&+ new Set([...journal.users.map(user => user.id), journal.team.id]).size === 3,+ 'Invalid recorded identity ownership'+ )+ const grants = scenarioGrants(input)+ requireValue(JSON.stringify(journal.grants) === JSON.stringify(grants), 'Journal grant mismatch')+ validateConnectionEvidence(journal)+ requireValue(+ ['creation-pending', 'created', 'recovery-required', 'cleanup-pending', 'cleaned'].includes(+ journal.status+ ),+ 'Invalid identity journal status'+ )+ requireValue(+ journal.cleanupOutcome === undefined ||+ ['recorded-identities-absent', 'deleted-with-audit-retained'].includes(+ journal.cleanupOutcome+ ),+ 'Invalid cleanup outcome'+ )+ return grants+}++async function persist(save, journal) {+ // Pass a detached snapshot: adapters cannot accidentally persist later mutations.+ await save(structuredClone(journal))+}++// Allocate public fixture identity metadata on the host before remote mutation.+export function createFixtureIdentityJournal(input, { env }) {+ const scope = binding(input, env)+ return {+ version: 1,+ ...scope,+ status: 'creation-pending',+ users: identities(input.run).map(user => ({ ...user, id: randomUUID() })),+ team: { id: randomUUID(), name: `${input.run}-team` },+ grants: scenarioGrants(input),+ connections: [],+ }+}++function validateConnectionEvidence(journal) {+ requireValue(+ Array.isArray(journal.connections) && journal.connections.length <= 4,+ 'Connection journal is required'+ )+ const fields = ['scenario', 'fixtureUserId', 'id', 'connectionKey', 'displayName', 'createdBy']+ for (const connection of journal.connections) {+ requireValue(+ connection &&+ Object.keys(connection).length === fields.length &&+ Object.keys(connection).every(key => fields.includes(key)) &&+ labels.includes(connection.scenario) &&+ uuid.test(connection.id ?? '') &&+ /^codex-[a-f0-9]{16}$/.test(connection.connectionKey ?? '') &&+ connection.displayName === `Codex fixture ${connection.scenario} ${journal.run}` &&+ connection.fixtureUserId === journal.users[0].id &&+ connection.createdBy === null,+ 'Invalid public connection creation evidence'+ )+ }+ for (const field of ['scenario', 'id', 'connectionKey'])+ requireValue(+ new Set(journal.connections.map(value => value[field])).size === journal.connections.length,+ 'Duplicate connection creation evidence'+ )+}++/** Called on the host with safe fields from the successful visible POST response.+ * fixtureUserId associates the experiment; it does not claim that Desktop user+ * created the connection. The real admin creation route stores created_by=NULL.+ * Persist immediately. A lost POST response is not recoverable by name adoption.+ */+export function recordFixtureConnection(input, journal, { env }, evidence) {+ validateJournal(journal, input, env)+ requireValue(+ journal.status === 'created',+ 'Identity creation must finish before UI grant creation'+ )+ const proposed = structuredClone(journal)+ proposed.connections.push(structuredClone(evidence))+ validateConnectionEvidence(proposed)+ journal.connections = proposed.connections+ return journal+}++async function revokeRecordedConnections(db, journal, revoke, rebuild) {+ const expectedNames = labels.map(label => `Codex fixture ${label} ${journal.run}`)+ // This bounded name query detects unjournaled POST outcomes only. Names never+ // supply deletion/revocation authority; every returned row needs recorded ID.+ const rows = (+ await db.query(+ `SELECT id::text, connection_key, display_name, created_by, status, revoked_at+ FROM codex_subscription_connections WHERE connection_key = ANY($1::text[])+ OR display_name = ANY($2::text[]) ORDER BY id FOR UPDATE`,+ [journal.connections.map(value => value.connectionKey), expectedNames]+ )+ ).rows+ requireValue(+ rows.length === journal.connections.length &&+ rows.every(row =>+ journal.connections.some(+ expected =>+ expected.id === row.id &&+ expected.connectionKey === row.connection_key &&+ expected.displayName === row.display_name &&+ expected.createdBy === row.created_by+ )+ ),+ 'Unrecorded or changed connection; retain identities for recovery'+ )+ if (!rows.length) return+ requireValue(+ typeof revoke === 'function' && typeof rebuild === 'function',+ 'Normal connection revocation and catalog adapters are required'+ )+ for (const row of rows) {+ if (row.revoked_at !== null) {+ requireValue(row.status === 'revoked', 'Invalid retained connection state')+ continue+ }+ const result = await revoke(db, row.connection_key)+ requireValue(+ result?.id === row.id &&+ result.connectionKey === row.connection_key &&+ result.status === 'revoked' &&+ result.revokedAt instanceof Date &&+ Number.isFinite(result.revokedAt.getTime()),+ 'Connection revocation identity mismatch'+ )+ }+ await rebuild(db)+}++/**+ * Only test preconditions: fresh Desktop identities and access to fixture Hosts/Contexts.+ * No invitation, subscription consent, connection, tool approval, or business result.+ * withTransaction must use one real transaction and roll back on any callback error.+ * hashPassword is the installed bcrypt.hash; saveJournal durably saves a private owned file.+ */+export async function createFixtureIdentities(+ input,+ { env, withTransaction, hashPassword, appendPermissionEvents, saveJournal, initialJournal }+) {+ binding(input, env)+ const grants = scenarioGrants(input)+ const users = identities(input.run)+ const journal = structuredClone(initialJournal)+ validateJournal(journal, input, env)+ requireValue(+ journal.status === 'creation-pending' &&+ journal.connections.length === 0 &&+ journal.cleanupOutcome === undefined,+ 'Expected a fresh identity intent'+ )+ requireValue(+ input.userEmail === users[0].email && input.unauthorizedEmail === users[1].email,+ 'Expected exact run-bound synthetic emails'+ )+ const passwords = [input.userPassword, input.unauthorizedPassword]+ requireValue(+ passwords.every(+ value =>+ typeof value === 'string' &&+ value === value.trim() &&+ value.length >= 12 &&+ Buffer.byteLength(value, 'utf8') <= 72 &&+ !/[\u0000-\u001f\u007f]/.test(value)+ ),+ 'Invalid fixture password'+ )+ requireValue(+ typeof appendPermissionEvents === 'function' && typeof saveJournal === 'function',+ 'Audit and durable journal adapters are required'+ )+ const hashes = await Promise.all(passwords.map(value => hashPassword(value, 12)))+ requireValue(+ hashes.every(+ value => typeof value === 'string' && /^\$2[aby]\$12\$[./A-Za-z0-9]{53}$/.test(value)+ ),+ 'Expected installed bcrypt password hashes'+ )+ await persist(saveJournal, journal)+ try {+ await withTransaction(async db => {+ await db.query("SET LOCAL statement_timeout = '15s'")+ await db.query("SET LOCAL lock_timeout = '5s'")+ for (const [index, user] of journal.users.entries()) {+ await db.query(+ `INSERT INTO users(id, email, name, password_hash, password_set_at)+ VALUES ($1::uuid, $2, $3, $4, NOW())`,+ [user.id, user.email, user.name, hashes[index]]+ )+ await db.query('INSERT INTO profiles(user_id, display_name) VALUES ($1::uuid, $2)', [+ user.id,+ user.name,+ ])+ }+ await db.query('INSERT INTO teams(id, name) VALUES ($1::uuid, $2)', [+ journal.team.id,+ journal.team.name,+ ])+ for (const user of journal.users) {+ await db.query(+ `INSERT INTO team_members(team_id, user_id, role, status)+ VALUES ($1::uuid, $2::uuid, 'member', 'active')`,+ [journal.team.id, user.id]+ )+ }+ // No team grants: sharing the empty team must not authorize the negative user.+ const userId = journal.users[0].id+ for (const agent of grants.agents)+ await db.query('INSERT INTO user_agents(user_id, agent_name) VALUES ($1::uuid, $2)', [+ userId,+ agent,+ ])+ for (const context of grants.contexts)+ await db.query('INSERT INTO user_contexts(user_id, context_id) VALUES ($1::uuid, $2)', [+ userId,+ context,+ ])+ // Current schema consolidates recipe discovery/approval eligibility into+ // user_workflow_triggers; the legacy allowed-users table was dropped.+ await db.query(+ `INSERT INTO user_workflow_triggers(user_id, recipe_namespace, recipe_name)+ VALUES ($1::uuid, $2, $3)`,+ [userId, grants.workflow.namespace, grants.workflow.name]+ )+ await appendFixturePermissions(db, journal, 'grant', appendPermissionEvents, true)+ })+ journal.status = 'created'+ await persist(saveJournal, journal)+ return journal+ } catch {+ // A failed COMMIT acknowledgement is ambiguous. Recorded random IDs permit+ // recovery without inferring ownership from a later same-email lookup.+ journal.status = 'recovery-required'+ await persist(saveJournal, journal)+ throw new Error('Fixture creation failed; recover using the recorded identity journal')+ }+}++function permissionEvents(journal, action, includeWorkflow) {+ const subject = { kind: 'user', id: journal.users[0].id }+ return {+ operatorSub: subject.id,+ operatorKind: 'platform_user',+ requestId: journal.run,+ changes: [+ ...journal.users.flatMap(user => [+ {+ action,+ resourceClass: 'platform_user_access',+ resourceRef: `platform_user:${user.id}`,+ subject: { kind: 'user', id: user.id },+ status: action === 'grant' ? 'account_created' : 'account_deleted',+ },+ {+ action,+ resourceClass: 'team_membership',+ resourceRef: `team_membership:${journal.team.id}:role:member`,+ subject: { kind: 'user', id: user.id },+ teamId: journal.team.id,+ },+ ]),+ ...journal.grants.agents.map(agent => ({+ action,+ resourceClass: 'agent_access',+ resourceRef: `agent:${agent}`,+ subject,+ })),+ ...journal.grants.contexts.map(context => ({+ action,+ resourceClass: 'context_access',+ resourceRef: `context:${context}`,+ subject,+ })),+ ...(includeWorkflow+ ? [+ {+ action,+ resourceClass: 'workflow_trigger_access',+ resourceRef: `workflow_recipe:${journal.grants.workflow.namespace}/${journal.grants.workflow.name}`,+ subject,+ namespace: journal.grants.workflow.namespace,+ },+ ]+ : []),+ ],+ }+}++async function appendFixturePermissions(db, journal, action, append, includeWorkflow) {+ const events = permissionEvents(journal, action, includeWorkflow)+ events.operationId = randomUUID()+ if (!includeWorkflow) {+ await append(db, events)+ return+ }+ const id = journal.users[0].id+ await db.query(+ `INSERT INTO trigger_grants_audit(operator_user_id, target_user_id,+ recipe_namespace, recipe_name, action, payload_json)+ VALUES ($1::uuid, $1::uuid, $2, $3, $4, $5::jsonb)`,+ [+ id,+ journal.grants.workflow.namespace,+ journal.grants.workflow.name,+ action,+ JSON.stringify({+ before: action === 'grant' ? [] : [id],+ after: action === 'grant' ? [id] : [],+ administrative_operation_id: events.operationId,+ }),+ ]+ )+ events.changes.at(-1).sourceAuditRef =+ `trigger_grants_audit:operation:${events.operationId}:action:${action}`+ await append(db, events)+}++/**+ * Legacy deletion is permitted only for fresh active users with no operator-link+ * history, matching adminDeleteUser's retention boundary. Retained-history cases+ * fail closed for governed retirement; no lifecycle history is erased here.+ * Parent FOR UPDATE locks also block new FK-dependent grants/memberships while+ * existing dependent rows are locked and checked within this same transaction.+ */+export async function cleanupFixtureIdentities(+ input,+ journal,+ {+ env,+ withTransaction,+ appendPermissionEvents,+ saveJournal,+ revokeCodexSubscriptionConnection,+ rebuildLiveCodexUnionAllowlist,+ publishRuntimeAllowlist,+ }+) {+ const grants = validateJournal(journal, input, env)+ requireValue(+ typeof appendPermissionEvents === 'function' &&+ typeof saveJournal === 'function' &&+ typeof publishRuntimeAllowlist === 'function',+ 'Audit, durable journal and runtime publication adapters are required'+ )+ journal.status = 'cleanup-pending'+ await persist(saveJournal, journal)+ try {+ const outcome = await withTransaction(async db => {+ await db.query("SET LOCAL statement_timeout = '15s'")+ await db.query("SET LOCAL lock_timeout = '5s'")+ const ids = journal.users.map(user => user.id)+ const users = (+ await db.query(+ `SELECT id::text, email, name, lifecycle_state FROM users+ WHERE id = ANY($1::uuid[]) ORDER BY id FOR UPDATE`,+ [ids]+ )+ ).rows+ const teams = (+ await db.query('SELECT id::text, name FROM teams WHERE id = $1::uuid FOR UPDATE', [+ journal.team.id,+ ])+ ).rows+ if (!users.length && !teams.length) {+ await revokeRecordedConnections(+ db,+ journal,+ revokeCodexSubscriptionConnection,+ rebuildLiveCodexUnionAllowlist+ )+ return 'recorded-identities-absent'+ }+ requireValue(+ users.length === 2 &&+ teams.length === 1 &&+ teams[0].name === journal.team.name &&+ users.every(+ user =>+ journal.users.some(+ expected =>+ expected.id === user.id &&+ expected.name === user.name &&+ expected.email === user.email+ ) && user.lifecycle_state === 'active'+ ),+ 'Identity ownership changed'+ )+ const profiles = (+ await db.query(+ 'SELECT user_id::text, display_name FROM profiles WHERE user_id = ANY($1::uuid[]) FOR UPDATE',+ [ids]+ )+ ).rows+ requireValue(+ profiles.length === 2 &&+ profiles.every(profile =>+ journal.users.some(+ user => user.id === profile.user_id && user.name === profile.display_name+ )+ ),+ 'Profile ownership changed'+ )+ const members = (+ await db.query(+ `SELECT team_id::text, user_id::text, role, status FROM team_members+ WHERE team_id = $1::uuid OR user_id = ANY($2::uuid[]) FOR UPDATE`,+ [journal.team.id, ids]+ )+ ).rows+ requireValue(+ members.length === 2 &&+ members.every(+ member =>+ member.team_id === journal.team.id &&+ ids.includes(member.user_id) &&+ member.role === 'member' &&+ member.status === 'active'+ ),+ 'Unrelated membership or changed role'+ )+ for (const [table, column, expected] of [+ ['user_agents', 'agent_name', grants.agents],+ ['user_contexts', 'context_id', grants.contexts],+ ]) {+ const rows = (+ await db.query(+ `SELECT user_id::text, ${column} AS resource FROM ${table}+ WHERE user_id = ANY($1::uuid[]) FOR UPDATE`,+ [ids]+ )+ ).rows+ requireValue(+ rows.length === expected.length &&+ new Set(rows.map(row => row.resource)).size === expected.length &&+ rows.every(row => row.user_id === ids[0] && expected.includes(row.resource)),+ 'Unrelated or changed user grants'+ )+ }+ const workflowRows = (+ await db.query(+ `SELECT user_id::text, recipe_namespace, recipe_name+ FROM user_workflow_triggers WHERE user_id = ANY($1::uuid[]) FOR UPDATE`,+ [ids]+ )+ ).rows+ requireValue(+ workflowRows.length <= 1 &&+ workflowRows.every(+ row =>+ row.user_id === ids[0] &&+ row.recipe_namespace === grants.workflow.namespace &&+ row.recipe_name === grants.workflow.name+ ),+ 'Unrelated or changed workflow grants'+ )+ for (const table of [+ 'team_agents',+ 'team_contexts',+ 'team_workflow_triggers',+ 'workflow_recipe_allowed_teams',+ ]) {+ const rows = (+ await db.query(`SELECT team_id FROM ${table} WHERE team_id = $1::uuid FOR UPDATE`, [+ journal.team.id,+ ])+ ).rows+ requireValue(rows.length === 0, 'Unrelated team grants')+ }+ const links = (+ await db.query(+ 'SELECT user_id FROM gfs_desktop_operator_links WHERE user_id = ANY($1::uuid[]) FOR UPDATE',+ [ids]+ )+ ).rows+ requireValue(+ links.length === 0,+ 'Operator-link history requires governed retirement; identities retained'+ )+ // Invitations are not created by this helper. Do not cascade unrelated ones.+ const invitations = (+ await db.query(+ `SELECT id FROM invitations WHERE team_id = $1::uuid+ OR accepted_user_id = ANY($2::uuid[]) OR email = ANY($3::text[]) FOR UPDATE`,+ [journal.team.id, ids, journal.users.map(user => user.email)]+ )+ ).rows+ const assignments = (+ await db.query(+ 'SELECT invitation_id FROM invitation_teams WHERE team_id = $1::uuid FOR UPDATE',+ [journal.team.id]+ )+ ).rows+ requireValue(+ !invitations.length && !assignments.length,+ 'Unexpected invitations; identities retained'+ )+ await revokeRecordedConnections(+ db,+ journal,+ revokeCodexSubscriptionConnection,+ rebuildLiveCodexUnionAllowlist+ )+ // Preserve the normal account-deletion revocation behavior before deleting.+ await db.query(+ `UPDATE workflow_approval_medium_accounts SET disabled_at = COALESCE(disabled_at, NOW()),+ updated_at = NOW() WHERE user_id = ANY($1::uuid[]) AND disabled_at IS NULL`,+ [ids]+ )+ await db.query(+ `UPDATE workflow_approval_medium_challenges SET consumed_at = COALESCE(consumed_at, NOW()),+ expires_at = LEAST(expires_at, NOW()) WHERE user_id = ANY($1::uuid[]) AND consumed_at IS NULL`,+ [ids]+ )+ // WRC reconcileDelete may already have removed the exact recipe grant.+ // Only claim a workflow revocation when this transaction removes a row.+ await appendFixturePermissions(+ db,+ journal,+ 'revoke',+ appendPermissionEvents,+ workflowRows.length === 1+ )+ for (const user of journal.users) {+ const result = await db.query(+ `DELETE FROM users WHERE id = $1::uuid AND email = $2 AND name = $3+ AND lifecycle_state = 'active' RETURNING id`,+ [user.id, user.email, user.name]+ )+ requireValue(result.rowCount === 1, 'User deletion ownership mismatch')+ }+ const result = await db.query(+ 'DELETE FROM teams WHERE id = $1::uuid AND name = $2 RETURNING id',+ [journal.team.id, journal.team.name]+ )+ requireValue(result.rowCount === 1, 'Team deletion ownership mismatch')+ return 'deleted-with-audit-retained'+ })+ // The ConfigMap writer reads committed state through its own DB client.+ // Never hold identity locks during K8s publication. Even the absent-ID retry+ // must republish: a preceding attempt may have committed then failed here.+ await publishRuntimeAllowlist()+ journal.status = 'cleaned'+ journal.cleanupOutcome = outcome+ await persist(saveJournal, journal)+ return { outcome, auditRetention: 'preserved' }+ } catch {+ journal.status = 'recovery-required'+ await persist(saveJournal, journal)+ throw new Error('Fixture cleanup refused or failed; retain journal for recovery')+ }+}diff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.test.mjs b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.test.mjsnew file mode 100644index 000000000..5fd7d9ed2--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/identity-lifecycle.test.mjs@@ -0,0 +1,543 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import {+ cleanupFixtureIdentities,+ createFixtureIdentityJournal,+ createFixtureIdentities as createRecordedFixtureIdentities,+ recordFixtureConnection,+} from './identity-lifecycle.mjs'++async function createFixtureIdentities(input, deps) {+ return createRecordedFixtureIdentities(input, {+ ...deps,+ initialJournal: createFixtureIdentityJournal(input, { env: deps.env }),+ })+}++const run = 'approved-tools-aabbccddeeff'+const input = {+ mode: 'deterministic',+ run,+ profile: 'owned-e2e',+ context: 'owned-e2e',+ userEmail: `${run}@example.test`,+ unauthorizedEmail: `${run}[email protected]`,+ userPassword: 'fixture-only-member-password',+ unauthorizedPassword: 'fixture-only-negative-password',+ scenarios: ['83', '150', '250', 'workflow'].map(label => ({+ runId: `${run}-${label}`,+ agentName: `${run}-agent-${label}`,+ contextName: `${run}-context-${label}`,+ })),+}+const env = {+ NODE_ENV: 'test',+ EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE: '1',+ APPROVED_TOOLS_RUN_ID: run,+ MINIKUBE_PROFILE: input.profile,+ CONTROL_API_REAL_PG_CONTEXT: input.context,+}++function harness() {+ const state = {+ calls: [],+ journal: [],+ committed: [],+ events: [],+ rollbacks: 0,+ commits: 0,+ publications: 0,+ transactionActive: false,+ }+ const adapters = {+ env,+ // Synthetic hash is intentional: tests verify wiring and never authenticate.+ hashPassword: async (password, rounds) => {+ assert.equal(rounds, 12)+ assert.ok([input.userPassword, input.unauthorizedPassword].includes(password))+ return '$2b$12$' + 'a'.repeat(53)+ },+ saveJournal: async value => {+ assert.ok(!JSON.stringify(value).includes('password'))+ state.journal.push(structuredClone(value))+ },+ publishRuntimeAllowlist: async () => {+ assert.equal(state.transactionActive, false, 'publish only after transaction completion')+ state.publications+++ if (state.publicationFailure) throw new Error('synthetic publication failure')+ },+ appendPermissionEvents: async (db, value) => {+ assert.equal(db, state.db)+ if (state.auditFailure) throw new Error('audit failure')+ state.events.push(value)+ },+ withTransaction: async callback => {+ const pending = []+ const db = {+ query: async (sql, values = []) => {+ state.calls.push({ sql, values })+ if (state.failQuery?.(sql)) throw new Error('synthetic query failure')+ pending.push({ sql, values })+ if (state.respond) return state.respond(sql, values)+ return { rows: [], rowCount: 1 }+ },+ }+ state.db = db+ state.transactionActive = true+ try {+ const result = await callback(db)+ state.committed.push(...pending)+ state.commits+++ if (state.commitLost) throw new Error('commit response lost')+ return result+ } catch (error) {+ state.rollbacks+++ throw error+ } finally {+ state.transactionActive = false+ }+ },+ }+ return { state, adapters }+}++test('remote creation preserves host-recorded IDs and refuses a reused intent', async () => {+ const { state, adapters } = harness()+ const initialJournal = createFixtureIdentityJournal(input, { env })+ const original = structuredClone(initialJournal)+ const created = await createRecordedFixtureIdentities(input, { ...adapters, initialJournal })+ assert.deepEqual(created.users, original.users)+ assert.deepEqual(created.team, original.team)+ assert.deepEqual(initialJournal, original)+ const calls = state.calls.length+ await assert.rejects(+ createRecordedFixtureIdentities(input, { ...adapters, initialJournal: created }),+ /fresh identity intent/+ )+ const prebound = structuredClone(initialJournal)+ prebound.connections.push(connectionEvidence(prebound))+ await assert.rejects(+ createRecordedFixtureIdentities(input, { ...adapters, initialJournal: prebound }),+ /fresh identity intent/+ )+ assert.equal(state.calls.length, calls)+})++function cleanupRows(journal, overrides = {}) {+ return sql => {+ const table = /FROM ([a-z_]+)/.exec(sql)?.[1]+ if (sql.startsWith('DELETE')) return { rowCount: 1, rows: [{ id: 'deleted' }] }+ const rows =+ {+ users: journal.users.map(user => ({ ...user, lifecycle_state: 'active' })),+ profiles: journal.users.map(user => ({ user_id: user.id, display_name: user.name })),+ teams: [journal.team],+ team_members: journal.users.map(user => ({+ user_id: user.id,+ team_id: journal.team.id,+ role: 'member',+ status: 'active',+ })),+ user_agents: journal.grants.agents.map(resource => ({+ user_id: journal.users[0].id,+ resource,+ })),+ user_contexts: journal.grants.contexts.map(resource => ({+ user_id: journal.users[0].id,+ resource,+ })),+ user_workflow_triggers: [+ {+ user_id: journal.users[0].id,+ recipe_namespace: journal.grants.workflow.namespace,+ recipe_name: journal.grants.workflow.name,+ },+ ],+ ...overrides,+ }[table] ?? []+ return { rows, rowCount: rows.length }+ }+}++test('creation is atomic, journals random IDs before mutation, and only grants authorized user', async () => {+ const { state, adapters } = harness()+ const original = adapters.withTransaction+ adapters.withTransaction = work => {+ assert.equal(state.journal[0].status, 'creation-pending')+ assert.equal(state.journal[0].users.length, 2)+ return original(work)+ }+ const journal = await createFixtureIdentities(input, adapters)+ assert.equal(journal.status, 'created')+ assert.equal(state.commits, 1)+ assert.equal(state.calls.filter(call => call.sql.includes('INSERT INTO users(')).length, 2)+ const grants = state.calls.filter(call => /INSERT INTO user_(agents|contexts)/.test(call.sql))+ assert.equal(grants.length, 8)+ assert.ok(grants.every(call => call.values[0] === journal.users[0].id))+ assert.ok(+ state.calls.every(+ call =>+ !/ON CONFLICT|invitations|subscription|connection|UPDATE users|INSERT INTO team_(agents|contexts)/i.test(+ call.sql+ )+ )+ )+ const workflow = state.calls.find(call =>+ call.sql.startsWith('INSERT INTO user_workflow_triggers')+ )+ assert.deepEqual(workflow.values, [journal.users[0].id, 'sandbox-recipes', `${run}-recipe`])+ assert.ok(state.calls.some(call => call.sql.startsWith('INSERT INTO trigger_grants_audit')))+ assert.equal(state.events[0].changes.length, 13)+})++test('environment, run, scenario, synthetic email and password gates precede mutations', async () => {+ for (const mutate of [+ (i, a) => {+ a.env = { ...env, NODE_ENV: 'production' }+ },+ (i, a) => {+ a.env = { ...env, EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE: '0' }+ },+ (i, a) => {+ a.env = { ...env, APPROVED_TOOLS_RUN_ID: 'other' }+ },+ i => {+ i.context = 'foreign'+ },+ i => {+ i.userEmail = '[email protected]'+ },+ i => {+ i.unauthorizedEmail = i.userEmail+ },+ i => {+ i.userPassword = 'x'.repeat(73)+ },+ i => {+ i.scenarios[0].agentName = 'foreign-agent'+ },+ i => {+ i.scenarios.push(i.scenarios[0])+ },+ ]) {+ const { state, adapters } = harness()+ const value = structuredClone(input)+ mutate(value, adapters)+ await assert.rejects(createFixtureIdentities(value, adapters))+ assert.equal(state.calls.length, 0)+ assert.equal(state.journal.length, 0)+ }+})++test('duplicate/query and audit failures roll back without discarding the intent journal', async () => {+ for (const kind of ['query', 'audit']) {+ const { state, adapters } = harness()+ if (kind === 'query') state.failQuery = sql => sql.includes('INSERT INTO teams')+ else state.auditFailure = true+ await assert.rejects(createFixtureIdentities(input, adapters), /recover using/)+ assert.equal(state.committed.length, 0)+ assert.equal(state.rollbacks, 1)+ assert.equal(state.journal.at(-1).status, 'recovery-required')+ assert.deepEqual(state.journal[0].users, state.journal.at(-1).users)+ }+})++test('lost commit acknowledgement retains exact IDs rather than retrying insertion', async () => {+ const { state, adapters } = harness()+ state.commitLost = true+ await assert.rejects(createFixtureIdentities(input, adapters), /recover using/)+ assert.equal(state.commits, 1)+ assert.equal(state.journal.at(-1).status, 'recovery-required')+ assert.deepEqual(state.journal[0].users, state.journal.at(-1).users)+})++test('ordinary cleanup locks ownership and dependencies and preserves audit behavior', async () => {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ state.calls = []+ state.respond = cleanupRows(journal)+ const outcome = await cleanupFixtureIdentities(input, journal, adapters)+ assert.deepEqual(outcome, { outcome: 'deleted-with-audit-retained', auditRetention: 'preserved' })+ assert.equal(journal.status, 'cleaned')+ const deletes = state.calls.filter(call => call.sql.startsWith('DELETE'))+ assert.equal(deletes.length, 3)+ assert.deepEqual(deletes[0].values, [+ journal.users[0].id,+ journal.users[0].email,+ journal.users[0].name,+ ])+ assert.ok(+ state.calls+ .filter(call => call.sql.startsWith('SELECT'))+ .every(call => call.sql.includes('FOR UPDATE'))+ )+ assert.equal(+ state.calls.filter(call => call.sql.startsWith('UPDATE workflow_approval_medium_')).length,+ 2+ )+ assert.ok(state.events.at(-1).changes.every(change => change.action === 'revoke'))+})++test('cleanup refuses foreign ownership, memberships, grants, invitations and retained links before mutation', async () => {+ for (const makeOverride of [+ j => ({+ users: j.users.map(user => ({ ...user, name: 'foreign', lifecycle_state: 'active' })),+ }),+ j => ({ profiles: j.users.map(user => ({ user_id: user.id, display_name: 'foreign' })) }),+ () => ({+ team_members: [{ team_id: 'foreign', user_id: 'foreign', role: 'admin', status: 'active' }],+ }),+ j => ({ user_agents: [{ user_id: j.users[1].id, resource: j.grants.agents[0] }] }),+ j => ({ team_contexts: [{ team_id: j.team.id }] }),+ j => ({+ user_workflow_triggers: [+ { user_id: j.users[0].id, recipe_namespace: 'foreign', recipe_name: 'foreign' },+ ],+ }),+ j => ({ team_workflow_triggers: [{ team_id: j.team.id }] }),+ j => ({ gfs_desktop_operator_links: [{ user_id: j.users[0].id }] }),+ () => ({ invitations: [{ id: 'retained' }] }),+ () => ({ invitation_teams: [{ invitation_id: 'retained' }] }),+ ]) {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ state.calls = []+ state.respond = cleanupRows(journal, makeOverride(journal))+ await assert.rejects(cleanupFixtureIdentities(input, journal, adapters), /retain journal/)+ assert.ok(state.calls.every(call => !/^(DELETE|UPDATE)/.test(call.sql)))+ assert.equal(journal.status, 'recovery-required')+ }+})++test('journal tampering is rejected before DB access; exact absent IDs support recovery', async () => {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ state.calls = []+ const foreign = structuredClone(journal)+ foreign.users[0].email = '[email protected]'+ await assert.rejects(cleanupFixtureIdentities(input, foreign, adapters), /ownership/)+ assert.equal(state.calls.length, 0)+ state.respond = () => ({ rows: [], rowCount: 0 })+ assert.equal(+ (await cleanupFixtureIdentities(input, journal, adapters)).outcome,+ 'recorded-identities-absent'+ )+ assert.ok(state.calls.every(call => !/^(DELETE|UPDATE)/.test(call.sql)))+})++test('cleanup deletion failure rolls back and leaves recovery journal', async () => {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ state.respond = cleanupRows(journal)+ state.committed = []+ state.failQuery = sql => sql.startsWith('DELETE FROM teams')+ await assert.rejects(cleanupFixtureIdentities(input, journal, adapters), /retain journal/)+ assert.equal(state.committed.length, 0)+ assert.equal(journal.status, 'recovery-required')+})++function connectionEvidence(journal) {+ return {+ scenario: '83',+ fixtureUserId: journal.users[0].id,+ id: '11111111-2222-4333-8444-555555555555',+ connectionKey: 'codex-0123456789abcdef',+ displayName: `Codex fixture 83 ${run}`,+ createdBy: null,+ }+}++function connectionRow(evidence) {+ return {+ id: evidence.id,+ connection_key: evidence.connectionKey,+ display_name: evidence.displayName,+ created_by: evidence.createdBy,+ status: 'connected',+ revoked_at: null,+ }+}++test('public UI connection evidence binds exact response ID and experiment without inventing creator identity', async () => {+ const { adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ const evidence = connectionEvidence(journal)+ recordFixtureConnection(input, journal, { env }, evidence)+ assert.deepEqual(journal.connections, [evidence])+ assert.throws(() => recordFixtureConnection(input, journal, { env }, evidence), /Duplicate/)+ for (const patch of [+ { id: 'invalid' },+ { displayName: 'unrelated subscription' },+ { connectionKey: 'deployment-default' },+ { createdBy: journal.users[0].id },+ { fixtureUserId: journal.users[1].id },+ { extra: 'unexpected' },+ ]) {+ const fresh = structuredClone(journal)+ fresh.connections = []+ assert.throws(+ () => recordFixtureConnection(input, fresh, { env }, { ...evidence, ...patch }),+ /evidence/+ )+ assert.deepEqual(fresh.connections, [])+ }+})++test('cleanup uses real revocation and union adapters under the same transaction and preserves tombstones', async () => {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ const evidence = connectionEvidence(journal)+ recordFixtureConnection(input, journal, { env }, evidence)+ state.respond = cleanupRows(journal, {+ codex_subscription_connections: [connectionRow(evidence)],+ })+ const actions = []+ adapters.revokeCodexSubscriptionConnection = async (db, key) => {+ assert.equal(db, state.db)+ assert.equal(key, evidence.connectionKey)+ actions.push('revoke')+ return { id: evidence.id, connectionKey: key, status: 'revoked', revokedAt: new Date() }+ }+ adapters.rebuildLiveCodexUnionAllowlist = async db => {+ assert.equal(db, state.db)+ actions.push('rebuild')+ }+ await cleanupFixtureIdentities(input, journal, adapters)+ assert.deepEqual(actions, ['revoke', 'rebuild'])+ assert.ok(!state.calls.some(call => /DELETE FROM codex_/.test(call.sql)))+ assert.deepEqual(journal.connections, [evidence])+})++test('unrecorded, replaced or foreign same-name connections block cleanup before any revocation', async () => {+ for (const kind of [+ 'unrecorded',+ 'replaced',+ 'renamed',+ 'creator-changed',+ 'missing',+ 'same-key-replacement',+ ]) {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ const evidence = connectionEvidence(journal)+ if (kind !== 'unrecorded') recordFixtureConnection(input, journal, { env }, evidence)+ const row = connectionRow(evidence)+ if (kind === 'replaced') row.id = '11111111-2222-4333-8444-666666666666'+ if (kind === 'renamed') row.display_name = 'foreign'+ if (kind === 'creator-changed') row.created_by = journal.users[1].id+ const rows = kind === 'missing' ? [] : [row]+ if (kind === 'same-key-replacement')+ rows.push({ ...row, id: '11111111-2222-4333-8444-666666666666' })+ state.respond = cleanupRows(journal, { codex_subscription_connections: rows })+ state.calls = []+ adapters.revokeCodexSubscriptionConnection = async () => assert.fail('Unowned revocation')+ adapters.rebuildLiveCodexUnionAllowlist = async () => assert.fail('Unexpected rebuild')+ await assert.rejects(cleanupFixtureIdentities(input, journal, adapters), /retain journal/)+ assert.ok(state.calls.every(call => !/^(DELETE|UPDATE)/.test(call.sql)))+ assert.equal(journal.status, 'recovery-required')+ }+})++test('already-revoked response IDs support retry but adapter failures retain recovery journal', async () => {+ for (const mode of ['retained', 'revoke-fails', 'wrong-result', 'union-fails']) {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ const evidence = connectionEvidence(journal)+ recordFixtureConnection(input, journal, { env }, evidence)+ const row = connectionRow(evidence)+ if (mode === 'retained') Object.assign(row, { status: 'revoked', revoked_at: new Date() })+ state.respond = cleanupRows(journal, { codex_subscription_connections: [row] })+ state.committed = []+ adapters.revokeCodexSubscriptionConnection = async () => {+ if (mode === 'retained') assert.fail('Repeated revocation')+ if (mode === 'revoke-fails') throw new Error('synthetic failure')+ return {+ id: mode === 'wrong-result' ? 'foreign' : evidence.id,+ connectionKey: evidence.connectionKey,+ status: 'revoked',+ revokedAt: new Date(),+ }+ }+ adapters.rebuildLiveCodexUnionAllowlist = async () => {+ if (mode === 'union-fails') throw new Error('synthetic failure')+ }+ if (mode === 'retained') {+ await cleanupFixtureIdentities(input, journal, adapters)+ assert.equal(journal.status, 'cleaned')+ } else {+ await assert.rejects(cleanupFixtureIdentities(input, journal, adapters), /retain journal/)+ assert.equal(state.committed.length, 0)+ assert.equal(journal.status, 'recovery-required')+ }+ }+})++test('publication is mandatory and cleanup cannot commit without an installed adapter', async () => {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ delete adapters.publishRuntimeAllowlist+ state.calls = []+ await assert.rejects(cleanupFixtureIdentities(input, journal, adapters), /runtime publication/)+ assert.equal(state.calls.length, 0)+})++test('controller-removed workflow grant permits cleanup without claiming a second revocation', async () => {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ state.calls = []+ state.events = []+ state.respond = cleanupRows(journal, { user_workflow_triggers: [] })+ await cleanupFixtureIdentities(input, journal, adapters)+ assert.equal(journal.status, 'cleaned')+ assert.equal(state.publications, 1)+ assert.ok(state.calls.every(call => !call.sql.includes('INSERT INTO trigger_grants_audit')))+ assert.equal(state.events.length, 1)+ assert.equal(state.events[0].changes.length, 12)+ assert.ok(+ state.events[0].changes.every(change => change.resourceClass !== 'workflow_trigger_access')+ )+})++test('optional workflow grant cannot belong to the negative user or another recipe', async () => {+ for (const changed of ['user', 'recipe']) {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ state.calls = []+ state.respond = cleanupRows(journal, {+ user_workflow_triggers: [+ {+ user_id: changed === 'user' ? journal.users[1].id : journal.users[0].id,+ recipe_namespace: journal.grants.workflow.namespace,+ recipe_name: changed === 'recipe' ? 'foreign-recipe' : journal.grants.workflow.name,+ },+ ],+ })+ await assert.rejects(cleanupFixtureIdentities(input, journal, adapters), /retain journal/)+ assert.ok(state.calls.every(call => !/^(DELETE|UPDATE)/.test(call.sql)))+ assert.equal(state.publications, 0)+ }+})++test('postcommit publication failure keeps recovery journal and absent-ID retry republishes before cleaned', async () => {+ const { state, adapters } = harness()+ const journal = await createFixtureIdentities(input, adapters)+ state.respond = cleanupRows(journal)+ state.publicationFailure = true+ await assert.rejects(cleanupFixtureIdentities(input, journal, adapters), /retain journal/)+ assert.equal(state.commits, 2, 'identity cleanup already committed')+ assert.equal(state.rollbacks, 0, 'publication failure cannot roll back committed DB work')+ assert.equal(state.publications, 1)+ assert.equal(journal.status, 'recovery-required')+ assert.ok(state.journal.every(value => value.status !== 'cleaned'))+ state.respond = () => ({ rows: [], rowCount: 0 })+ state.publicationFailure = false+ const save = adapters.saveJournal+ adapters.saveJournal = async value => {+ if (value.status === 'cleaned') assert.equal(state.publications, 2)+ await save(value)+ }+ const result = await cleanupFixtureIdentities(input, journal, adapters)+ assert.equal(result.outcome, 'recorded-identities-absent')+ assert.equal(state.publications, 2)+ assert.equal(journal.status, 'cleaned')+})diff --git a/tests/e2e/fixtures/codex-subscription/approved-tools-setup/seed.mjs b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/seed.mjsnew file mode 100644index 000000000..5f42b94ea--- /dev/null+++ b/tests/e2e/fixtures/codex-subscription/approved-tools-setup/seed.mjs@@ -0,0 +1,64 @@+// Runs only in the isolated Control API test image. The host records identity+// intent before invoking this program; no production account is reused.+if (+ process.env.NODE_ENV !== 'test' ||+ process.env.EVENFIRE_APPROVED_TOOLS_OAUTH_FIXTURE !== '1' ||+ !process.env.KUBERNETES_SERVICE_HOST+)+ throw new Error('Isolated test image required')++const inputChunks = []+let inputBytes = 0+for await (const chunk of process.stdin) {+ inputBytes += chunk.length+ if (inputBytes > 65_536) throw new Error('Identity input exceeds limit')+ inputChunks.push(chunk)+}+const input = JSON.parse(Buffer.concat(inputChunks, inputBytes).toString('utf8'))+if (!['create', 'cleanup'].includes(input.action)) throw new Error('Invalid identity action')+const { pool, withTransaction } = await import('/app/control-api/dist/db.js')+try {+ const { default: bcrypt } = await import('/app/control-api/node_modules/bcryptjs/index.js')+ const { appendControlApiPermissionEventsInTransaction } =+ await import('/app/control-api/dist/services/tracing/controlApiPermissionEvents.js')+ const { revokeCodexSubscriptionConnection } =+ await import('/app/control-api/dist/services/codexSubscriptionConnection.js')+ const { rebuildLiveCodexUnionAllowlist } =+ await import('/app/control-api/dist/services/codexSubscriptionCatalog.js')+ const { createFixtureIdentities, cleanupFixtureIdentities } =+ await import('/app/approved-tools-setup/identity-lifecycle.mjs')+ const publish = journal => process.stdout.write(JSON.stringify({ e2eIdentity: journal }) + '\n')+ const adapters = {+ env: process.env,+ withTransaction,+ hashPassword: (value, rounds) => bcrypt.hash(value, rounds),+ appendPermissionEvents: appendControlApiPermissionEventsInTransaction,+ revokeCodexSubscriptionConnection,+ rebuildLiveCodexUnionAllowlist,+ publishRuntimeAllowlist: async () => {+ const { KubeConfig, CoreV1Api } =+ await import('/app/control-api/node_modules/@kubernetes/client-node/dist/index.js')+ const { config } = await import('/app/control-api/dist/config.js')+ const { LlmAllowedModelsConfigMapWriter } =+ await import('/app/control-api/dist/services/llmAllowedModelsConfigMap.js')+ const clusterConfig = new KubeConfig()+ clusterConfig.loadFromCluster()+ const writer = new LlmAllowedModelsConfigMapWriter(+ clusterConfig.makeApiClient(CoreV1Api),+ config.hostsNamespace+ )+ await writer.materialize()+ },+ saveJournal: publish,+ }+ if (input.action === 'create') {+ await createFixtureIdentities(input, { ...adapters, initialJournal: input.initialJournal })+ } else {+ await cleanupFixtureIdentities(input, input.initialJournal, adapters)+ }+} catch {+ process.stderr.write('Fixture identity operation failed; retain the host journal for recovery\n')+ process.exitCode = 1+} finally {+ await pool.end()+}diff --git a/tests/e2e/fixtures/package-lock.json b/tests/e2e/fixtures/package-lock.jsonindex a9b0869ae..3c9437eab 100644--- a/tests/e2e/fixtures/package-lock.json+++ b/tests/e2e/fixtures/package-lock.json@@ -1,12 +1,12 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.77",+ "version": "1.0.78","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "@clerum/e2e-test-fixtures",- "version": "1.0.77",+ "version": "1.0.78","dependencies": {"@kubernetes/client-node": "^1.0.0"},diff --git a/tests/e2e/fixtures/package.json b/tests/e2e/fixtures/package.jsonindex 890f18cee..9729e9f7e 100644--- a/tests/e2e/fixtures/package.json+++ b/tests/e2e/fixtures/package.json@@ -1,6 +1,6 @@{"name": "@clerum/e2e-test-fixtures",- "version": "1.0.77",+ "version": "1.0.78","description": "E2E test fixtures and utilities for Clerum testing","type": "module","main": "index.ts",diff --git a/tests/e2e/playwright/desktop/codex-subscription-approved-tools.spec.ts b/tests/e2e/playwright/desktop/codex-subscription-approved-tools.spec.tsindex 327e17d57..88c225532 100644--- a/tests/e2e/playwright/desktop/codex-subscription-approved-tools.spec.ts+++ b/tests/e2e/playwright/desktop/codex-subscription-approved-tools.spec.ts@@ -6,7 +6,8 @@* E2E_GUARDIAN_ENTRY_POINT: Control UI starts at its application root.* E2E_GUARDIAN_IPC_FLOW: Desktop uses real main-process login and chat IPC.* Completed messages and MCP evidence replace renderer response waits. Tests- * never inject IPC calls or authentication. Only the external model is faked.+ * never inject IPC calls or authentication. Only the external OAuth and model+ * providers are simulated in deterministic mode.*/import { type Page, expect, test } from '@playwright/test'import {diff --git a/tests/e2e/playwright/helpers/approved-tools-subscription.ts b/tests/e2e/playwright/helpers/approved-tools-subscription.tsindex 59a42e6ef..4996b047e 100644--- a/tests/e2e/playwright/helpers/approved-tools-subscription.ts+++ b/tests/e2e/playwright/helpers/approved-tools-subscription.ts@@ -5,6 +5,7 @@* Real-account mode uses the explicitly prepared existing grant unchanged.*/import { type Page, type Route, expect } from '@playwright/test'+import { beginConnectionCapture } from '../../../../scripts/e2e/approved-tools-connection-journal.mjs'import { ControlUiShell, SecretsLlmSubscriptionsPage } from '../pages/codex-subscription'import { type Scenario, required } from './approved-tools-scenarios'@@ -18,7 +19,23 @@ export async function prepareSubscriptionVisible(page: Page, scenario: Scenario)}await new ControlUiShell(page).openSecretsLlmSubscriptions()const subscriptions = new SecretsLlmSubscriptionsPage(page)- const connectionKey = await subscriptions.createGrant(scenario.subscriptionName)+ const scenarioLabel = scenario.runId.split('-').at(-1)!+ const run = scenario.runId.slice(0, -(scenarioLabel.length + 1))+ const capture = beginConnectionCapture(required('APPROVED_TOOLS_EVIDENCE_DIR'), {+ run,+ profile: required('MINIKUBE_PROFILE'),+ context: required('CONTROL_API_REAL_PG_CONTEXT'),+ scenario: scenarioLabel,+ fixtureUserId: required('APPROVED_TOOLS_FIXTURE_USER_ID'),+ })+ let connectionKey: string+ try {+ connectionKey = await subscriptions.createGrant(scenario.subscriptionName, metadata =>+ capture.record(metadata)+ )+ } finally {+ capture.close()+ }expect(connectionKey).not.toBe('unassigned')const context = page.context()const externalConsent = async (route: Route) => {diff --git a/tests/e2e/playwright/package-lock.json b/tests/e2e/playwright/package-lock.jsonindex dcb2ee065..b271048f2 100644--- a/tests/e2e/playwright/package-lock.json+++ b/tests/e2e/playwright/package-lock.json@@ -1,12 +1,12 @@{"name": "clerum-playwright-tests",- "version": "0.1.47",+ "version": "0.1.48","lockfileVersion": 3,"requires": true,"packages": {"": {"name": "clerum-playwright-tests",- "version": "0.1.47",+ "version": "0.1.48","devDependencies": {"@playwright/test": "^1.50.0","@types/node": "^22.0.0",diff --git a/tests/e2e/playwright/package.json b/tests/e2e/playwright/package.jsonindex ae6b2ce3b..026b81dc6 100644--- a/tests/e2e/playwright/package.json+++ b/tests/e2e/playwright/package.json@@ -1,6 +1,6 @@{"name": "clerum-playwright-tests",- "version": "0.1.47",+ "version": "0.1.48","private": true,"description": "Playwright E2E tests for Control UI and Desktop App","scripts": {diff --git a/tests/e2e/playwright/pages/codex-subscription.ts b/tests/e2e/playwright/pages/codex-subscription.tsindex 0ebbd9274..587ead804 100644--- a/tests/e2e/playwright/pages/codex-subscription.ts+++ b/tests/e2e/playwright/pages/codex-subscription.ts@@ -162,7 +162,15 @@ export class SecretsLlmSubscriptionsPage {* Create a named grant. After the 201 the sync dialog stays open* (Sign in visible). Callers that leave Secrets must closeConnectModal first.*/- async createGrant(displayName: string): Promise<string> {+ async createGrant(+ displayName: string,+ onCreated?: (metadata: {+ id?: unknown+ connectionKey?: unknown+ displayName?: unknown+ createdBy?: unknown+ }) => void | Promise<void>+ ): Promise<string> {await this.page.getByRole('button', { name: 'Add subscription' }).click()await this.page.getByLabel('Name', { exact: true }).fill(displayName)const created = this.page.waitForResponse(@@ -173,8 +181,20 @@ export class SecretsLlmSubscriptionsPage {)await this.page.getByRole('button', { name: 'Create', exact: true }).click()const response = await created+ const body = (await response.json()) as {+ id?: unknown+ connectionKey?: string+ displayName?: unknown+ createdBy?: unknown+ }+ if (response.status() === 201 && onCreated)+ await onCreated({+ id: body.id,+ connectionKey: body.connectionKey,+ displayName: body.displayName,+ createdBy: body.createdBy,+ })expect(response.status(), `create grant must return 201, got ${response.status()}`).toBe(201)- const body = (await response.json()) as { connectionKey?: string }expect(body.connectionKey).toBeTruthy()await this.expectConnectModal()return String(body.connectionKey)