Evenfire is an intelligence layer platform for running LLM agents that take real actions, on your infrastructure
TypeScript
test(llm): complete private login and fixture reuse guards
Alfredo Lopezf8ebd8a0ac03
diff --git a/.github/workflows/ci-public.yml b/.github/workflows/ci-public.ymlindex 0f913fb62..031155fe8 100644--- a/.github/workflows/ci-public.yml+++ b/.github/workflows/ci-public.yml@@ -172,6 +172,10 @@ jobs:working-directory: desktop-apprun: npx playwright install --with-deps chromium+ - name: Test subscription login privacy+ if: matrix.service == 'desktop-app'+ run: node --test scripts/tests/subscription-private-ui-input.test.mjs+- name: Test the pinned-suite checkerif: matrix.service == 'gfs-controller'run: node scripts/tests/run-node-test-files.mjs scripts/ci/assert-pinned-vitest-suites.test.mjsdiff --git a/codex-llm-proxy/test/visualBodyReadOwnership.test.ts b/codex-llm-proxy/test/visualBodyReadOwnership.test.tsindex d283efb0b..50ff0001b 100644--- a/codex-llm-proxy/test/visualBodyReadOwnership.test.ts+++ b/codex-llm-proxy/test/visualBodyReadOwnership.test.ts@@ -20,6 +20,7 @@ type ObservedRead = {error: unknownfinishes: numberendCalls: number+ suppressedCloseBackstops: number}const parserBarrier = vi.hoisted(() => {@@ -69,10 +70,24 @@ vi.mock('express', async () => {error: undefined,finishes: 0,endCalls: 0,+ suppressedCloseBackstops: 0,}: undefinedif (read) {parserBarrier.reads.push(read)+ if (req.headers['x-visual-hold-response-close'] === '1') {+ // Controlled fault injection for the direct-release witness:+ // production may not register its response-close backstop, so a+ // released slot can only have come from the route's eager path.+ const originalOnce = res.once.bind(res)+ res.once = ((event: string, listener: (...args: unknown[]) => void) => {+ if (event === 'close') {+ read.suppressedCloseBackstops += 1+ return res+ }+ return originalOnce(event, listener as never)+ }) as Response['once']+ }res.once('finish', () => {read.finishes += 1})@@ -272,6 +287,49 @@ async function postVisualStatus(port: number, body: string): Promise<number> {return status}+function openVisualKeepAlive(port: number): {+ send: (body: string) => Promise<number>+ destroy: () => void+} {+ let owner: ReturnType<typeof connectTcp> | undefined+ let wire = ''+ const statusWaiters: Array<(status: number) => void> = []+ owner = connectTcp(port, '127.0.0.1')+ sockets.add(owner)+ owner.once('close', () => sockets.delete(owner!))+ owner.setTimeout(5_000, () => {+ owner?.destroy()+ for (const resolve of statusWaiters.splice(0)) resolve(-1)+ })+ owner.on('data', data => {+ wire += data.toString('utf8')+ for (;;) {+ const match = /HTTP\/1\.1 (\d{3})/.exec(wire)+ if (!match) return+ wire = wire.slice(match.index + match[0].length)+ statusWaiters.shift()?.(Number(match[1]))+ }+ })+ return {+ send(body: string) {+ return new Promise<number>((resolve, reject) => {+ statusWaiters.push(resolve)+ owner?.once('error', reject)+ owner?.write(+ `POST ${COMPLETIONS_PATH} HTTP/1.1\r\n` ++ `Host: 127.0.0.1:${port}\r\n` ++ `Authorization: Bearer ${platformToken()}\r\n` ++ `Content-Type: application/json\r\n` ++ `X-Visual-Hold-Response-Close: 1\r\n` ++ `Content-Length: ${Buffer.byteLength(body)}\r\n` ++ `\r\n${body}`+ )+ })+ },+ destroy: () => owner?.destroy(),+ }+}+describe('codex visual body read ownership', () => {const servers: Array<ReturnType<typeof createProxyApps>> = []const listeners: Array<ReturnType<typeof createServer>> = []@@ -442,6 +500,40 @@ describe('codex visual body read ownership', () => {'a parsed visual body did not release its admission after the route response')})++ it('eagerly releases a refused visual body before its response-close backstop', async () => {+ const apps = createProxyApps(config())+ servers.push(apps)+ const listener = createServer(apps.runtimeApp).listen(0)+ listeners.push(listener)+ const address = listener.address()+ if (!address || typeof address === 'string') throw new Error('listener has no port')++ const client = openVisualKeepAlive(address.port)+ const firstResponse = client.send(invalidTicketBody())+ await waitFor(+ () => parserBarrier.reads.length === 1 && parserBarrier.reads[0]!.returned,+ 'the first refused visual route did not reach its direct-release path'+ )+ const firstRead = parserBarrier.reads[0]!+ expect(await firstResponse).toBe(403)+ expect(firstRead.nativeSettled).toBe(true)+ expect(firstRead.error).toBeUndefined()+ expect(firstRead.suppressedCloseBackstops).toBe(1)+ expect(visualStreamGate.snapshot()).toEqual({ running: 0, queued: 0 })++ const secondResponse = client.send(invalidTicketBody())+ expect(await secondResponse).toBe(403)+ await waitFor(+ () => parserBarrier.reads.length === 2 && parserBarrier.reads.every(read => read.returned),+ 'the next eligible visual request was not admitted after direct release'+ )+ expect(parserBarrier.reads[1]!.nativeSettled).toBe(true)+ expect(parserBarrier.reads[1]!.error).toBeUndefined()+ expect(visualStreamGate.snapshot()).toEqual({ running: 0, queued: 0 })+ client.destroy()+ })+it('stops the native reader independently when a non-reading peer never finishes the response', async () => {const apps = createProxyApps(config(), { bodyReadDeadlineMs: 40, visualReadCloseGraceMs: 15 })servers.push(apps)diff --git a/desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts b/desktop-app/test/e2e-playwright/subscriptionImageFixtures.tsindex b799eaf62..974e2caee 100644--- a/desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts+++ b/desktop-app/test/e2e-playwright/subscriptionImageFixtures.ts@@ -39,6 +39,7 @@ import {requireSubscriptionImageRun,verifyRunnerObservation,} from './subscriptionImageRunContract.js'+import { enterLoginPassword } from './subscriptionPrivateUiInput.mjs'export const subscriptionImageRun = requireSubscriptionImageRun()const repoRoot = path.resolve(__dirname, '../../..')@@ -341,7 +342,7 @@ export const test = base.extend<Fixtures>({await expect(loginEmail).toBeVisible({ timeout: 30_000 })await expect(page.locator('#password-input')).toBeVisible()await loginEmail.fill(process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_EMAIL!)- await page.locator('#password-input').fill(process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_PASSWORD!)+ await enterLoginPassword(page, process.env.E2E_SUBSCRIPTION_IMAGE_LOGIN_PASSWORD!)await page.getByRole('button', { name: 'Sign in', exact: true }).click()await expect(loginEmail).toHaveCount(0)await expect(page.getByTestId('nav-settings-menu')).toBeVisible({diff --git a/desktop-app/test/e2e-playwright/subscriptionPrivateUiInput.d.mts b/desktop-app/test/e2e-playwright/subscriptionPrivateUiInput.d.mtsnew file mode 100644index 000000000..89590b2d6--- /dev/null+++ b/desktop-app/test/e2e-playwright/subscriptionPrivateUiInput.d.mts@@ -0,0 +1,3 @@+import type { Page } from '@playwright/test'++export function enterLoginPassword(page: Page, value: string): Promise<void>diff --git a/desktop-app/test/e2e-playwright/subscriptionPrivateUiInput.mjs b/desktop-app/test/e2e-playwright/subscriptionPrivateUiInput.mjsnew file mode 100644index 000000000..ad2fd7d1d--- /dev/null+++ b/desktop-app/test/e2e-playwright/subscriptionPrivateUiInput.mjs@@ -0,0 +1,14 @@+// @ts-check+// E2E_GUARDIAN_IPC_FLOW: enter credentials through the visible login field.+/**+ * Playwright fill() includes its value in progress errors, even with trace off.+ * Native keyboard insertion keeps that value out of the progress call log.+ * @param {import('@playwright/test').Page} page+ * @param {string} value+ */+export async function enterLoginPassword(page, value) {+ await page.locator('#password-input').click()+ await page.keyboard.press('ControlOrMeta+A')+ await page.keyboard.press('Backspace')+ await page.keyboard.insertText(value)+}diff --git a/grok-llm-proxy/test/visualBodyReadOwnership.test.ts b/grok-llm-proxy/test/visualBodyReadOwnership.test.tsindex e32e5da43..b84867d55 100644--- a/grok-llm-proxy/test/visualBodyReadOwnership.test.ts+++ b/grok-llm-proxy/test/visualBodyReadOwnership.test.ts@@ -20,6 +20,7 @@ type ObservedRead = {error: unknownfinishes: numberendCalls: number+ suppressedCloseBackstops: number}const parserBarrier = vi.hoisted(() => {@@ -69,10 +70,24 @@ vi.mock('express', async () => {error: undefined,finishes: 0,endCalls: 0,+ suppressedCloseBackstops: 0,}: undefinedif (read) {parserBarrier.reads.push(read)+ if (req.headers['x-visual-hold-response-close'] === '1') {+ // Controlled fault injection for the direct-release witness:+ // production may not register its response-close backstop, so a+ // released slot can only have come from the route's eager path.+ const originalOnce = res.once.bind(res)+ res.once = ((event: string, listener: (...args: unknown[]) => void) => {+ if (event === 'close') {+ read.suppressedCloseBackstops += 1+ return res+ }+ return originalOnce(event, listener as never)+ }) as Response['once']+ }res.once('finish', () => {read.finishes += 1})@@ -272,6 +287,49 @@ async function postVisualStatus(port: number, body: string): Promise<number> {return status}+function openVisualKeepAlive(port: number): {+ send: (body: string) => Promise<number>+ destroy: () => void+} {+ let owner: ReturnType<typeof connectTcp> | undefined+ let wire = ''+ const statusWaiters: Array<(status: number) => void> = []+ owner = connectTcp(port, '127.0.0.1')+ sockets.add(owner)+ owner.once('close', () => sockets.delete(owner!))+ owner.setTimeout(5_000, () => {+ owner?.destroy()+ for (const resolve of statusWaiters.splice(0)) resolve(-1)+ })+ owner.on('data', data => {+ wire += data.toString('utf8')+ for (;;) {+ const match = /HTTP\/1\.1 (\d{3})/.exec(wire)+ if (!match) return+ wire = wire.slice(match.index + match[0].length)+ statusWaiters.shift()?.(Number(match[1]))+ }+ })+ return {+ send(body: string) {+ return new Promise<number>((resolve, reject) => {+ statusWaiters.push(resolve)+ owner?.once('error', reject)+ owner?.write(+ `POST ${COMPLETIONS_PATH} HTTP/1.1\r\n` ++ `Host: 127.0.0.1:${port}\r\n` ++ `Authorization: Bearer ${platformToken()}\r\n` ++ `Content-Type: application/json\r\n` ++ `X-Visual-Hold-Response-Close: 1\r\n` ++ `Content-Length: ${Buffer.byteLength(body)}\r\n` ++ `\r\n${body}`+ )+ })+ },+ destroy: () => owner?.destroy(),+ }+}+describe('grok visual body read ownership', () => {const servers: Array<ReturnType<typeof createProxyApps>> = []const listeners: Array<ReturnType<typeof createServer>> = []@@ -442,6 +500,40 @@ describe('grok visual body read ownership', () => {'a parsed visual body did not release its admission after the route response')})++ it('eagerly releases a refused visual body before its response-close backstop', async () => {+ const apps = createProxyApps(config())+ servers.push(apps)+ const listener = createServer(apps.runtimeApp).listen(0)+ listeners.push(listener)+ const address = listener.address()+ if (!address || typeof address === 'string') throw new Error('listener has no port')++ const client = openVisualKeepAlive(address.port)+ const firstResponse = client.send(invalidTicketBody())+ await waitFor(+ () => parserBarrier.reads.length === 1 && parserBarrier.reads[0]!.returned,+ 'the first refused visual route did not reach its direct-release path'+ )+ const firstRead = parserBarrier.reads[0]!+ expect(await firstResponse).toBe(403)+ expect(firstRead.nativeSettled).toBe(true)+ expect(firstRead.error).toBeUndefined()+ expect(firstRead.suppressedCloseBackstops).toBe(1)+ expect(visualStreamGate.snapshot()).toEqual({ running: 0, queued: 0 })++ const secondResponse = client.send(invalidTicketBody())+ expect(await secondResponse).toBe(403)+ await waitFor(+ () => parserBarrier.reads.length === 2 && parserBarrier.reads.every(read => read.returned),+ 'the next eligible visual request was not admitted after direct release'+ )+ expect(parserBarrier.reads[1]!.nativeSettled).toBe(true)+ expect(parserBarrier.reads[1]!.error).toBeUndefined()+ expect(visualStreamGate.snapshot()).toEqual({ running: 0, queued: 0 })+ client.destroy()+ })+it('stops the native reader independently when a non-reading peer never finishes the response', async () => {const apps = createProxyApps(config(), { bodyReadDeadlineMs: 40, visualReadCloseGraceMs: 15 })servers.push(apps)diff --git a/scripts/ci/pinned-vitest-cases/codex-llm-proxy.json b/scripts/ci/pinned-vitest-cases/codex-llm-proxy.jsonindex d890e99f2..8cde688bf 100644--- a/scripts/ci/pinned-vitest-cases/codex-llm-proxy.json+++ b/scripts/ci/pinned-vitest-cases/codex-llm-proxy.json@@ -102,5 +102,9 @@{"suite": "streamLimitsFreeze.test.ts","fullName": "codex-subscription stream limits freeze rejects open or mutable admission code producers while reading the closed production union"+ },+ {+ "suite": "visualBodyReadOwnership.test.ts",+ "fullName": "codex visual body read ownership eagerly releases a refused visual body before its response-close backstop"}]diff --git a/scripts/ci/pinned-vitest-cases/grok-llm-proxy.json b/scripts/ci/pinned-vitest-cases/grok-llm-proxy.jsonindex 06f231acb..b3d75735c 100644--- a/scripts/ci/pinned-vitest-cases/grok-llm-proxy.json+++ b/scripts/ci/pinned-vitest-cases/grok-llm-proxy.json@@ -102,5 +102,9 @@{"suite": "contractFreeze.test.ts","fullName": "grok-subscription contract freeze rejects open or mutable admission code producers while reading the closed production union"+ },+ {+ "suite": "visualBodyReadOwnership.test.ts",+ "fullName": "grok visual body read ownership eagerly releases a refused visual body before its response-close backstop"}]diff --git a/scripts/e2e/coordinate-subscription-image-journeys.mjs b/scripts/e2e/coordinate-subscription-image-journeys.mjsindex af988a087..f92121d59 100755--- a/scripts/e2e/coordinate-subscription-image-journeys.mjs+++ b/scripts/e2e/coordinate-subscription-image-journeys.mjs@@ -153,6 +153,46 @@ function releaseOptionsForQa(options, receiptFile) {return parseOptions(Object.entries(fields).flatMap(([key, value]) => value === true ? [`--${key}`] : [`--${key}`, String(value)]))}+export function validateMemoryOperatorSelection(options) {+ const username = options?.operatorUser+ assert(typeof username === 'string' && /^[A-Za-z0-9_.-]{3,64}$/.test(username),+ 'COORDINATOR_OPERATOR_USERNAME_INVALID')+ if (options.prepareFixtures && Object.hasOwn(options.publicArguments ?? {}, 'operator-user')) {+ assert(options.publicArguments['operator-user'] === username, 'COORDINATOR_OPERATOR_SOURCE_CHANGED')+ return 'existing'+ }+ if (options.prepareFixtures) {+ assert(username === `${options.runId}-operator`, 'COORDINATOR_ISOLATED_OPERATOR_REQUIRED')+ return 'generated'+ }+ assert(options.fixtureBinding, 'COORDINATOR_ISOLATED_OPERATOR_REQUIRED')+ return 'fixture'+}++function validatePrivateControlMaterial(material) {+ assert(material && typeof material.operatorPassword === 'string' &&+ material.operatorPassword.length >= 8 && material.operatorPassword.length <= 1024 &&+ (material.cookie === undefined || (typeof material.cookie === 'string' &&+ material.cookie.length <= 8192 && !/[\r\n\0]/.test(material.cookie))) &&+ (material.desktopPassword === undefined || (typeof material.desktopPassword === 'string' &&+ material.desktopPassword.length >= 8 && material.desktopPassword.length <= 1024)) &&+ Object.keys(material).every(key => ['operatorPassword', 'cookie', 'desktopPassword'].includes(key)),+ 'COORDINATOR_PRIVATE_OPERATOR_REQUIRED')+}++export function seedPrivateMaterial(material) {+ validatePrivateControlMaterial(material)+ return {+ operatorPassword: material.operatorPassword,+ ...(material.cookie === undefined ? {} : { cookie: material.cookie }),+ }+}++export function desktopPasswordFor(material) {+ validatePrivateControlMaterial(material)+ return material.desktopPassword ?? material.operatorPassword+}+/** Physical callers keep this one real CAS fence across all cgroup windows and* image suites. Its methods use the existing private driver/runner; no raw* credential enters options, receipts or the recovery record.@@ -170,7 +210,7 @@ export async function withControlApiFixtureRuntime(options, privateMaterial, worcheck(value); referenceOptions = valueif (value.prepareFixtures) memoryState = 'created-or-unknown'else if (value.fixtureBinding) { memoryState = 'created'; receiptFile = value.publicArguments['fixtures-receipt'] }- const report = await seed(value, privateMaterial)+ const report = await seed(value, seedPrivateMaterial(privateMaterial))if (value.prepareFixtures) { memoryState = 'created'; receiptFile = value.report }return report},@@ -183,12 +223,26 @@ export async function withControlApiFixtureRuntime(options, privateMaterial, worif (value.prepareFixtures) { memoryState = 'created'; receiptFile = value.report; referenceOptions = value }return report},+ async proxyMemory(runId, value, work) {+ check(value)+ assert(memoryState === 'created' && value.prepareFixtures !== true && value.fixtureBinding &&+ value.publicArguments?.['fixtures-receipt'] === receiptFile && typeof work === 'function' &&+ /^subscription-image-[a-f0-9]{12}$/.test(runId) && images.length === 4 &&+ images.every(status => status.state === 'revoked'), 'COORDINATOR_LIVE_PROXY_FIXTURE_REQUIRED')+ referenceOptions = value+ const grantStatus = { state: 'not-created', bindings: [] }; images.push(grantStatus)+ // Resume the same owned memory run/UIDs while the original cron fence is+ // active. The registered image status participates in outer restoration.+ return seed(value, seedPrivateMaterial(privateMaterial), async session =>+ withImageQaSession(session, runId, grantStatus, qa => work({ session, qa,+ qaState: () => ({ state: grantStatus.state, bindings: structuredClone(grantStatus.bindings) }) })))+ },}try { result = await work(runtime) } catch (error) { failure = error }finally {if (memoryState === 'created' && receiptFile) {try {- const released = await seed(releaseOptionsForQa(referenceOptions, receiptFile), privateMaterial, async session => session.revokeMemory())+ const released = await seed(releaseOptionsForQa(referenceOptions, receiptFile), seedPrivateMaterial(privateMaterial), async session => session.revokeMemory())assert(released.kind === 'control-api-authorize-qa-finalization.v1' && released.fixtureFinalization?.verified === true &&released.fixtureFinalization.state === 'revoked' && released.fixtureFinalization.grantsRevoked === 2 &&released.fixtureFinalization.hostsDetached === 2, 'COORDINATOR_MEMORY_QA_FINALIZATION_UNPROVED')@@ -511,13 +565,9 @@ async function pressureRelay({ containerName, pressure, metadata, processIdentitexport async function coordinate(prepareArguments, memoryOptions, privateMaterial, catalogRuntime) {assert(process.versions.node.startsWith('24.') && fs.realpathSync(process.cwd()) === ROOT, 'COORDINATOR_NODE24_WORKTREE_REQUIRED')- assert((memoryOptions.prepareFixtures === true || memoryOptions.fixtureBinding) && privateMaterial && typeof privateMaterial.operatorPassword === 'string' &&- privateMaterial.operatorPassword.length >= 8 && privateMaterial.operatorPassword.length <= 1024 &&- (privateMaterial.cookie === undefined || (typeof privateMaterial.cookie === 'string' &&- privateMaterial.cookie.length <= 8192 && !/[\r\n\0]/.test(privateMaterial.cookie))) &&- Object.keys(privateMaterial).every(key => ['operatorPassword', 'cookie'].includes(key)),- 'COORDINATOR_PRIVATE_OPERATOR_REQUIRED')- assert(memoryOptions.operatorUser === `${memoryOptions.runId}-operator`, 'COORDINATOR_ISOLATED_OPERATOR_REQUIRED')+ assert(memoryOptions.prepareFixtures === true || memoryOptions.fixtureBinding, 'COORDINATOR_ISOLATED_OPERATOR_REQUIRED')+ validatePrivateControlMaterial(privateMaterial)+ validateMemoryOperatorSelection(memoryOptions)assert(memoryOptions.prepare === 'restart', 'COORDINATOR_RECONCILED_BASELINE_REQUIRED')const values = Object.fromEntries(Array.from({ length: prepareArguments.length / 2 }, (_, index) =>[prepareArguments[index * 2].slice(2), prepareArguments[index * 2 + 1]]))@@ -550,7 +600,7 @@ export async function coordinate(prepareArguments, memoryOptions, privateMateria{ timeout: 150_000 })}if (memoryOptions.prepareFixtures) memoryState = 'created-or-unknown'- await seed(memoryOptions, privateMaterial, async session => {+ await seed(memoryOptions, seedPrivateMaterial(privateMaterial), async session => {memoryState = 'created'await withImageQaSession(session, values['run-id'], grantStatus, async qa => {assert(qa.credentialState === 'opaque-qa-not-real-G8' && qa.vendorCronsDisabled === true &&@@ -604,7 +654,7 @@ export async function coordinate(prepareArguments, memoryOptions, privateMateria},frames(admission) {const loginFrame = Object.fromEntries([['kind', 'evenfire-subscription-image-login-v1'],- ['runId', admission.runId], ['email', qa.loginEmail], ['password', privateMaterial.operatorPassword]])+ ['runId', admission.runId], ['email', qa.loginEmail], ['password', desktopPasswordFor(privateMaterial)]])return Readable.from(vendorFrames({ admission, states, remainingFrame, loginFrame, signal: abort.signal,observe: state => {relay?.assertHealthy()@@ -680,7 +730,7 @@ async function main() {material = JSON.parse(bytes.toString('utf8')); bytes.fill(0); bytes = Buffer.alloc(0); break}assert(material?.kind === 'evenfire-subscription-image-private-control-v1', 'COORDINATOR_PRIVATE_INPUT_REQUIRED')- const privateMaterial = Object.fromEntries(['operatorPassword', 'cookie'].filter(field => material[field] !== undefined)+ const privateMaterial = Object.fromEntries(['operatorPassword', 'cookie', 'desktopPassword'].filter(field => material[field] !== undefined).map(field => [field, material[field]]))material = undefinedconst result = await coordinate(argv, memoryOptions, privateMaterial)diff --git a/scripts/tests/control-api-qa-runtime.test.mjs b/scripts/tests/control-api-qa-runtime.test.mjsindex 25a6104a2..2bcfb0472 100644--- a/scripts/tests/control-api-qa-runtime.test.mjs+++ b/scripts/tests/control-api-qa-runtime.test.mjs@@ -7,7 +7,8 @@ import vm from 'node:vm'import { stripTypeScriptTypes } from 'node:module'import { isDeepStrictEqual } from 'node:util'import { CATALOG_CRON_KEYS, snapshotDeployment, deploymentMutationPatch, openControlApiCatalogIsolation,- withControlApiFixtureRuntime, catalogRestorationSafe } from '../e2e/coordinate-subscription-image-journeys.mjs'+ withControlApiFixtureRuntime, catalogRestorationSafe, seedPrivateMaterial,+ withImageQaSession } from '../e2e/coordinate-subscription-image-journeys.mjs'import { revokeMemoryFixtures } from './lib/control-api-authorize-memory-seeder.ts'const id = number => `00000000-0000-4000-8000-${String(number).padStart(12, '0')}`@@ -21,44 +22,69 @@ function patchObject(object, operations) {else target[key] = structuredClone(operation.value)}}-function fixture({ seedFailure = false } = {}) {+function fixture({ seedFailure = false, imageRevokeFailure = false } = {}) {const resource = { metadata: { uid: id(1), resourceVersion: '1' }, spec: { replicas: 1,template: { spec: { containers: [{ name: 'control-api', image, env: [...CATALOG_CRON_KEYS.map(name => ({ name, value: 'true' })),{ name: 'UNRELATED', value: 'keep' }] }] } } } }const events = [], recovery = []+ const liveBindings = [0, 1].map(index => ({ hostRef: `unit-memory-${index}`, hostUid: id(10 + index),+ connectionId: id(20 + index), connectionKey: `unit-memory-grant-${index}` }))+ let prepared = false, memoryRevoked = falseconst effective = () => Object.fromEntries(resource.spec.template.spec.containers[0].env.map(entry => [entry.name, entry.value]))const context = { assert: (value, code) => assert(value, code), validImageId: value => value === image,imageId: value => value, ROOT: '/unit-source', NAMESPACE: 'control-plane', CATALOG_CRON_KEYS, snapshotDeployment, deploymentMutationPatch,getDeployment: () => structuredClone(resource), readyPod: () => ({ metadata: { name: 'unit-api' }, status: { containerStatuses: [{ name: 'control-api', imageID: image }] } }),until: async check => check(), json: () => ({ llm: effective()[CATALOG_CRON_KEYS[0]] === 'true', subscription: effective()[CATALOG_CRON_KEYS[1]] === 'true' }),patchDeployment: (_context, _name, patch) => { patchObject(resource, patch); events.push('cron-patch'); resource.metadata.resourceVersion = String(Number(resource.metadata.resourceVersion) + 1) },- command: () => '', catalogRestorationSafe,+ command: () => '', catalogRestorationSafe, seedPrivateMaterial,restoreDeployments: async (_context, states) => {for (const state of states) patchObject(resource, deploymentMutationPatch(resource, state.original, state.applied, true))events.push('restore-original-crons')},- seed: async (_options, _private, finalization) => {+ seed: async (value, _private, work) => {assert(CATALOG_CRON_KEYS.every(name => effective()[name] === 'false')); events.push('seed-sees-false')if (seedFailure) throw new Error('UNIT_SEED_FAILED')- if (finalization) { await finalization({ revokeMemory: async () => { events.push('memory-revoked-verified'); return { verified: true } } });- return { kind: 'control-api-authorize-qa-finalization.v1', fixtureFinalization: { verified: true, state: 'revoked', grantsRevoked: 2, hostsDetached: 2 } } }- return { fixtures: {} }+ if (value.prepareFixtures) { assert.equal(prepared, false, 'fixed Hosts cannot be reseeded'); prepared = true }+ if (work) {+ const session = { fixtures: { bindings: structuredClone(liveBindings) },+ prepareImages: async () => { assert.equal(memoryRevoked, false); events.push('proxy-images-created');+ return { bindings: [{ provider: 'grok-subscription', hostRef: 'unit-image-grok' },+ { provider: 'codex-subscription', hostRef: 'unit-image-codex' }] } },+ revokeImages: async () => { events.push('proxy-images-revoke');+ if (imageRevokeFailure) return { verified: false }+ return { verified: true, grantsRevoked: 2, hostsDetached: 2 } },+ revokeMemory: async () => { assert.equal(memoryRevoked, false); memoryRevoked = true;+ events.push('memory-revoked-verified'); return { verified: true } } }+ await work(session)+ }+ return memoryRevoked+ ? { kind: 'control-api-authorize-qa-finalization.v1', fixtureFinalization: { verified: true, state: 'revoked', grantsRevoked: 2, hostsDetached: 2 } }+ : { fixtures: { bindings: structuredClone(liveBindings) }, producer: { code: 0, signal: null } }},- releaseOptionsForQa: options => options,+ coordinate: async (_args, value, _private, scope) => {+ assert.equal(value.prepareFixtures, false); assert.equal(memoryRevoked, false)+ assert(CATALOG_CRON_KEYS.every(name => effective()[name] === 'false'))+ scope.grantStatus.state = 'revoked'; events.push('journey-images-revoked')+ return { producerExit: 0, restoration: { verified: true } }+ },+ releaseOptionsForQa: options => ({ ...options, prepareFixtures: false }),writeCatalogRecovery: (...args) => { recovery.push(args); events.push('retain-crons-false') },- Error, Promise, Object, path: { dirname: () => '/unit-report', join: (...parts) => parts.join('/') },+ Error, Promise, Object, structuredClone, path: { dirname: () => '/unit-report', join: (...parts) => parts.join('/') },}const sandbox = vm.createContext(context)context.openControlApiCatalogIsolation = vm.runInContext(`(${openControlApiCatalogIsolation.toString()})`, sandbox)+ context.withImageQaSession = vm.runInContext(`(${withImageQaSession.toString()})`, sandbox)const wrapper = vm.runInContext(`(${withControlApiFixtureRuntime.toString()})`, sandbox)const options = { profile: 'qa-unit', context: 'qa-unit', runId: 'pr806-memory-123456789abc', prepare: 'restart', prepareFixtures: true,report: '/unit-report/seed.json', publicArguments: {} }- return { wrapper, options, events, recovery, resource, effective }+ // Public, test-only input; it is not an actual operator credential.+ const material = { operatorPassword: 'unit-only-control-material' }+ return { wrapper, options, material, events, recovery, resource, effective, liveBindings }}test('actual wrapper applies real cron keys false before seed and restores true only after final memory revocation', async () => {const world = fixture()- await world.wrapper(world.options, {}, async runtime => {+ await world.wrapper(world.options, world.material, async runtime => {assert.deepEqual(runtime.initialSnapshot.env, Object.fromEntries(CATALOG_CRON_KEYS.map(name => [name, 'true'])))await runtime.run(world.options)})@@ -68,11 +94,11 @@ test('actual wrapper applies real cron keys false before seed and restores true})test('partial seed failure keeps actual crons false and records recovery; a zero-QA work failure restores originals', async () => {const partial = fixture({ seedFailure: true })- await assert.rejects(partial.wrapper(partial.options, {}, runtime => runtime.run(partial.options)), /UNIT_SEED_FAILED/)+ await assert.rejects(partial.wrapper(partial.options, partial.material, runtime => runtime.run(partial.options)), /UNIT_SEED_FAILED/)assert(CATALOG_CRON_KEYS.every(name => partial.effective()[name] === 'false'))assert(!partial.events.includes('restore-original-crons')); assert.equal(partial.recovery.length, 1)const zero = fixture()- await assert.rejects(zero.wrapper(zero.options, {}, async () => { throw new Error('UNIT_BEFORE_QA') }), /UNIT_BEFORE_QA/)+ await assert.rejects(zero.wrapper(zero.options, zero.material, async () => { throw new Error('UNIT_BEFORE_QA') }), /UNIT_BEFORE_QA/)assert(CATALOG_CRON_KEYS.every(name => zero.effective()[name] === 'true'))for (const state of ['created', 'created-or-unknown']) {assert.equal(catalogRestorationSafe(state, []), false)@@ -80,6 +106,46 @@ test('partial seed failure keeps actual crons false and records recovery; a zero}})+test('registered proxy work resumes the same live memory UID run after four image revokes and revokes memory once outside', async () => {+ const world = fixture()+ await world.wrapper(world.options, world.material, async runtime => {+ await runtime.run(world.options)+ const resumed = { ...world.options, prepareFixtures: false, fixtureBinding: { uid: world.liveBindings[0].hostUid },+ report: '/unit-report/proxy-session.json', publicArguments: { 'fixtures-receipt': world.options.report } }+ await assert.rejects(runtime.proxyMemory('subscription-image-123456789abc', resumed, async () => {}), /LIVE_PROXY_FIXTURE/)+ for (let n = 0; n < 4; n++) await runtime.journey([], resumed)+ const reseed = { ...resumed, prepareFixtures: true }+ await assert.rejects(runtime.proxyMemory('subscription-image-123456789abc', reseed, async () => {}), /LIVE_PROXY_FIXTURE/)+ await assert.rejects(runtime.proxyMemory('subscription-image-123456789abc', { ...resumed, runId: 'pr806-memory-aaaaaaaaaaaa' }, async () => {}), /SCOPE_CHANGED/)+ await runtime.proxyMemory('subscription-image-123456789abc', resumed, async ({ session, qaState }) => {+ assert.deepEqual(session.fixtures.bindings, world.liveBindings)+ assert.equal(qaState().state, 'created')+ const view = qaState(); view.state = 'revoked'; view.bindings.length = 0+ assert.equal(qaState().state, 'created'); assert.equal(qaState().bindings.length, 2)+ assert(!world.events.includes('memory-revoked-verified'))+ world.events.push('proxy-work-with-live-memory')+ })+ assert(!world.events.includes('memory-revoked-verified'))+ })+ assert.equal(world.events.filter(event => event === 'memory-revoked-verified').length, 1)+ assert(world.events.indexOf('proxy-work-with-live-memory') < world.events.indexOf('proxy-images-revoke'))+ assert(world.events.indexOf('proxy-images-revoke') < world.events.indexOf('memory-revoked-verified'))+ assert(world.events.indexOf('memory-revoked-verified') < world.events.indexOf('restore-original-crons'))+})+test('registered proxy revoke unknown retains actual cronfalse despite independent final memory revoke', async () => {+ const world = fixture({ imageRevokeFailure: true })+ await assert.rejects(world.wrapper(world.options, world.material, async runtime => {+ await runtime.run(world.options)+ const resumed = { ...world.options, prepareFixtures: false, fixtureBinding: { uid: world.liveBindings[0].hostUid },+ publicArguments: { 'fixtures-receipt': world.options.report } }+ for (let n = 0; n < 4; n++) await runtime.journey([], resumed)+ await runtime.proxyMemory('subscription-image-123456789abc', resumed, async () => world.events.push('proxy-work'))+ }), /QA_GRANT_RESTORATION_FAILED/)+ assert.equal(world.events.filter(event => event === 'memory-revoked-verified').length, 1)+ assert(!world.events.includes('restore-original-crons')); assert.equal(world.recovery.length, 1)+ assert(CATALOG_CRON_KEYS.every(name => world.effective()[name] === 'false'))+})+test('real first-tick scheduler would call direct sync after restart; disabled actual config gate prevents scheduling', async () => {const full = fs.readFileSync(new URL('../../control-api/src/services/subscriptionCatalogSyncCron.ts', import.meta.url), 'utf8')const start = full.indexOf('let intervalHandle:'), source = stripTypeScriptTypes(full.slice(start)).replace(/^export /gm, '')diff --git a/scripts/tests/lib/subscription-image-source-context.mjs b/scripts/tests/lib/subscription-image-source-context.mjsindex 7f63a9616..ff8e5b2d2 100644--- a/scripts/tests/lib/subscription-image-source-context.mjs+++ b/scripts/tests/lib/subscription-image-source-context.mjs@@ -21,6 +21,8 @@ const fixedFiles = ['subscription-image-input.spec.ts','playwright.subscription-image.config.ts','subscriptionImageFixtures.ts',+ 'subscriptionPrivateUiInput.mjs',+ 'subscriptionPrivateUiInput.d.mts','subscriptionImageRunContract.ts','subscriptionImageChallenge.ts','codexImageChallenge.ts',diff --git a/scripts/tests/subscription-image-coordinator-regressions.test.mjs b/scripts/tests/subscription-image-coordinator-regressions.test.mjsindex 64d32134f..96796759b 100644--- a/scripts/tests/subscription-image-coordinator-regressions.test.mjs+++ b/scripts/tests/subscription-image-coordinator-regressions.test.mjs@@ -8,7 +8,8 @@ import path from 'node:path'import net from 'node:net'import { once } from 'node:events'import { prepareVendorEvidenceDirectory } from '../e2e/fixtures/subscription-image-provider.mjs'-import { closePressureResources, withImageQaSession, qaRestorationTargets } from '../e2e/coordinate-subscription-image-journeys.mjs'+import { closePressureResources, withImageQaSession, qaRestorationTargets,+ validateMemoryOperatorSelection, seedPrivateMaterial, desktopPasswordFor } from '../e2e/coordinate-subscription-image-journeys.mjs'import { openAdmissionPressure, pressureCommandDeadlineMs, verifyPressureMetadata } from '../e2e/fixtures/subscription-image-admission-pressure.mjs'import { openAuthorizeAdmissionPressure } from './measure-control-api-authorize-memory.mjs'import { prepareSubscriptionImageBindings, revokeSubscriptionImageBindings, resumeMemoryFixtures } from './lib/control-api-authorize-memory-seeder.ts'@@ -179,6 +180,33 @@ function qaWorld({ residualFallback = false } = {}) {return { options, operator, memory, session, prod, hosts, grants }}+test('explicit existing operator is admitted while the generated default remains mandatory without opt-in', () => {+ const runId = 'pr806-memory-123456789abc'+ const explicit = { runId, prepareFixtures: true, operatorUser: 'manual.admin',+ publicArguments: { 'operator-user': 'manual.admin' } }+ assert.equal(validateMemoryOperatorSelection(explicit), 'existing')+ const generated = { runId, prepareFixtures: true, operatorUser: `${runId}-operator`, publicArguments: {} }+ assert.equal(validateMemoryOperatorSelection(generated), 'generated')+ assert.throws(() => validateMemoryOperatorSelection({ ...generated, operatorUser: 'manual.admin' }),+ /ISOLATED_OPERATOR_REQUIRED/)+ assert.throws(() => validateMemoryOperatorSelection({ ...explicit, publicArguments: { 'operator-user': 'other.admin' } }),+ /OPERATOR_SOURCE_CHANGED/)+ assert.equal(validateMemoryOperatorSelection({ runId, fixtureBinding: {}, operatorUser: 'manual.admin' }), 'fixture')+})++test('RAM-only Desktop secret is withheld from the admin seed and defaults to the operator secret', () => {+ const separated = { operatorPassword: 'unit-admin-password', desktopPassword: 'unit-desktop-password' }+ assert.deepEqual(Object.keys(seedPrivateMaterial(separated)), ['operatorPassword'])+ assert.equal(desktopPasswordFor(separated), 'unit-desktop-password')+ const shared = { operatorPassword: 'unit-shared-password' }+ assert.deepEqual(seedPrivateMaterial(shared), shared)+ assert.equal(desktopPasswordFor(shared), 'unit-shared-password')+ assert.deepEqual(Object.keys(seedPrivateMaterial({ ...separated, cookie: 'unit-cookie' })).sort(),+ ['cookie', 'operatorPassword'])+ assert.throws(() => seedPrivateMaterial({ ...separated, repeatedDesktopPassword: 'unit-desktop-password' }),+ /PRIVATE_OPERATOR_REQUIRED/)+})+test('detach refuses an API success retaining a QA fallback before it can claim verified revocation', async () => {const world = qaWorld({ residualFallback: true }), state = []await prepareSubscriptionImageBindings({ ...world, prepared: world.memory, runId: 'subscription-image-111111111111', state })@@ -201,6 +229,12 @@ test('prepareA -> revokeA -> resume retained memory -> prepareB uses fresh imageawait assert.rejects(resumeMemoryFixtures({ ...world, expected: { ...world.memory, bindings: qaA.bindings } }), /BINDING_FOREIGN/)})+test('native resume rejects a changed operator username and Desktop UUID even after explicit admission', async () => {+ const world = qaWorld()+ await assert.rejects(resumeMemoryFixtures({ ...world, expected: { ...world.memory,+ operatorUsername: 'wrong.admin', operatorDesktopUserId: uid(999) } }), /OPERATOR_CHANGED/)+})+test('revocation barrier retains vendor fixtures on residual fallback while allowing independent CAPI restoration', async () => {const world = qaWorld({ residualFallback: true }), state = [], timeline = []const status = { state: 'not-created', bindings: [] }diff --git a/scripts/tests/subscription-private-ui-input.test.mjs b/scripts/tests/subscription-private-ui-input.test.mjsnew file mode 100644index 000000000..4ccad986c--- /dev/null+++ b/scripts/tests/subscription-private-ui-input.test.mjs@@ -0,0 +1,89 @@+// E2E_GUARDIAN_IPC_FLOW: standalone native browser/CDP privacy controls;+// the synthetic form has no application HTTP, account, auth or storage flow.+import test from 'node:test'+import assert from 'node:assert/strict'+import { createHash, randomBytes } from 'node:crypto'+import { createRequire } from 'node:module'+import { spawnSync } from 'node:child_process'+import fs from 'node:fs'+import path from 'node:path'+import { fileURLToPath } from 'node:url'+import { enterLoginPassword } from '../../desktop-app/test/e2e-playwright/subscriptionPrivateUiInput.mjs'++const filename = fileURLToPath(import.meta.url)+const workspace = process.env.PR806_PRIVACY_CONTROL_WORKSPACE ?? path.resolve(path.dirname(filename), '../..')+const hash = value => createHash('sha256').update(value).digest('hex')+const mode = process.env.PR806_PRIVACY_CONTROL_MODE++if (mode) {+ test(`synthetic private input ${mode}`, { timeout: 20000 }, async () => {+ const require = createRequire(path.join(workspace, 'desktop-app/package.json'))+ const { chromium } = require('playwright')+ const browser = await chromium.launch({ executablePath: chromium.executablePath(), headless: true, timeout: 15000 })+ process.stdout.write('PRIVACY_BROWSER_METADATA:' + JSON.stringify({+ playwright: require('playwright/package.json').version,+ executablePath: fs.realpathSync(chromium.executablePath()), browserVersion: browser.version(),+ }) + '\n')+ try {+ const page = await browser.newPage()+ page.setDefaultTimeout(300)+ // Synthetic negative privacy guard entry, not an application terminal route.+ const readOnly = mode === 'old-fill-failure' ? 'readonly' : ''+ await page.goto('data:text/html,' + encodeURIComponent(`<form><label>Password<input id="password-input" type="password" ${readOnly} value="initial-control"></label><button type="button" onclick="document.getElementById('status').textContent='submitted'">Submit</button><output id="status"></output></form>`))+ const sentinel = process.env.PR806_PRIVACY_CONTROL_SENTINEL+ assert.ok(typeof sentinel === 'string' && sentinel.length > 16, 'synthetic control data required')+ if (mode === 'old-fill-failure') {+ // Expected failure: the real Playwright reporter must expose this test-only sentinel.+ await page.locator('#password-input').fill(sentinel)+ } else {+ if (mode === 'safe-insert-failure') {+ // Close the real page after the real Backspace, before native insertion.+ // This fault is confined to the negative synthetic control.+ const press = page.keyboard.press.bind(page.keyboard)+ page.keyboard.press = async key => {+ await press(key)+ if (key === 'Backspace') await page.close()+ }+ }+ await enterLoginPassword(page, sentinel)+ assert.equal(hash(await page.locator('#password-input').inputValue()), hash(sentinel))+ await page.getByRole('button', { name: 'Submit', exact: true }).click()+ assert.equal(await page.locator('#status').textContent(), 'submitted')+ }+ } finally { await browser.close() }+ })+} else {+ test('actual Chromium private input and failure reporter preserve credential privacy', { timeout: 80000 }, () => {+ assert.match(process.version, /^v24\./)+ const sentinel = 'synthetic-ui-privacy-' + randomBytes(16).toString('hex')+ const observations = []+ for (const current of ['old-fill-failure', 'safe-entry-success', 'safe-insert-failure']) {+ const env = Object.fromEntries(['PATH','HOME','TMPDIR','USER','LOGNAME'].filter(key => process.env[key] !== undefined).map(key => [key,process.env[key]]))+ Object.assign(env, { PR806_PRIVACY_CONTROL_WORKSPACE: workspace, PR806_PRIVACY_CONTROL_MODE: current,+ PR806_PRIVACY_CONTROL_SENTINEL: sentinel, NO_COLOR: '1', FORCE_COLOR: '0' })+ const child = spawnSync(process.execPath, ['--test', '--test-reporter=tap', filename], {+ env, encoding: 'utf8', timeout: 25000, maxBuffer: 256 * 1024,+ })+ const output = (child.stdout ?? '') + (child.stderr ?? '')+ assert.equal(child.signal, null, 'synthetic browser control must finish without a signal')+ assert.equal(child.status, current === 'safe-entry-success' ? 0 : 1, 'expected control outcome')+ const containsSentinel = output.includes(sentinel)+ assert.equal(containsSentinel, current === 'old-fill-failure', 'reporter plaintext boundary')+ if (current !== 'safe-entry-success') assert.match(output, /not ok 1 - synthetic private input/)+ if (current === 'safe-insert-failure') assert.match(output, /keyboard\.insertText/)+ const metadata = /PRIVACY_BROWSER_METADATA:(\{[^\n]+\})/.exec(output)+ assert.ok(metadata, 'actual browser metadata required')+ const browser = JSON.parse(metadata[1])+ assert.equal(browser.playwright, '1.58.2')+ observations.push({ mode: current, producerExit: child.status, signal: child.signal,+ reporterContainsSyntheticSentinel: containsSentinel, reporterSha256: hash(output), browser })+ }+ if (process.env.PR806_PRIVACY_CONTROL_RECEIPT) {+ fs.writeFileSync(process.env.PR806_PRIVACY_CONTROL_RECEIPT, JSON.stringify({+ kind: 'pr806-private-ui-input-browser-controls.v1', node: process.version,+ control: 'actual-existing-Chromium-with-real-Playwright-reporter', tracing: 'off',+ actualAuthentication: 'NOT_RUN', observations,+ }, null, 2), { mode: 0o600, flag: 'wx' })+ }+ })+}diff --git a/scripts/tests/test-codex-subscription-t0.sh b/scripts/tests/test-codex-subscription-t0.shindex 3c4f173ae..4ee044135 100755--- a/scripts/tests/test-codex-subscription-t0.sh+++ b/scripts/tests/test-codex-subscription-t0.sh@@ -243,6 +243,7 @@ run_node_group "approved-tools-fixtures-and-runner" \"scripts/tests/subscription-image-coordinator.test.mjs" \"scripts/tests/subscription-image-coordinator-regressions.test.mjs" \"scripts/tests/control-api-qa-runtime.test.mjs" \+ "scripts/tests/subscription-private-ui-input.test.mjs" \"scripts/tests/subscription-image-input-frames.test.mjs" \"scripts/e2e/prepare-subscription-remaining-fixtures.test.mjs" \"scripts/e2e/fixtures/subscription-image-provider.test.mjs" \diff --git a/scripts/tests/test-grok-subscription-t0.sh b/scripts/tests/test-grok-subscription-t0.shindex f35cbec54..e2fecc5f8 100755--- a/scripts/tests/test-grok-subscription-t0.sh+++ b/scripts/tests/test-grok-subscription-t0.sh@@ -241,6 +241,7 @@ run_node_group "subscription-discovery-and-offline-image-provider" \"scripts/tests/subscription-image-coordinator.test.mjs" \"scripts/tests/subscription-image-coordinator-regressions.test.mjs" \"scripts/tests/control-api-qa-runtime.test.mjs" \+ "scripts/tests/subscription-private-ui-input.test.mjs" \"scripts/tests/subscription-image-input-frames.test.mjs" \"scripts/e2e/prepare-subscription-remaining-fixtures.test.mjs" \"scripts/e2e/fixtures/subscription-image-provider.test.mjs"