From f711830f24a070d3887235d56aa8380f81a234d0 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 4 Nov 2026 14:43:01 +0000 Subject: [PATCH 1/6] Initial plan From 20db162668b6ea0f5ce6e2845e1a24ed0ce958c0 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:00:08 +0000 Subject: [PATCH 2/6] feat: gate NVX commands on selected-harness observations --- docs/INTEGRATION-TESTS.md | 41 +++ docs/adr/0004-model-information-management.md | 35 ++- scripts/ci/nvx-manager-live-evidence.ts | 143 ++++++++- src/commands/main-action.ts | 2 +- .../validators/api-proxy-validator.ts | 2 +- src/external-runtime-backend.ts | 2 + src/harness-observation.test.ts | 27 +- src/harness-observation.ts | 2 +- src/nvx/harness-observation.ts | 162 ++++++++++ src/nvx/runtime-backend.test.ts | 276 ++++++++++++++++++ src/nvx/runtime-backend.ts | 52 +++- 11 files changed, 708 insertions(+), 36 deletions(-) create mode 100644 src/nvx/harness-observation.ts diff --git a/docs/INTEGRATION-TESTS.md b/docs/INTEGRATION-TESTS.md index 3905ec7d6..3e82dfe20 100644 --- a/docs/INTEGRATION-TESTS.md +++ b/docs/INTEGRATION-TESTS.md @@ -71,6 +71,47 @@ digests. Scan targets, vulnerability database updates, and the blocking High/Critical PR-image gate are unchanged. The setup script validates the merged daemon configuration before restart and refuses local or self-hosted runners. +### Provider-free NVX harness observations + +The deterministic NVX cases in `src/nvx/runtime-backend.test.ts` run the generated +one-shot entrypoint in local shells with fixture executables. They verify the +adapter's single-launch ordering, command context, bounded/sanitized evidence, +test-only host requirements, cancellation, exit collection and observation-share +cleanup. They do **not** establish NVX guest compatibility. + +On a supported Linux x86_64/KVM runner provisioned with the existing signed NVX +release artifacts, distro layer, host tools and infrastructure bridge, the +existing live runner offers a separate provider-free mode: + +```bash +sudo npx tsx scripts/ci/nvx-manager-live-evidence.ts \ + --artifacts /absolute/path/to/attested-nvx-artifacts \ + --layer /absolute/path/to/distro-layer \ + --bridge awfnvxbr0 \ + --signerWorkflow github/gh-aw-firewall/.github/workflows/release.yml \ + --evidence /tmp/nvx-harness-live-evidence \ + --harnessOnly true +``` + +Use the signer workflow from the attested artifact release, not an arbitrary +replacement. This mode does not run the default provider-inference campaign. +It uses the production NVX manager, guest entrypoint and observation producer +with the existing version fixture, checks matching guest contexts, and exercises +compatible, incompatible and unverified test-owned requirements before command +release. Blocked commands are cancelled; final outcomes, confinement and resource +residue checks still use the existing manager evidence path. It writes +`harness-observation-live.json` with the tested Git revision, Linux environment, +artifact manifest, sanitized reports and individual outcomes. Missing artifacts +or KVM produce `blocked`, never successful acceptance. No test requirement is +added to the bundled catalogue or authorizes feed activation. + +**Current acceptance status:** blocked, not live-accepted. The implementation +session on 2026-11-04 had Linux `7.0.0-1017-azure` x86_64 and readable `/dev/kvm`, +but no signed NVX OpenVMM/kernel/initramfs/manifest bundle or distro layer, and +neither Bubblewrap nor `mkfs.erofs`. Deterministic results are separate from this +missing guest evidence. No Docker/ARC-DinD live acceptance, provider inference, +enclave observation or opaque/session attribution is claimed. + ### Provider-free Docker harness observations `.github/workflows/test-docker-harness-observation.yml` automatically runs two diff --git a/docs/adr/0004-model-information-management.md b/docs/adr/0004-model-information-management.md index 3574c4880..2b888d183 100644 --- a/docs/adr/0004-model-information-management.md +++ b/docs/adr/0004-model-information-management.md @@ -1447,7 +1447,7 @@ support list: sbx is not supported, and runc/gVisor/Kata are not separate supported product targets. The host produces selected-harness observations through the existing ready -Cloud Hypervisor execution channel and a Docker command-shell pre-command gate, +Cloud Hypervisor execution channel and Docker/NVX command-shell pre-command gates, after backend startup and before primary command execution. Selection is deliberately limited to direct `copilot`, `claude`, and `codex` executables (including simple absolute or `./` paths), mapped to the @@ -1462,7 +1462,7 @@ never establishes selection. | Cloud Hypervisor primary guest | Existing `manager.execute` channel, same guest UID/GID, environment, cwd and login shell as the primary command | | Docker primary agent | Generated command prelude runs the probe after the existing entrypoint's identity, chroot, environment, PATH and cwd setup; user command waits for host publication/recheck and release | | ARC/DinD (Docker deployment topology) | Same Docker producer, with container-local private tmpfs control transport via Docker exec; public report publication retains existing runner-visible log-mount translation | -| NVX | Explicit `runtime_probe_unsupported`; its one-shot execute lifecycle exposes no persistent ready guest for a separate observation | +| NVX primary guest | The observation starts the single existing `manager.execute` lifecycle; the generated entrypoint probes in the command's non-login `/bin/sh`, UID/GID, env, PATH and cwd, then waits for host publication/recheck and release over existing virtio-fs mounts | | Enclave executors | No primary observation is attached to the dedicated enclave proxy; per-invocation enclave observation remains unimplemented | Supported probes resolve the selected executable with `command -v` and run only @@ -1511,6 +1511,23 @@ back to the existing log/exit-status collection, without issuing any release. Historical non-default OCI backend names do not gain additional producer coverage in this slice. +NVX does not assume a persistent ready guest or launch a version-only VM. +Its probe rendezvous is a private per-run read-write share; its separate release +share is read-only in the guest, because NVX maps workload ownership to share +ownership. Only the host can publish the release. The generated POSIX prelude +uses the supported distro's Bash job control to supervise whole process groups +(BusyBox timeout alone signals only one PID), bounds the entire pipeline to +10 seconds plus a one-second kill grace, retains at most 4097 stdout +bytes, and discards stderr. Readiness and release each have a 120-second bound. +The host bounds the raw read and checks its unique environment binding before +publishing through the same canonical parser and atomic report path. +An applicable failed host recheck never releases the guest. Failed version +evidence alone still permits unconstrained legacy admission, not verified support. +Startup failure races readiness so an exited guest cannot deadlock observation; +the existing one-shot result remains responsible for exit status, timeout, +cancellation and manager cleanup. Private observation shares are removed after +that execution settles, including failed startup and cancellation. + `src/harness-observation.ts` initializes explicit unavailable/pending evidence before Compose generation, then atomically publishes the observation to `harness-observation.json` in the existing primary API-proxy log mount. @@ -1531,7 +1548,7 @@ requirement reason. The host also supplies the report when rechecking concrete `COPILOT_MODEL` CLI selections (flags, env files or opted-in host env) after backend readiness. Pre-start offline validation preserves naming/retirement checks but defers an otherwise-known direct Copilot model's unverified harness decision to -that ready-runtime check on Cloud Hypervisor and Docker (including ARC/DinD). +that pre-command check on Cloud Hypervisor, NVX and Docker (including ARC/DinD). Alias candidate expansion and its final harness eligibility remain proxy-owned; custom provider paths retain their existing validation exemption. No applicable constraint means legacy admission, not a claim of @@ -1562,8 +1579,16 @@ deployments. Live Docker and ARC/DinD acceptance must be recorded separately when infrastructure is available; no live provider inference or workflow dispatch is needed. -**Remaining handoff:** the actual observation producer for NVX is still missing; -product support does not imply observation capability. Per-invocation enclave observations, +NVX deterministic shell-transport fixtures exercise its real backend adapter, +generated entrypoint, probe bounds, context equality, host requirements, startup +failure, cancellation, final exit and share cleanup. They are not live guest +acceptance. The existing NVX live-evidence runner has a separate provider-free +`--harnessOnly true` mode; prerequisites and recorded acceptance are described in +[the integration guide](../INTEGRATION-TESTS.md). + +**Remaining handoff:** live supported NVX guest acceptance must be recorded +separately; product support and deterministic fixtures do not establish it. +Per-invocation enclave observations, opaque commands and per-session attribution, and complete pre-start enforcement on lifecycles without observation capability remain open. This slice keeps the bundled constraint projection empty. An opaque diff --git a/scripts/ci/nvx-manager-live-evidence.ts b/scripts/ci/nvx-manager-live-evidence.ts index 1b46d7dd4..4b08bbdb7 100644 --- a/scripts/ci/nvx-manager-live-evidence.ts +++ b/scripts/ci/nvx-manager-live-evidence.ts @@ -12,6 +12,13 @@ import { type NvxLiveMount, } from '../../src/nvx'; import { guardStaleChildPipe } from './nvx-manager-live-evidence-stream'; +import { NvxHarnessObservation } from '../../src/nvx/harness-observation'; +import { buildNvxGuestRunScript } from '../../src/nvx/guest-entrypoint'; +import { harnessContext, observeHarness, prepareHarnessObservation } from '../../src/harness-observation'; +import { eligibilityEvidence } from '../../src/model-information-contract/harness-observation'; +import { createEligibilityStore } from '../../src/model-information-contract/eligibility'; +import { identity } from '../../src/model-information-contract/identity'; +import type { WrapperConfig } from '../../src/types'; interface Inputs { artifacts: string; @@ -20,6 +27,7 @@ interface Inputs { signerWorkflow: string; evidence: string; childRunId?: string; + harnessOnly?: boolean; } const MAX_CAPTURED_OUTPUT_BYTES = 64 * 1024; @@ -30,6 +38,10 @@ async function main(): Promise { } const inputs = parseInputs(process.argv.slice(2)); await fs.mkdir(inputs.evidence, { recursive: true, mode: 0o700 }); + if (inputs.harnessOnly) { + await runHarnessObservationCases(inputs); + return; + } if (inputs.childRunId) { await runCase(inputs, { name: 'stale-owner-child', @@ -156,7 +168,133 @@ interface RunCaseOptions { scratchBytes?: number; mounts?: readonly NvxLiveMount[]; runScript?: string; - hostInteraction?: () => Promise; + hostInteraction?: () => Promise; +} + +/** Provider-free acceptance, deliberately separate from deterministic shell fixtures. */ +async function runHarnessObservationCases(inputs: Inputs): Promise { + const revision = (await execa('git', ['rev-parse', 'HEAD'])).stdout; + const environment = (await execa('uname', ['-smr'])).stdout; + const dirty = Boolean((await execa('git', ['status', '--porcelain'])).stdout); + const evidenceFile = path.join(inputs.evidence, 'harness-observation-live.json'); + const evidence: Record = { + schemaVersion: 1, revision, dirty, environment, status: 'blocked', cases: [], + }; + const checks: unknown[] = []; + evidence.cases = checks; + const writeEvidence = () => fs.writeFile(evidenceFile, `${JSON.stringify(evidence, null, 2)}\n`); + const prerequisites = [ + '/dev/kvm', inputs.layer, + ...['openvmm', 'vmlinux', 'initramfs.cpio.gz', 'manifest.json', 'manifest.sigstore.jsonl'] + .map(name => path.join(inputs.artifacts, name)), + ]; + const missing: string[] = []; + for (const filename of prerequisites) { + try { await fs.access(filename, constants.R_OK); } catch { missing.push(filename); } + } + if (missing.length) { + evidence.missing = missing; + await writeEvidence(); + throw new Error('NVX harness live acceptance blocked: missing KVM/runtime artifacts (see evidence)'); + } + evidence.manifest = JSON.parse(await fs.readFile(path.join(inputs.artifacts, 'manifest.json'), 'utf8')); + evidence.status = 'failed'; + await writeEvidence(); + try { + for (const [binary, mode, version, expected] of [ + ['copilot', 'valid', '1.2.3', 'compatible'], + ['claude', 'valid', '2.1.3 (Claude Code)', 'compatible'], + ['codex', 'valid', 'codex-cli 0.89.0', 'incompatible'], + ['copilot', 'valid', '1.0.0', 'incompatible'], + ...['malformed', 'failed', 'overflow', 'timeout', 'missing'].map(mode => + ['copilot', mode, '1.2.3', 'unverified']), + ]) { + const workspace = await fs.mkdtemp('/tmp/awf-nvx-harness-live-'); + await fs.chmod(workspace, 0o755); + await fs.chown(workspace, 65534, 65534); + const config = { + containerRuntime: 'nvx', agentCommand: `./${binary} --fixture`, + workDir: workspace, enableApiProxy: true, + } as WrapperConfig; + const controller = new NvxHarnessObservation(harnessContext(config)); + try { + await fs.mkdir(path.join(workspace, 'api-proxy-logs')); + if (mode !== 'missing') { + await fs.copyFile(path.resolve('tests/fixtures/harness-observation/executable.sh'), + path.join(workspace, binary)); + await fs.chmod(path.join(workspace, binary), 0o755); + } + const mounts = await controller.stage(65534, 65534); + const runScript = buildNvxGuestRunScript({ + environment: { + PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/tmp/awf-home', + USER: 'nobody', LOGNAME: 'nobody', FIXTURE_DIRECTORY: '/workspace', + FIXTURE_ENV: 'controlled', FIXTURE_MODE: mode, FIXTURE_VERSION: version, + }, + workingDirectory: '/workspace', command: controller.wrap(config.agentCommand), + }); + prepareHarnessObservation(config); + let report; + const outcome = await runCase(inputs, { + name: `selected-harness-${binary}-${mode}-${version.split(' ')[0]}`, + entrypoint: '/etc/awf/nvx-run.sh', timeoutMs: 120_000, runScript, + mounts: [{ + tag: 'workspace', guestTarget: '/workspace', hostPath: workspace, mode: 'rw', + deniedPaths: [], allowedPaths: [], writablePaths: [], + }, ...mounts], + hostInteraction: async () => { + report = await observeHarness(config, controller.probe); + const scope = { provider: 'copilot', channel: 'fixture' }; + const model = identity('copilot', 'fixture-model'); + const snapshot = createEligibilityStore({ models: [{ + identity: model, harnesses: [{ + scope, name: harnessContext(config).name!, minimum: '1.2.0', + scheme: 'semver', reason: 'Test-only NVX requirement', + provenance: { authority: 'maintained' }, + }], + }] }).pin(); + const decision = snapshot.evaluate({ + identity: model, scope, ...eligibilityEvidence(report, scope), + discovery: { status: 'available', authoritative: true }, + }); + if (decision.harness !== expected) throw new Error('Unexpected NVX harness eligibility'); + try { + await fs.access(path.join(workspace, 'command-context')); + throw new Error('NVX command started before host eligibility'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + if (!decision.admitted) return 'stop'; + await controller.release(); + }, + }); + if (expected === 'compatible') { + if (outcome.result.exitCode !== 23) throw new Error('NVX fixture exit code was not propagated'); + const probe = await fs.readFile(path.join(workspace, 'probe-context'), 'utf8'); + const command = await fs.readFile(path.join(workspace, 'command-context'), 'utf8'); + if (probe !== command) throw new Error('NVX probe and command contexts differ'); + } else { + if (outcome.result.exitCode !== 130 || outcome.result.category !== 'cancelled') { + throw new Error('NVX blocked guest did not complete cancellation'); + } + try { + await fs.access(path.join(workspace, 'command-context')); + throw new Error('NVX blocked command executed'); + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } + } + checks.push({ binary, mode, expected, report, outcome, status: 'passed' }); + await writeEvidence(); + } finally { + await controller.cleanup(); + await fs.rm(workspace, { recursive: true, force: true }); + } + } + evidence.status = 'passed'; + } finally { + await writeEvidence(); + } } async function runCase( @@ -242,7 +380,7 @@ async function runCase( try { const execution = manager.execute(); try { - await options.hostInteraction?.(); + if (await options.hostInteraction?.() === 'stop') abortController?.abort(); } catch (error) { abortController?.abort(); await execution.catch(() => undefined); @@ -613,6 +751,7 @@ function parseInputs(args: readonly string[]): Inputs { signerWorkflow, evidence: required('evidence'), ...(values.get('childRunId') ? { childRunId: values.get('childRunId') } : {}), + ...(values.get('harnessOnly') === 'true' ? { harnessOnly: true } : {}), }; } diff --git a/src/commands/main-action.ts b/src/commands/main-action.ts index a8ccdf518..0009e64cb 100644 --- a/src/commands/main-action.ts +++ b/src/commands/main-action.ts @@ -868,7 +868,7 @@ export function createMainAction(getOptionValueSource: OptionSourceResolver) { setupHostIptables, writeConfigs, probeHarness: externalRuntimeBackend?.probeHarness?.bind(externalRuntimeBackend) ?? dockerHarness?.probeHarness, - releaseHarness: dockerHarness?.releaseHarness, + releaseHarness: externalRuntimeBackend?.releaseHarness?.bind(externalRuntimeBackend) ?? dockerHarness?.releaseHarness, startContainers: externalWorkflowDependencies?.startContainers ?? startContainers, runAgentCommand: trackedRunAgentCommand, collectDiagnosticLogs: workflowCollectDiagnosticLogs, diff --git a/src/commands/validators/api-proxy-validator.ts b/src/commands/validators/api-proxy-validator.ts index 316a91312..8ba255537 100644 --- a/src/commands/validators/api-proxy-validator.ts +++ b/src/commands/validators/api-proxy-validator.ts @@ -190,7 +190,7 @@ export function validateCopilotModelOption( const deferredToReadyRuntime = (result: ReturnType): boolean => !result.valid && result.eligibility?.harness === 'unverified' && result.eligibility.status === 'unknown' && selectedHarness === 'copilot-cli' && - (config.containerRuntime === 'cloud-hypervisor' || supportsDockerHarnessObservation(config)); + (config.containerRuntime === 'cloud-hypervisor' || config.containerRuntime === 'nvx' || supportsDockerHarnessObservation(config)); if ( copilotModel && !hasCustomCopilotProvider(config) && diff --git a/src/external-runtime-backend.ts b/src/external-runtime-backend.ts index 12fb82958..3576b2b24 100644 --- a/src/external-runtime-backend.ts +++ b/src/external-runtime-backend.ts @@ -19,6 +19,8 @@ export interface ExternalAgentRuntimeBackend { preserve?(): Promise; /** Bounded output from the ready agent environment, not the host installation. */ probeHarness?: HarnessProbe; + /** Release a one-shot guest only after observation publication and eligibility. */ + releaseHarness?: () => Promise; } type ExternalRuntimeWorkflowDependencies = Pick< diff --git a/src/harness-observation.test.ts b/src/harness-observation.test.ts index 286c51abb..86b28b757 100644 --- a/src/harness-observation.test.ts +++ b/src/harness-observation.test.ts @@ -164,7 +164,8 @@ describe('actual-environment harness observations', () => { expect(probe).not.toHaveBeenCalled(); }); - it('wires ready-backend output through the atomic file to immutable scoped proxy eligibility pins', async () => { + it.each(['cloud-hypervisor', 'nvx'] as const)('wires %s output through the atomic file to immutable scoped proxy eligibility pins', async runtime => { + config.containerRuntime = runtime; prepareHarnessObservation(config); connectProxy(); const evidence = store(); @@ -251,7 +252,7 @@ describe('actual-environment harness observations', () => { config.runnerTopology = topology; prepareHarnessObservation(config); expect(report()).toMatchObject({ - status: 'unavailable', reason: runtime === 'nvx' ? 'runtime_probe_unsupported' : 'probe_pending', + status: 'unavailable', reason: 'probe_pending', }); expect(harnessContext(config).environment).toMatch(runtime === 'nvx' ? /^nvx:/ : /^docker:/); expect(await observeHarness(config)).toMatchObject({ status: 'unavailable', reason: 'runtime_probe_unsupported' }); @@ -287,6 +288,7 @@ describe('actual-environment harness observations', () => { }); it.each([ ['Cloud Hypervisor', 'cloud-hypervisor', 'standard'], + ['NVX', 'nvx', 'standard'], ['Docker', undefined, 'standard'], ['ARC/DinD', undefined, 'arc-dind'], ] as const)('defers pending host harness checks until %s is ready, then enforces the real report', async (_target, runtime, topology) => { @@ -311,27 +313,6 @@ describe('actual-environment harness observations', () => { await expect(observeHarness(config, jest.fn().mockResolvedValue({ exitCode: 127, stdout: '' }))).rejects .toThrow('observation=binary_missing'); }); - it.each([ - ['NVX', 'nvx', 'standard'], - ] as const)('does not defer an applicable host requirement without an observation producer on %s', (_target, runtime, topology) => { - config.containerRuntime = runtime; - config.runnerTopology = topology; - config.copilotGithubToken = 'fixture-token'; - config.additionalEnv = { COPILOT_MODEL: 'gpt-6-sol' }; - const actualValidation = copilotModels.validateCopilotModel; - jest.spyOn(copilotModels, 'validateCopilotModel').mockImplementation((model, evidence) => - actualValidation(model, { - ...evidence, - harnesses: [{ ...requirement, scope: { provider: 'copilot', channel: 'copilot-cli' } }], - })); - const exit = jest.spyOn(process, 'exit').mockImplementation(() => { - throw new Error('preflight rejected'); - }); - expect(() => validateCopilotModelOption(config, { - additionalEnv: config.additionalEnv!, volumeMounts: undefined, allowedUrls: undefined, - })).toThrow('preflight rejected'); - expect(exit).toHaveBeenCalledWith(1); - }); it('does not impose the first alias candidate floor on a later eligible runtime sibling', async () => { config.copilotGithubToken = 'fixture-token'; config.additionalEnv = { COPILOT_MODEL: 'coding' }; diff --git a/src/harness-observation.ts b/src/harness-observation.ts index a6d04185f..c72bca243 100644 --- a/src/harness-observation.ts +++ b/src/harness-observation.ts @@ -56,7 +56,7 @@ function publish(config: WrapperConfig, report: HarnessObservationReport): void export function prepareHarnessObservation(config: WrapperConfig): void { const context = harnessContext(config); publish(config, unavailable(context, !context.name ? 'selection_unavailable' : - config.containerRuntime === 'cloud-hypervisor' || supportsDockerHarnessObservation(config) + config.containerRuntime === 'cloud-hypervisor' || config.containerRuntime === 'nvx' || supportsDockerHarnessObservation(config) ? 'probe_pending' : 'runtime_probe_unsupported')); } diff --git a/src/nvx/harness-observation.ts b/src/nvx/harness-observation.ts new file mode 100644 index 000000000..aa2341189 --- /dev/null +++ b/src/nvx/harness-observation.ts @@ -0,0 +1,162 @@ +import { constants, promises as fs } from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { shellSingleQuote as quote } from '../cloud-hypervisor/backend-utils'; +import { + MAX_PROBE_BYTES, probeCommand, selectHarness, + type HarnessContext, type HarnessProbe, +} from '../model-information-contract/harness-observation'; +import type { NvxLiveMount } from './live-mount-policy'; + +const GUEST_CONTROL = '/run/awf-harness'; +const GUEST_PROBE = `${GUEST_CONTROL}/probe`; +const GUEST_RELEASE = `${GUEST_CONTROL}/release`; +const READY_TIMEOUT_MS = 120_000; + +/** + * One-shot rendezvous over NVX's existing virtio-fs transport. Only the guest + * writes probe output; the host publishes sanitized evidence before releasing it. + */ +export class NvxHarnessObservation { + private root: string | undefined; + private directory: string | undefined; + private releaseDirectory: string | undefined; + private ready = false; + private closed = false; + + constructor(private readonly context: HarnessContext) {} + + async stage(uid: number, gid: number): Promise { + this.root = await fs.mkdtemp(path.join(os.tmpdir(), 'awf-nvx-harness-')); + // The confined VMM must traverse the parent to export the private directory. + await fs.chmod(this.root, 0o711); + this.directory = path.join(this.root, 'probe'); + this.releaseDirectory = path.join(this.root, 'release'); + for (const directory of [this.directory, this.releaseDirectory]) { + await fs.mkdir(directory, { mode: 0o700 }); + await fs.chown(directory, uid, gid); + } + // NVX maps guest workload ownership to each share's owner. A separate + // read-only share, not mode bits, keeps the release host-owned in the guest. + return [ + { tag: 'harness-probe', hostPath: this.directory, guestTarget: GUEST_PROBE, mode: 'rw', + deniedPaths: [], allowedPaths: [], writablePaths: [] }, + { tag: 'harness-release', hostPath: this.releaseDirectory, guestTarget: GUEST_RELEASE, mode: 'ro', + deniedPaths: [], allowedPaths: [], writablePaths: [] }, + ]; + } + + wrap(command: string): string { + return withNvxHarnessObservation(this.context, command); + } + + readonly probe: HarnessProbe = async () => { + const deadline = Date.now() + READY_TIMEOUT_MS; + while (!this.closed && Date.now() < deadline) { + if (this.directory) { + let file; + try { + file = await fs.open(path.join(this.directory, 'result'), + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + const stat = await file.stat(); + if (!stat.isFile() || stat.size > MAX_PROBE_BYTES + 257) { + throw new Error('Invalid NVX harness observation'); + } + const buffer = Buffer.alloc(MAX_PROBE_BYTES + 258); + const { bytesRead } = await file.read(buffer, 0, buffer.length, 0); + const [environment, status, ...output] = buffer.subarray(0, bytesRead).toString('utf8').split('\n'); + if (environment !== this.context.environment || !/^\d{1,3}$/.test(status)) { + throw new Error('Invalid NVX harness observation binding'); + } + const stdout = output.join('\n'); + const exitCode = Number(status); + this.ready = true; + return { + stdout, exitCode, timedOut: exitCode === 124 || exitCode === 137, + overflow: Buffer.byteLength(stdout) > MAX_PROBE_BYTES, + }; + } catch (error) { + if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; + } finally { + await file?.close(); + } + } + await new Promise(resolve => setTimeout(resolve, 20)); + } + throw new Error('NVX harness observation timed out; command not started'); + }; + + async release(): Promise { + if (!this.ready || !this.releaseDirectory) { + throw new Error('NVX harness observation is not ready; command not started'); + } + const temporary = path.join(this.releaseDirectory, 'allow.tmp'); + await fs.writeFile(temporary, `${this.context.environment}\n`, { flag: 'wx', mode: 0o444 }); + await fs.rename(temporary, path.join(this.releaseDirectory, 'allow')); + this.ready = false; + } + + async cleanup(): Promise { + this.closed = true; + if (this.root) await fs.rm(this.root, { recursive: true, force: true }); + this.directory = undefined; + this.releaseDirectory = undefined; + this.root = undefined; + } +} + +/** Runs in the same non-login /bin/sh, UID/GID, cwd and exported env as the command. */ +export function withNvxHarnessObservation(context: HarnessContext, command: string): string { + const selection = selectHarness(context.binary || ''); + if (!selection || selection.name !== context.name) throw new Error('Invalid NVX selected harness'); + const probe = `${probeCommand(selection)}`; + // BusyBox timeout signals only one PID. Bash job control gives both the probe + // pipeline and watchdog their own groups, so neither leaves descendants behind. + // -p suppresses startup evaluation without changing exported BASH_ENV. + const bounded = `set -m +( + set +m + ( /bin/sh -c ${quote(probe)}; printf '%s\\n' "$?" >${GUEST_PROBE}/status ) | /usr/bin/head -c ${MAX_PROBE_BYTES + 1} +) & +probe=$! +( + set +m + /bin/sleep 10 + : >${GUEST_PROBE}/timed-out + kill -TERM -- "-$probe" 2>/dev/null || : + /bin/sleep 1 + kill -KILL -- "-$probe" 2>/dev/null || : +) & +watchdog=$! +wait "$probe" 2>/dev/null || : +if [ -f ${GUEST_PROBE}/timed-out ]; then + wait "$watchdog" 2>/dev/null || : + exit 124 +fi +kill -TERM -- "-$watchdog" 2>/dev/null || : +wait "$watchdog" 2>/dev/null || :`; + return `( +umask 077 +if /bin/bash --noprofile --norc -p -c ${quote(bounded)} >${GUEST_PROBE}/stdout 2>/dev/null; then + if [ -f ${GUEST_PROBE}/status ]; then IFS= read -r status <${GUEST_PROBE}/status; else status=126; fi +else + status=$? +fi +cd ${quote(GUEST_PROBE)} || exit 125 +printf '%s\\n%s\\n' ${quote(context.environment)} "$status" >result.tmp || exit 125 +/bin/cat stdout >>result.tmp || exit 125 +/bin/mv result.tmp result || exit 125 +n=0 +while [ "$n" -lt ${READY_TIMEOUT_MS / 100} ]; do + if [ -f ${GUEST_RELEASE}/allow ]; then + IFS= read -r decision <${GUEST_RELEASE}/allow + [ "$decision" = ${quote(context.environment)} ] || exit 125 + exit 0 + fi + /bin/sleep 0.1 + n=$((n + 1)) +done +exit 125 +) || exit 125 +${command}`; +} diff --git a/src/nvx/runtime-backend.test.ts b/src/nvx/runtime-backend.test.ts index 77aa50b02..4aa982700 100644 --- a/src/nvx/runtime-backend.test.ts +++ b/src/nvx/runtime-backend.test.ts @@ -1,4 +1,12 @@ import type { WrapperConfig } from '../types'; +import fs from 'fs'; +import os from 'os'; +import path from 'path'; +import execa from 'execa'; +import { harnessContext, observeHarness, prepareHarnessObservation } from '../harness-observation'; +import { validateCopilotModel } from '../copilot-model'; +import * as copilotModels from '../copilot-model'; +import { buildNvxKernelCommandLine } from './one-shot-arguments'; import type { MicrovmInfrastructureSnapshot } from '../microvm/infrastructure'; import type { NvxOneShotExecutionResult } from './one-shot-adapter'; import { withInputPreflight } from '../input-preflight'; @@ -107,6 +115,274 @@ describe('NvxRuntimeBackend', () => { Object.defineProperty(process, 'arch', { value: 'x64' }); }); + describe('NVX one-shot selected-harness shell transport fixture (not live NVX)', () => { + let directory: string; + let config: WrapperConfig; + let backend: ReturnType; + let guestScript: string; + let child: execa.ExecaChildProcess | undefined; + let managerConfig: Parameters[0]; + let createManager: jest.Mock; + + beforeEach(() => { + directory = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-nvx-observation-test-')); + for (const name of ['bin', 'workspace', 'api-proxy-logs']) fs.mkdirSync(path.join(directory, name)); + config = { + ...nvxConfig(), workDir: directory, allowedDomains: [], logLevel: 'error', keepContainers: false, + agentCommand: 'copilot --fixture', + additionalEnv: { + FIXTURE_DIRECTORY: directory, FIXTURE_ENV: 'command-env', + }, + }; + writeHarness('copilot', 'printf "1.2.3\\n"'); + createManager = jest.fn(options => { + managerConfig = options; + return { + execute: async () => { + let script = guestScript.split('/tmp/awf-home').join(`${directory}/home`) + .split('/home/awf').join(`${directory}/seed`) + .split("cd '/workspace'").join(`cd '${directory}/workspace'`); + // Map distro-installed fixture binaries onto the generated guest PATH. + script = script.replace("export PATH='", `export PATH='${directory}/bin:`); + for (const mount of options.execution.mounts) { + if (mount.tag.startsWith('harness-')) { + script = script.split(mount.guestTarget).join(mount.hostPath); + } + } + child = execa('/bin/sh', ['-c', script], { + env: {}, extendEnv: false, reject: false, detached: true, + }); + const abort = () => { if (child?.pid) process.kill(-child.pid, 'SIGTERM'); }; + options.execution.abortSignal.addEventListener('abort', abort, { once: true }); + if (options.execution.abortSignal.aborted) abort(); + try { + const result = await child; + return { + exitCode: result.signal ? 130 : result.exitCode, + category: result.signal ? 'cancelled' : 'success', signal: result.signal, + timedOut: false, rawStdoutTail: Buffer.from(result.stdout), + rawStderrTail: Buffer.from(result.stderr), + }; + } finally { + options.execution.abortSignal.removeEventListener('abort', abort); + } + }, + }; + }); + const { dependencies } = harness({ + identity: () => ({ uid: process.getuid!(), gid: process.getgid!() }), + createManager: createManager as NvxRuntimeBackendDependencies['createManager'], + createGuestConfigLayer: options => { + guestScript = options.runScript; + return { stage: async () => '', cleanup: async () => undefined } as never; + }, + }); + backend = nvxRuntimeTestHelpers.createBackendWithDependencies(config, dependencies); + }); + + afterEach(async () => { + await backend.stop(); + jest.restoreAllMocks(); + fs.rmSync(directory, { recursive: true, force: true }); + child = undefined; + }); + + function writeHarness(binary: string, version: string): void { + fs.writeFileSync(path.join(directory, 'bin', binary), `#!/bin/sh + if [ "$1" = --version ]; then phase=probe; else phase=command; fi + { id -u; id -g; printf '%s\\n' "$PWD" "$PATH" "$FIXTURE_ENV"; } >"$FIXTURE_DIRECTORY/$phase-context" + if [ "$phase" = probe ]; then + ${version} + else + printf 'command-output\\n' + exit 23 + fi + `, { mode: 0o700 }); + } + function report() { + return JSON.parse(fs.readFileSync(`${directory}/api-proxy-logs/harness-observation.json`, 'utf8')); + } + async function observe() { + prepareHarnessObservation(config); + await backend.start(directory, []); + return observeHarness(config, backend.probeHarness); + } + function assertCleaned() { + for (const mount of managerConfig.execution.mounts!.filter(m => m.tag.startsWith('harness-'))) { + expect(fs.existsSync(path.dirname(mount.hostPath))).toBe(false); + } + } + + it.each([ + ['copilot', 'copilot-cli', '1.2.3'], + ['claude', 'claude-code', '2.1.3 (Claude Code)'], + ['codex', 'codex-cli', 'codex-cli 0.89.0'], + ])('observes only selected %s before release, matching identity/env/PATH/non-login shell/cwd', async (binary, name, version) => { + config.agentCommand = `${binary} --fixture`; + writeHarness(binary, `printf '%s\\n' '${version}'`); + const observed = await observe(); + expect(observed).toMatchObject({ ...harnessContext(config), name, status: 'observed' }); + expect(report()).toEqual(observed); + expect(fs.existsSync(`${directory}/command-context`)).toBe(false); + expect(createManager).toHaveBeenCalledTimes(1); + expect(managerConfig.execution.mounts).toEqual(expect.arrayContaining([ + expect.objectContaining({ tag: 'harness-probe', mode: 'rw' }), + expect.objectContaining({ tag: 'harness-release', mode: 'ro' }), + ])); + // Adding the rendezvous must still fit the attested guest's x86 boot ABI. + expect(() => buildNvxKernelCommandLine({ + ...managerConfig.execution, + filesystem: { layers: [{ role: 'distro', uuid: '0'.repeat(36) }] }, + } as never)).not.toThrow(); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); + expect(createManager).toHaveBeenCalledTimes(1); + expect((await child!).stdout).toBe('command-output'); + expect(fs.readFileSync(`${directory}/probe-context`, 'utf8')) + .toBe(fs.readFileSync(`${directory}/command-context`, 'utf8')); + assertCleaned(); + }); + + it.each([ + ['printf "malformed-secret\\n"; printf "stderr-secret\\n" >&2', 'probe_output_invalid'], + ['exit 7', 'probe_failed'], + ['printf "%5000s" x', 'probe_output_limit'], + ])('sanitizes failed probes and preserves unconstrained legacy admission: %s', async (version, reason) => { + writeHarness('copilot', version); + await observe(); + expect(report()).toMatchObject({ status: 'unavailable', reason }); + expect(JSON.stringify(report())).not.toContain('secret'); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); + assertCleaned(); + }); + + it.each([ + ['printf "1.2.3\\n"', true, ''], + ['printf "1.0.0\\n"', false, 'harness_incompatible'], + ['printf "malformed\\n"', false, 'harness_unverified'], + ])('enforces only test-owned host requirements before releasing the real command: %s', async (version, admitted, error) => { + config.additionalEnv!.COPILOT_MODEL = 'gpt-6-sol'; + config.copilotGithubToken = 'fixture-token'; + const actualValidation = validateCopilotModel; + jest.spyOn(copilotModels, 'validateCopilotModel').mockImplementation((model, evidence) => + actualValidation(model, { + ...evidence, harnesses: [{ + scope: { provider: 'copilot', channel: 'copilot-cli' }, name: 'copilot-cli', + minimum: '1.2.0', scheme: 'semver', reason: 'Test-owned NVX fixture requirement', + provenance: { authority: 'maintained' }, + }], + })); + writeHarness('copilot', version); + if (admitted) { + await observe(); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); + } else { + await expect(observe()).rejects.toThrow(error); + expect(fs.existsSync(`${directory}/command-context`)).toBe(false); + await backend.stop(); + } + assertCleaned(); + }); + + it('bounds the guest version pipeline at ten seconds, then keeps legacy admission', async () => { + writeHarness('copilot', `trap '' TERM +printf '%s\\n' "$$" >"$FIXTURE_DIRECTORY/probe-pid" +sleep 30 +printf "1.2.3\\n"`); + const started = Date.now(); + await observe(); + expect(Date.now() - started).toBeGreaterThanOrEqual(9900); + expect(Date.now() - started).toBeLessThan(13000); + expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_timed_out' }); + const pid = Number(fs.readFileSync(`${directory}/probe-pid`, 'utf8')); + // A killed child can briefly remain as a zombie until the fixture's init reaps it. + const stat = fs.existsSync(`/proc/${pid}/stat`) ? fs.readFileSync(`/proc/${pid}/stat`, 'utf8') : ''; + expect(stat === '' || stat.split(' ')[2] === 'Z').toBe(true); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); + assertCleaned(); + }, 15000); + + it('collects an early startup exit without waiting for a persistent ready guest or releasing user code', async () => { + createManager.mockImplementation(() => ({ + execute: async () => ({ exitCode: 42, category: 'failure', signal: null }), + })); + await observe(); + expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 42 }); + expect(fs.existsSync(`${directory}/command-context`)).toBe(false); + }); + + it('cancels a guest waiting at the gate and collects its final exit and channel cleanup', async () => { + await observe(); + await backend.stop(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 130 }); + expect(fs.existsSync(`${directory}/command-context`)).toBe(false); + assertCleaned(); + }); + + it('does not execute a second guest when startup rejects', async () => { + createManager.mockImplementation(() => ({ execute: async () => { throw new Error('startup failed'); } })); + await observe(); + expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); + await backend.releaseHarness!(); + await expect(backend.exec(directory, [])).rejects.toThrow('startup failed'); + expect(createManager).toHaveBeenCalledTimes(1); + }); + + it('cancels during version execution without waiting for the readiness deadline', async () => { + writeHarness('copilot', 'sleep 30'); + const observation = observe(); + while (!fs.existsSync(`${directory}/probe-context`)) await new Promise(resolve => setTimeout(resolve, 10)); + await backend.stop(); + await observation; + expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 130 }); + expect(fs.existsSync(`${directory}/command-context`)).toBe(false); + assertCleaned(); + }); + + it('treats a missing binary as unverified, never substituting another harness', async () => { + config.agentCommand = './copilot --fixture'; + await observe(); + expect(report()).toMatchObject({ status: 'unavailable', reason: 'binary_missing' }); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 127 }); + assertCleaned(); + }); + + it('resolves a relative selected executable in the command cwd', async () => { + fs.copyFileSync(`${directory}/bin/copilot`, `${directory}/workspace/copilot`); + config.agentCommand = './copilot --fixture'; + await observe(); + expect(report()).toMatchObject({ status: 'observed', resolvedBinary: './copilot' }); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); + assertCleaned(); + }); + + it('never releases on an invalid run binding and cleans up the waiting guest', async () => { + createManager.mockImplementation(options => { + managerConfig = options; + const probe = options.execution.mounts.find((mount: { tag: string }) => mount.tag === 'harness-probe'); + fs.writeFileSync(`${probe.hostPath}/result`, 'wrong-environment\n0\n/bin/copilot\n1.2.3\n'); + return { + execute: () => new Promise(resolve => options.execution.abortSignal.addEventListener('abort', + () => resolve({ exitCode: 130 }), { once: true })), + }; + }); + await observe(); + expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); + await expect(backend.releaseHarness!()).rejects.toThrow('not ready'); + await backend.stop(); + expect(fs.existsSync(`${directory}/command-context`)).toBe(false); + assertCleaned(); + }); + }); + afterEach(() => { Object.defineProperty(process, 'platform', { value: originalPlatform }); Object.defineProperty(process, 'arch', { value: originalArch }); diff --git a/src/nvx/runtime-backend.ts b/src/nvx/runtime-backend.ts index 580a960d1..665849a4c 100644 --- a/src/nvx/runtime-backend.ts +++ b/src/nvx/runtime-backend.ts @@ -28,6 +28,9 @@ import { import { buildNvxGuestEnvironment } from './guest-environment-builder'; import { buildNvxGuestRunScript } from './guest-entrypoint'; import { NvxGuestConfigLayer } from './guest-config-layer'; +import { harnessContext } from '../harness-observation'; +import { selectHarness, type HarnessProbe } from '../model-information-contract/harness-observation'; +import { NvxHarnessObservation } from './harness-observation'; import { planNvxLiveMounts, type NvxLiveMountPlan, @@ -133,6 +136,30 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { private abortController: AbortController | undefined; private activeExecution: Promise | undefined; private stopped = false; + private harnessObservation: NvxHarnessObservation | undefined; + private oneShotExecution: Promise<{ exitCode: number }> | undefined; + private executionSettled = false; + + readonly probeHarness: HarnessProbe = async () => { + if (this.oneShotExecution || !selectHarness(this.config.agentCommand)) { + throw new Error('NVX selected harness observation cannot be restarted'); + } + this.harnessObservation = new NvxHarnessObservation(harnessContext(this.config)); + // Start exactly one guest now, not a second version-only VM. Its command + // remains gated while the workflow publishes evidence and checks eligibility. + this.oneShotExecution = this.executeOnce(this.config.agentTimeout); + return Promise.race([ + this.harnessObservation.probe(''), + this.oneShotExecution.then(() => { + throw new Error('NVX guest exited before harness observation'); + }), + ]); + }; + + readonly releaseHarness = async (): Promise => { + if (!this.harnessObservation || this.executionSettled) return; + await this.harnessObservation.release(); + }; constructor( private readonly config: WrapperConfig, @@ -210,6 +237,19 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { _proxyLogsDir, agentTimeoutMinutes, ) => { + return this.oneShotExecution ?? this.executeOnce(agentTimeoutMinutes); + }; + + private async executeOnce(agentTimeoutMinutes?: number): Promise<{ exitCode: number }> { + try { + return await this.runExecution(agentTimeoutMinutes); + } finally { + this.executionSettled = true; + await this.harnessObservation?.cleanup(); + } + } + + private async runExecution(agentTimeoutMinutes?: number): Promise<{ exitCode: number }> { if (this.stopped) { throw new Error('NVX microVM execution aborted by shutdown'); } @@ -256,6 +296,11 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { exports, ); logNvxGuestEnvironment(environment, this.dependencies.logger); + const harnessMounts = await this.harnessObservation?.stage(identity.uid, identity.gid); + if (this.stopped) { + throw new Error('NVX microVM execution aborted by shutdown'); + } + const command = withInputPreflight(this.config.agentCommand, this.config.inputDirs); const guestConfigLayer = this.dependencies.createGuestConfigLayer({ stagingRoot: path.join(this.config.workDir ?? '/run/awf-nvx', 'nvx-guest-layer', runId), uid: identity.uid, @@ -263,7 +308,7 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { runScript: buildNvxGuestRunScript({ environment, workingDirectory: resolveNvxGuestWorkDir(this.config.containerWorkDir), - command: withInputPreflight(this.config.agentCommand, this.config.inputDirs), + command: this.harnessObservation?.wrap(command) ?? command, }), homePath: process.env.HOME, hostAliases: { @@ -309,7 +354,7 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { memoryMib: nvx.memoryMib, memoryMaxBytes: nvx.memoryMaxBytes, pidsMax: nvx.pidsMax, - mounts: mountPlan.mounts, + mounts: harnessMounts ? [...mountPlan.mounts, ...harnessMounts] : mountPlan.mounts, ...(timeoutMs === undefined ? {} : { timeoutMs }), abortSignal: abortController.signal, stdout: process.stdout, @@ -336,7 +381,7 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { this.activeExecution = undefined; this.abortController = undefined; } - }; + } async collectDiagnostics(): Promise { // NvxManager tears down all per-run diagnostics-bearing state (network @@ -352,6 +397,7 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { if (this.activeExecution) { await this.activeExecution.catch(() => undefined); } + await this.oneShotExecution?.catch(() => undefined); } } From 3e2343e94df7b06da3b766f485401b44f6ed4443 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:03:51 +0000 Subject: [PATCH 3/6] fix: clean up NVX probe descendants before command release --- docs/INTEGRATION-TESTS.md | 4 +++- scripts/ci/nvx-manager-live-evidence.ts | 13 +++++++++++-- src/cli-workflow.ts | 2 +- src/external-runtime-backend.ts | 2 +- src/nvx/harness-observation.ts | 7 ++++++- src/nvx/runtime-backend.test.ts | 14 ++++++++++++++ 6 files changed, 36 insertions(+), 6 deletions(-) diff --git a/docs/INTEGRATION-TESTS.md b/docs/INTEGRATION-TESTS.md index 3e82dfe20..ee76fc040 100644 --- a/docs/INTEGRATION-TESTS.md +++ b/docs/INTEGRATION-TESTS.md @@ -106,7 +106,9 @@ or KVM produce `blocked`, never successful acceptance. No test requirement is added to the bundled catalogue or authorizes feed activation. **Current acceptance status:** blocked, not live-accepted. The implementation -session on 2026-11-04 had Linux `7.0.0-1017-azure` x86_64 and readable `/dev/kvm`, +session's prerequisite attempt at revision +`20db162668b6ea0f5ce6e2845e1a24ed0ce958c0` (clean tree) on 2026-11-04 +had Linux `7.0.0-1017-azure` x86_64 and readable `/dev/kvm`, but no signed NVX OpenVMM/kernel/initramfs/manifest bundle or distro layer, and neither Bubblewrap nor `mkfs.erofs`. Deterministic results are separate from this missing guest evidence. No Docker/ARC-DinD live acceptance, provider inference, diff --git a/scripts/ci/nvx-manager-live-evidence.ts b/scripts/ci/nvx-manager-live-evidence.ts index 4b08bbdb7..c75a584e8 100644 --- a/scripts/ci/nvx-manager-live-evidence.ts +++ b/scripts/ci/nvx-manager-live-evidence.ts @@ -231,7 +231,8 @@ async function runHarnessObservationCases(inputs: Inputs): Promise { USER: 'nobody', LOGNAME: 'nobody', FIXTURE_DIRECTORY: '/workspace', FIXTURE_ENV: 'controlled', FIXTURE_MODE: mode, FIXTURE_VERSION: version, }, - workingDirectory: '/workspace', command: controller.wrap(config.agentCommand), + workingDirectory: '/workspace', + command: `if touch /run/awf-harness/release/forbidden 2>/dev/null; then exit 90; fi\n${controller.wrap(config.agentCommand)}`, }); prepareHarnessObservation(config); let report; @@ -380,7 +381,15 @@ async function runCase( try { const execution = manager.execute(); try { - if (await options.hostInteraction?.() === 'stop') abortController?.abort(); + if (options.hostInteraction) { + const action = await Promise.race([ + options.hostInteraction(), + execution.then(() => { + throw new Error(`${options.name} exited before host interaction completed`); + }), + ]); + if (action === 'stop') abortController?.abort(); + } } catch (error) { abortController?.abort(); await execution.catch(() => undefined); diff --git a/src/cli-workflow.ts b/src/cli-workflow.ts index 7f1703f45..1502e9874 100644 --- a/src/cli-workflow.ts +++ b/src/cli-workflow.ts @@ -28,7 +28,7 @@ import type { HarnessProbe } from './model-information-contract/harness-observat */ export interface WorkflowDependencies { probeHarness?: HarnessProbe; - /** Release Docker's pre-command gate only after publication and eligibility recheck. */ + /** Release a pre-command gate only after publication and eligibility recheck. */ releaseHarness?: () => Promise; ensureFirewallNetwork: (subnetOverride?: string) => Promise<{ squidIp: string; agentIp: string; proxyIp: string; subnet: string }>; setupHostIptables: (squidIp: string, port: number, dnsServers: string[], apiProxyIp?: string, dohProxyIp?: string, hostAccess?: HostAccessConfig, cliProxyConfig?: CliProxyHostConfig, gatewayIp?: string) => Promise; diff --git a/src/external-runtime-backend.ts b/src/external-runtime-backend.ts index 3576b2b24..6c80d2c0b 100644 --- a/src/external-runtime-backend.ts +++ b/src/external-runtime-backend.ts @@ -17,7 +17,7 @@ export interface ExternalAgentRuntimeBackend { stop(): Promise; /** Safely quiesces the runtime while retaining inspectable state. */ preserve?(): Promise; - /** Bounded output from the ready agent environment, not the host installation. */ + /** Bounded output from the agent environment; a one-shot backend may launch here. */ probeHarness?: HarnessProbe; /** Release a one-shot guest only after observation publication and eligibility. */ releaseHarness?: () => Promise; diff --git a/src/nvx/harness-observation.ts b/src/nvx/harness-observation.ts index aa2341189..f4fae6834 100644 --- a/src/nvx/harness-observation.ts +++ b/src/nvx/harness-observation.ts @@ -134,7 +134,12 @@ if [ -f ${GUEST_PROBE}/timed-out ]; then exit 124 fi kill -TERM -- "-$watchdog" 2>/dev/null || : -wait "$watchdog" 2>/dev/null || :`; +wait "$watchdog" 2>/dev/null || : +kill -TERM -- "-$probe" 2>/dev/null || : +if kill -0 -- "-$probe" 2>/dev/null; then + /bin/sleep 1 + kill -KILL -- "-$probe" 2>/dev/null || : +fi`; return `( umask 077 if /bin/bash --noprofile --norc -p -c ${quote(bounded)} >${GUEST_PROBE}/stdout 2>/dev/null; then diff --git a/src/nvx/runtime-backend.test.ts b/src/nvx/runtime-backend.test.ts index 4aa982700..62eddc40d 100644 --- a/src/nvx/runtime-backend.test.ts +++ b/src/nvx/runtime-backend.test.ts @@ -333,6 +333,20 @@ printf "1.2.3\\n"`); expect(createManager).toHaveBeenCalledTimes(1); }); + it('kills background probe helpers even when version execution succeeds', async () => { + writeHarness('copilot', `( trap '' TERM; exec sleep 30 ) >/dev/null 2>&1 & +printf '%s\\n' "$!" >"$FIXTURE_DIRECTORY/helper-pid" +printf '1.2.3\\n'`); + await observe(); + expect(report()).toMatchObject({ status: 'observed' }); + const pid = Number(fs.readFileSync(`${directory}/helper-pid`, 'utf8')); + const stat = fs.existsSync(`/proc/${pid}/stat`) ? fs.readFileSync(`/proc/${pid}/stat`, 'utf8') : ''; + expect(stat === '' || stat.split(' ')[2] === 'Z').toBe(true); + await backend.releaseHarness!(); + expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); + assertCleaned(); + }); + it('cancels during version execution without waiting for the readiness deadline', async () => { writeHarness('copilot', 'sleep 30'); const observation = observe(); From bfd0b766d86b717f7ae50c586898c96477f31e82 Mon Sep 17 00:00:00 2001 From: "copilot-swe-agent[bot]" <198982749+Copilot@users.noreply.github.com> Date: Wed, 4 Nov 2026 15:54:55 +0000 Subject: [PATCH 4/6] fix: keep NVX observation work within current scope --- docs/INTEGRATION-TESTS.md | 60 ++-- docs/adr/0004-model-information-management.md | 35 +-- scripts/ci/nvx-manager-live-evidence.ts | 152 +-------- src/cli-workflow.ts | 2 +- src/commands/main-action.ts | 2 +- .../validators/api-proxy-validator.ts | 2 +- src/external-runtime-backend.ts | 4 +- src/harness-observation.test.ts | 27 +- src/harness-observation.ts | 2 +- src/nvx/harness-observation.ts | 167 ---------- src/nvx/runtime-backend.test.ts | 290 ------------------ src/nvx/runtime-backend.ts | 52 +--- 12 files changed, 56 insertions(+), 739 deletions(-) delete mode 100644 src/nvx/harness-observation.ts diff --git a/docs/INTEGRATION-TESTS.md b/docs/INTEGRATION-TESTS.md index ee76fc040..2bfc0351c 100644 --- a/docs/INTEGRATION-TESTS.md +++ b/docs/INTEGRATION-TESTS.md @@ -71,48 +71,24 @@ digests. Scan targets, vulnerability database updates, and the blocking High/Critical PR-image gate are unchanged. The setup script validates the merged daemon configuration before restart and refuses local or self-hosted runners. -### Provider-free NVX harness observations - -The deterministic NVX cases in `src/nvx/runtime-backend.test.ts` run the generated -one-shot entrypoint in local shells with fixture executables. They verify the -adapter's single-launch ordering, command context, bounded/sanitized evidence, -test-only host requirements, cancellation, exit collection and observation-share -cleanup. They do **not** establish NVX guest compatibility. - -On a supported Linux x86_64/KVM runner provisioned with the existing signed NVX -release artifacts, distro layer, host tools and infrastructure bridge, the -existing live runner offers a separate provider-free mode: - -```bash -sudo npx tsx scripts/ci/nvx-manager-live-evidence.ts \ - --artifacts /absolute/path/to/attested-nvx-artifacts \ - --layer /absolute/path/to/distro-layer \ - --bridge awfnvxbr0 \ - --signerWorkflow github/gh-aw-firewall/.github/workflows/release.yml \ - --evidence /tmp/nvx-harness-live-evidence \ - --harnessOnly true -``` - -Use the signer workflow from the attested artifact release, not an arbitrary -replacement. This mode does not run the default provider-inference campaign. -It uses the production NVX manager, guest entrypoint and observation producer -with the existing version fixture, checks matching guest contexts, and exercises -compatible, incompatible and unverified test-owned requirements before command -release. Blocked commands are cancelled; final outcomes, confinement and resource -residue checks still use the existing manager evidence path. It writes -`harness-observation-live.json` with the tested Git revision, Linux environment, -artifact manifest, sanitized reports and individual outcomes. Missing artifacts -or KVM produce `blocked`, never successful acceptance. No test requirement is -added to the bundled catalogue or authorizes feed activation. - -**Current acceptance status:** blocked, not live-accepted. The implementation -session's prerequisite attempt at revision -`20db162668b6ea0f5ce6e2845e1a24ed0ce958c0` (clean tree) on 2026-11-04 -had Linux `7.0.0-1017-azure` x86_64 and readable `/dev/kvm`, -but no signed NVX OpenVMM/kernel/initramfs/manifest bundle or distro layer, and -neither Bubblewrap nor `mkfs.erofs`. Deterministic results are separate from this -missing guest evidence. No Docker/ARC-DinD live acceptance, provider inference, -enclave observation or opaque/session attribution is claimed. +### NVX harness-observation limitation + +NVX currently launches the configured command through one atomic +`NvxManager.execute()` lifecycle. It does not expose a persistent ready guest or +a selected-harness probe/pre-command release interface, so NVX harness +observations remain `runtime_probe_unsupported`. The existing manager tests and +live evidence runner validate NVX execution and result/cleanup behavior only; +they do not establish selected-harness evidence or guest compatibility for a +probe lifecycle. + +**Current live acceptance status:** blocked, not live-accepted. A provider-free +NVX guest acceptance run requires signed OpenVMM/kernel/initramfs/manifest +artifacts, a distro layer, and host tooling including Bubblewrap and +`mkfs.erofs`, in addition to a supported Linux x86_64/KVM runner. The recorded +prerequisite attempt had no signed runtime bundle or distro layer and lacked +Bubblewrap and `mkfs.erofs`. Deterministic fixtures are not a substitute for +that guest evidence. No NVX harness-observation producer or live acceptance is +claimed. ### Provider-free Docker harness observations diff --git a/docs/adr/0004-model-information-management.md b/docs/adr/0004-model-information-management.md index 2b888d183..3574c4880 100644 --- a/docs/adr/0004-model-information-management.md +++ b/docs/adr/0004-model-information-management.md @@ -1447,7 +1447,7 @@ support list: sbx is not supported, and runc/gVisor/Kata are not separate supported product targets. The host produces selected-harness observations through the existing ready -Cloud Hypervisor execution channel and Docker/NVX command-shell pre-command gates, +Cloud Hypervisor execution channel and a Docker command-shell pre-command gate, after backend startup and before primary command execution. Selection is deliberately limited to direct `copilot`, `claude`, and `codex` executables (including simple absolute or `./` paths), mapped to the @@ -1462,7 +1462,7 @@ never establishes selection. | Cloud Hypervisor primary guest | Existing `manager.execute` channel, same guest UID/GID, environment, cwd and login shell as the primary command | | Docker primary agent | Generated command prelude runs the probe after the existing entrypoint's identity, chroot, environment, PATH and cwd setup; user command waits for host publication/recheck and release | | ARC/DinD (Docker deployment topology) | Same Docker producer, with container-local private tmpfs control transport via Docker exec; public report publication retains existing runner-visible log-mount translation | -| NVX primary guest | The observation starts the single existing `manager.execute` lifecycle; the generated entrypoint probes in the command's non-login `/bin/sh`, UID/GID, env, PATH and cwd, then waits for host publication/recheck and release over existing virtio-fs mounts | +| NVX | Explicit `runtime_probe_unsupported`; its one-shot execute lifecycle exposes no persistent ready guest for a separate observation | | Enclave executors | No primary observation is attached to the dedicated enclave proxy; per-invocation enclave observation remains unimplemented | Supported probes resolve the selected executable with `command -v` and run only @@ -1511,23 +1511,6 @@ back to the existing log/exit-status collection, without issuing any release. Historical non-default OCI backend names do not gain additional producer coverage in this slice. -NVX does not assume a persistent ready guest or launch a version-only VM. -Its probe rendezvous is a private per-run read-write share; its separate release -share is read-only in the guest, because NVX maps workload ownership to share -ownership. Only the host can publish the release. The generated POSIX prelude -uses the supported distro's Bash job control to supervise whole process groups -(BusyBox timeout alone signals only one PID), bounds the entire pipeline to -10 seconds plus a one-second kill grace, retains at most 4097 stdout -bytes, and discards stderr. Readiness and release each have a 120-second bound. -The host bounds the raw read and checks its unique environment binding before -publishing through the same canonical parser and atomic report path. -An applicable failed host recheck never releases the guest. Failed version -evidence alone still permits unconstrained legacy admission, not verified support. -Startup failure races readiness so an exited guest cannot deadlock observation; -the existing one-shot result remains responsible for exit status, timeout, -cancellation and manager cleanup. Private observation shares are removed after -that execution settles, including failed startup and cancellation. - `src/harness-observation.ts` initializes explicit unavailable/pending evidence before Compose generation, then atomically publishes the observation to `harness-observation.json` in the existing primary API-proxy log mount. @@ -1548,7 +1531,7 @@ requirement reason. The host also supplies the report when rechecking concrete `COPILOT_MODEL` CLI selections (flags, env files or opted-in host env) after backend readiness. Pre-start offline validation preserves naming/retirement checks but defers an otherwise-known direct Copilot model's unverified harness decision to -that pre-command check on Cloud Hypervisor, NVX and Docker (including ARC/DinD). +that ready-runtime check on Cloud Hypervisor and Docker (including ARC/DinD). Alias candidate expansion and its final harness eligibility remain proxy-owned; custom provider paths retain their existing validation exemption. No applicable constraint means legacy admission, not a claim of @@ -1579,16 +1562,8 @@ deployments. Live Docker and ARC/DinD acceptance must be recorded separately when infrastructure is available; no live provider inference or workflow dispatch is needed. -NVX deterministic shell-transport fixtures exercise its real backend adapter, -generated entrypoint, probe bounds, context equality, host requirements, startup -failure, cancellation, final exit and share cleanup. They are not live guest -acceptance. The existing NVX live-evidence runner has a separate provider-free -`--harnessOnly true` mode; prerequisites and recorded acceptance are described in -[the integration guide](../INTEGRATION-TESTS.md). - -**Remaining handoff:** live supported NVX guest acceptance must be recorded -separately; product support and deterministic fixtures do not establish it. -Per-invocation enclave observations, +**Remaining handoff:** the actual observation producer for NVX is still missing; +product support does not imply observation capability. Per-invocation enclave observations, opaque commands and per-session attribution, and complete pre-start enforcement on lifecycles without observation capability remain open. This slice keeps the bundled constraint projection empty. An opaque diff --git a/scripts/ci/nvx-manager-live-evidence.ts b/scripts/ci/nvx-manager-live-evidence.ts index c75a584e8..1b46d7dd4 100644 --- a/scripts/ci/nvx-manager-live-evidence.ts +++ b/scripts/ci/nvx-manager-live-evidence.ts @@ -12,13 +12,6 @@ import { type NvxLiveMount, } from '../../src/nvx'; import { guardStaleChildPipe } from './nvx-manager-live-evidence-stream'; -import { NvxHarnessObservation } from '../../src/nvx/harness-observation'; -import { buildNvxGuestRunScript } from '../../src/nvx/guest-entrypoint'; -import { harnessContext, observeHarness, prepareHarnessObservation } from '../../src/harness-observation'; -import { eligibilityEvidence } from '../../src/model-information-contract/harness-observation'; -import { createEligibilityStore } from '../../src/model-information-contract/eligibility'; -import { identity } from '../../src/model-information-contract/identity'; -import type { WrapperConfig } from '../../src/types'; interface Inputs { artifacts: string; @@ -27,7 +20,6 @@ interface Inputs { signerWorkflow: string; evidence: string; childRunId?: string; - harnessOnly?: boolean; } const MAX_CAPTURED_OUTPUT_BYTES = 64 * 1024; @@ -38,10 +30,6 @@ async function main(): Promise { } const inputs = parseInputs(process.argv.slice(2)); await fs.mkdir(inputs.evidence, { recursive: true, mode: 0o700 }); - if (inputs.harnessOnly) { - await runHarnessObservationCases(inputs); - return; - } if (inputs.childRunId) { await runCase(inputs, { name: 'stale-owner-child', @@ -168,134 +156,7 @@ interface RunCaseOptions { scratchBytes?: number; mounts?: readonly NvxLiveMount[]; runScript?: string; - hostInteraction?: () => Promise; -} - -/** Provider-free acceptance, deliberately separate from deterministic shell fixtures. */ -async function runHarnessObservationCases(inputs: Inputs): Promise { - const revision = (await execa('git', ['rev-parse', 'HEAD'])).stdout; - const environment = (await execa('uname', ['-smr'])).stdout; - const dirty = Boolean((await execa('git', ['status', '--porcelain'])).stdout); - const evidenceFile = path.join(inputs.evidence, 'harness-observation-live.json'); - const evidence: Record = { - schemaVersion: 1, revision, dirty, environment, status: 'blocked', cases: [], - }; - const checks: unknown[] = []; - evidence.cases = checks; - const writeEvidence = () => fs.writeFile(evidenceFile, `${JSON.stringify(evidence, null, 2)}\n`); - const prerequisites = [ - '/dev/kvm', inputs.layer, - ...['openvmm', 'vmlinux', 'initramfs.cpio.gz', 'manifest.json', 'manifest.sigstore.jsonl'] - .map(name => path.join(inputs.artifacts, name)), - ]; - const missing: string[] = []; - for (const filename of prerequisites) { - try { await fs.access(filename, constants.R_OK); } catch { missing.push(filename); } - } - if (missing.length) { - evidence.missing = missing; - await writeEvidence(); - throw new Error('NVX harness live acceptance blocked: missing KVM/runtime artifacts (see evidence)'); - } - evidence.manifest = JSON.parse(await fs.readFile(path.join(inputs.artifacts, 'manifest.json'), 'utf8')); - evidence.status = 'failed'; - await writeEvidence(); - try { - for (const [binary, mode, version, expected] of [ - ['copilot', 'valid', '1.2.3', 'compatible'], - ['claude', 'valid', '2.1.3 (Claude Code)', 'compatible'], - ['codex', 'valid', 'codex-cli 0.89.0', 'incompatible'], - ['copilot', 'valid', '1.0.0', 'incompatible'], - ...['malformed', 'failed', 'overflow', 'timeout', 'missing'].map(mode => - ['copilot', mode, '1.2.3', 'unverified']), - ]) { - const workspace = await fs.mkdtemp('/tmp/awf-nvx-harness-live-'); - await fs.chmod(workspace, 0o755); - await fs.chown(workspace, 65534, 65534); - const config = { - containerRuntime: 'nvx', agentCommand: `./${binary} --fixture`, - workDir: workspace, enableApiProxy: true, - } as WrapperConfig; - const controller = new NvxHarnessObservation(harnessContext(config)); - try { - await fs.mkdir(path.join(workspace, 'api-proxy-logs')); - if (mode !== 'missing') { - await fs.copyFile(path.resolve('tests/fixtures/harness-observation/executable.sh'), - path.join(workspace, binary)); - await fs.chmod(path.join(workspace, binary), 0o755); - } - const mounts = await controller.stage(65534, 65534); - const runScript = buildNvxGuestRunScript({ - environment: { - PATH: '/usr/local/bin:/usr/bin:/bin', HOME: '/tmp/awf-home', - USER: 'nobody', LOGNAME: 'nobody', FIXTURE_DIRECTORY: '/workspace', - FIXTURE_ENV: 'controlled', FIXTURE_MODE: mode, FIXTURE_VERSION: version, - }, - workingDirectory: '/workspace', - command: `if touch /run/awf-harness/release/forbidden 2>/dev/null; then exit 90; fi\n${controller.wrap(config.agentCommand)}`, - }); - prepareHarnessObservation(config); - let report; - const outcome = await runCase(inputs, { - name: `selected-harness-${binary}-${mode}-${version.split(' ')[0]}`, - entrypoint: '/etc/awf/nvx-run.sh', timeoutMs: 120_000, runScript, - mounts: [{ - tag: 'workspace', guestTarget: '/workspace', hostPath: workspace, mode: 'rw', - deniedPaths: [], allowedPaths: [], writablePaths: [], - }, ...mounts], - hostInteraction: async () => { - report = await observeHarness(config, controller.probe); - const scope = { provider: 'copilot', channel: 'fixture' }; - const model = identity('copilot', 'fixture-model'); - const snapshot = createEligibilityStore({ models: [{ - identity: model, harnesses: [{ - scope, name: harnessContext(config).name!, minimum: '1.2.0', - scheme: 'semver', reason: 'Test-only NVX requirement', - provenance: { authority: 'maintained' }, - }], - }] }).pin(); - const decision = snapshot.evaluate({ - identity: model, scope, ...eligibilityEvidence(report, scope), - discovery: { status: 'available', authoritative: true }, - }); - if (decision.harness !== expected) throw new Error('Unexpected NVX harness eligibility'); - try { - await fs.access(path.join(workspace, 'command-context')); - throw new Error('NVX command started before host eligibility'); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; - } - if (!decision.admitted) return 'stop'; - await controller.release(); - }, - }); - if (expected === 'compatible') { - if (outcome.result.exitCode !== 23) throw new Error('NVX fixture exit code was not propagated'); - const probe = await fs.readFile(path.join(workspace, 'probe-context'), 'utf8'); - const command = await fs.readFile(path.join(workspace, 'command-context'), 'utf8'); - if (probe !== command) throw new Error('NVX probe and command contexts differ'); - } else { - if (outcome.result.exitCode !== 130 || outcome.result.category !== 'cancelled') { - throw new Error('NVX blocked guest did not complete cancellation'); - } - try { - await fs.access(path.join(workspace, 'command-context')); - throw new Error('NVX blocked command executed'); - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; - } - } - checks.push({ binary, mode, expected, report, outcome, status: 'passed' }); - await writeEvidence(); - } finally { - await controller.cleanup(); - await fs.rm(workspace, { recursive: true, force: true }); - } - } - evidence.status = 'passed'; - } finally { - await writeEvidence(); - } + hostInteraction?: () => Promise; } async function runCase( @@ -381,15 +242,7 @@ async function runCase( try { const execution = manager.execute(); try { - if (options.hostInteraction) { - const action = await Promise.race([ - options.hostInteraction(), - execution.then(() => { - throw new Error(`${options.name} exited before host interaction completed`); - }), - ]); - if (action === 'stop') abortController?.abort(); - } + await options.hostInteraction?.(); } catch (error) { abortController?.abort(); await execution.catch(() => undefined); @@ -760,7 +613,6 @@ function parseInputs(args: readonly string[]): Inputs { signerWorkflow, evidence: required('evidence'), ...(values.get('childRunId') ? { childRunId: values.get('childRunId') } : {}), - ...(values.get('harnessOnly') === 'true' ? { harnessOnly: true } : {}), }; } diff --git a/src/cli-workflow.ts b/src/cli-workflow.ts index 1502e9874..7f1703f45 100644 --- a/src/cli-workflow.ts +++ b/src/cli-workflow.ts @@ -28,7 +28,7 @@ import type { HarnessProbe } from './model-information-contract/harness-observat */ export interface WorkflowDependencies { probeHarness?: HarnessProbe; - /** Release a pre-command gate only after publication and eligibility recheck. */ + /** Release Docker's pre-command gate only after publication and eligibility recheck. */ releaseHarness?: () => Promise; ensureFirewallNetwork: (subnetOverride?: string) => Promise<{ squidIp: string; agentIp: string; proxyIp: string; subnet: string }>; setupHostIptables: (squidIp: string, port: number, dnsServers: string[], apiProxyIp?: string, dohProxyIp?: string, hostAccess?: HostAccessConfig, cliProxyConfig?: CliProxyHostConfig, gatewayIp?: string) => Promise; diff --git a/src/commands/main-action.ts b/src/commands/main-action.ts index 0009e64cb..a8ccdf518 100644 --- a/src/commands/main-action.ts +++ b/src/commands/main-action.ts @@ -868,7 +868,7 @@ export function createMainAction(getOptionValueSource: OptionSourceResolver) { setupHostIptables, writeConfigs, probeHarness: externalRuntimeBackend?.probeHarness?.bind(externalRuntimeBackend) ?? dockerHarness?.probeHarness, - releaseHarness: externalRuntimeBackend?.releaseHarness?.bind(externalRuntimeBackend) ?? dockerHarness?.releaseHarness, + releaseHarness: dockerHarness?.releaseHarness, startContainers: externalWorkflowDependencies?.startContainers ?? startContainers, runAgentCommand: trackedRunAgentCommand, collectDiagnosticLogs: workflowCollectDiagnosticLogs, diff --git a/src/commands/validators/api-proxy-validator.ts b/src/commands/validators/api-proxy-validator.ts index 8ba255537..316a91312 100644 --- a/src/commands/validators/api-proxy-validator.ts +++ b/src/commands/validators/api-proxy-validator.ts @@ -190,7 +190,7 @@ export function validateCopilotModelOption( const deferredToReadyRuntime = (result: ReturnType): boolean => !result.valid && result.eligibility?.harness === 'unverified' && result.eligibility.status === 'unknown' && selectedHarness === 'copilot-cli' && - (config.containerRuntime === 'cloud-hypervisor' || config.containerRuntime === 'nvx' || supportsDockerHarnessObservation(config)); + (config.containerRuntime === 'cloud-hypervisor' || supportsDockerHarnessObservation(config)); if ( copilotModel && !hasCustomCopilotProvider(config) && diff --git a/src/external-runtime-backend.ts b/src/external-runtime-backend.ts index 6c80d2c0b..12fb82958 100644 --- a/src/external-runtime-backend.ts +++ b/src/external-runtime-backend.ts @@ -17,10 +17,8 @@ export interface ExternalAgentRuntimeBackend { stop(): Promise; /** Safely quiesces the runtime while retaining inspectable state. */ preserve?(): Promise; - /** Bounded output from the agent environment; a one-shot backend may launch here. */ + /** Bounded output from the ready agent environment, not the host installation. */ probeHarness?: HarnessProbe; - /** Release a one-shot guest only after observation publication and eligibility. */ - releaseHarness?: () => Promise; } type ExternalRuntimeWorkflowDependencies = Pick< diff --git a/src/harness-observation.test.ts b/src/harness-observation.test.ts index 86b28b757..286c51abb 100644 --- a/src/harness-observation.test.ts +++ b/src/harness-observation.test.ts @@ -164,8 +164,7 @@ describe('actual-environment harness observations', () => { expect(probe).not.toHaveBeenCalled(); }); - it.each(['cloud-hypervisor', 'nvx'] as const)('wires %s output through the atomic file to immutable scoped proxy eligibility pins', async runtime => { - config.containerRuntime = runtime; + it('wires ready-backend output through the atomic file to immutable scoped proxy eligibility pins', async () => { prepareHarnessObservation(config); connectProxy(); const evidence = store(); @@ -252,7 +251,7 @@ describe('actual-environment harness observations', () => { config.runnerTopology = topology; prepareHarnessObservation(config); expect(report()).toMatchObject({ - status: 'unavailable', reason: 'probe_pending', + status: 'unavailable', reason: runtime === 'nvx' ? 'runtime_probe_unsupported' : 'probe_pending', }); expect(harnessContext(config).environment).toMatch(runtime === 'nvx' ? /^nvx:/ : /^docker:/); expect(await observeHarness(config)).toMatchObject({ status: 'unavailable', reason: 'runtime_probe_unsupported' }); @@ -288,7 +287,6 @@ describe('actual-environment harness observations', () => { }); it.each([ ['Cloud Hypervisor', 'cloud-hypervisor', 'standard'], - ['NVX', 'nvx', 'standard'], ['Docker', undefined, 'standard'], ['ARC/DinD', undefined, 'arc-dind'], ] as const)('defers pending host harness checks until %s is ready, then enforces the real report', async (_target, runtime, topology) => { @@ -313,6 +311,27 @@ describe('actual-environment harness observations', () => { await expect(observeHarness(config, jest.fn().mockResolvedValue({ exitCode: 127, stdout: '' }))).rejects .toThrow('observation=binary_missing'); }); + it.each([ + ['NVX', 'nvx', 'standard'], + ] as const)('does not defer an applicable host requirement without an observation producer on %s', (_target, runtime, topology) => { + config.containerRuntime = runtime; + config.runnerTopology = topology; + config.copilotGithubToken = 'fixture-token'; + config.additionalEnv = { COPILOT_MODEL: 'gpt-6-sol' }; + const actualValidation = copilotModels.validateCopilotModel; + jest.spyOn(copilotModels, 'validateCopilotModel').mockImplementation((model, evidence) => + actualValidation(model, { + ...evidence, + harnesses: [{ ...requirement, scope: { provider: 'copilot', channel: 'copilot-cli' } }], + })); + const exit = jest.spyOn(process, 'exit').mockImplementation(() => { + throw new Error('preflight rejected'); + }); + expect(() => validateCopilotModelOption(config, { + additionalEnv: config.additionalEnv!, volumeMounts: undefined, allowedUrls: undefined, + })).toThrow('preflight rejected'); + expect(exit).toHaveBeenCalledWith(1); + }); it('does not impose the first alias candidate floor on a later eligible runtime sibling', async () => { config.copilotGithubToken = 'fixture-token'; config.additionalEnv = { COPILOT_MODEL: 'coding' }; diff --git a/src/harness-observation.ts b/src/harness-observation.ts index c72bca243..a6d04185f 100644 --- a/src/harness-observation.ts +++ b/src/harness-observation.ts @@ -56,7 +56,7 @@ function publish(config: WrapperConfig, report: HarnessObservationReport): void export function prepareHarnessObservation(config: WrapperConfig): void { const context = harnessContext(config); publish(config, unavailable(context, !context.name ? 'selection_unavailable' : - config.containerRuntime === 'cloud-hypervisor' || config.containerRuntime === 'nvx' || supportsDockerHarnessObservation(config) + config.containerRuntime === 'cloud-hypervisor' || supportsDockerHarnessObservation(config) ? 'probe_pending' : 'runtime_probe_unsupported')); } diff --git a/src/nvx/harness-observation.ts b/src/nvx/harness-observation.ts deleted file mode 100644 index f4fae6834..000000000 --- a/src/nvx/harness-observation.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { constants, promises as fs } from 'fs'; -import * as os from 'os'; -import * as path from 'path'; -import { shellSingleQuote as quote } from '../cloud-hypervisor/backend-utils'; -import { - MAX_PROBE_BYTES, probeCommand, selectHarness, - type HarnessContext, type HarnessProbe, -} from '../model-information-contract/harness-observation'; -import type { NvxLiveMount } from './live-mount-policy'; - -const GUEST_CONTROL = '/run/awf-harness'; -const GUEST_PROBE = `${GUEST_CONTROL}/probe`; -const GUEST_RELEASE = `${GUEST_CONTROL}/release`; -const READY_TIMEOUT_MS = 120_000; - -/** - * One-shot rendezvous over NVX's existing virtio-fs transport. Only the guest - * writes probe output; the host publishes sanitized evidence before releasing it. - */ -export class NvxHarnessObservation { - private root: string | undefined; - private directory: string | undefined; - private releaseDirectory: string | undefined; - private ready = false; - private closed = false; - - constructor(private readonly context: HarnessContext) {} - - async stage(uid: number, gid: number): Promise { - this.root = await fs.mkdtemp(path.join(os.tmpdir(), 'awf-nvx-harness-')); - // The confined VMM must traverse the parent to export the private directory. - await fs.chmod(this.root, 0o711); - this.directory = path.join(this.root, 'probe'); - this.releaseDirectory = path.join(this.root, 'release'); - for (const directory of [this.directory, this.releaseDirectory]) { - await fs.mkdir(directory, { mode: 0o700 }); - await fs.chown(directory, uid, gid); - } - // NVX maps guest workload ownership to each share's owner. A separate - // read-only share, not mode bits, keeps the release host-owned in the guest. - return [ - { tag: 'harness-probe', hostPath: this.directory, guestTarget: GUEST_PROBE, mode: 'rw', - deniedPaths: [], allowedPaths: [], writablePaths: [] }, - { tag: 'harness-release', hostPath: this.releaseDirectory, guestTarget: GUEST_RELEASE, mode: 'ro', - deniedPaths: [], allowedPaths: [], writablePaths: [] }, - ]; - } - - wrap(command: string): string { - return withNvxHarnessObservation(this.context, command); - } - - readonly probe: HarnessProbe = async () => { - const deadline = Date.now() + READY_TIMEOUT_MS; - while (!this.closed && Date.now() < deadline) { - if (this.directory) { - let file; - try { - file = await fs.open(path.join(this.directory, 'result'), - constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); - const stat = await file.stat(); - if (!stat.isFile() || stat.size > MAX_PROBE_BYTES + 257) { - throw new Error('Invalid NVX harness observation'); - } - const buffer = Buffer.alloc(MAX_PROBE_BYTES + 258); - const { bytesRead } = await file.read(buffer, 0, buffer.length, 0); - const [environment, status, ...output] = buffer.subarray(0, bytesRead).toString('utf8').split('\n'); - if (environment !== this.context.environment || !/^\d{1,3}$/.test(status)) { - throw new Error('Invalid NVX harness observation binding'); - } - const stdout = output.join('\n'); - const exitCode = Number(status); - this.ready = true; - return { - stdout, exitCode, timedOut: exitCode === 124 || exitCode === 137, - overflow: Buffer.byteLength(stdout) > MAX_PROBE_BYTES, - }; - } catch (error) { - if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error; - } finally { - await file?.close(); - } - } - await new Promise(resolve => setTimeout(resolve, 20)); - } - throw new Error('NVX harness observation timed out; command not started'); - }; - - async release(): Promise { - if (!this.ready || !this.releaseDirectory) { - throw new Error('NVX harness observation is not ready; command not started'); - } - const temporary = path.join(this.releaseDirectory, 'allow.tmp'); - await fs.writeFile(temporary, `${this.context.environment}\n`, { flag: 'wx', mode: 0o444 }); - await fs.rename(temporary, path.join(this.releaseDirectory, 'allow')); - this.ready = false; - } - - async cleanup(): Promise { - this.closed = true; - if (this.root) await fs.rm(this.root, { recursive: true, force: true }); - this.directory = undefined; - this.releaseDirectory = undefined; - this.root = undefined; - } -} - -/** Runs in the same non-login /bin/sh, UID/GID, cwd and exported env as the command. */ -export function withNvxHarnessObservation(context: HarnessContext, command: string): string { - const selection = selectHarness(context.binary || ''); - if (!selection || selection.name !== context.name) throw new Error('Invalid NVX selected harness'); - const probe = `${probeCommand(selection)}`; - // BusyBox timeout signals only one PID. Bash job control gives both the probe - // pipeline and watchdog their own groups, so neither leaves descendants behind. - // -p suppresses startup evaluation without changing exported BASH_ENV. - const bounded = `set -m -( - set +m - ( /bin/sh -c ${quote(probe)}; printf '%s\\n' "$?" >${GUEST_PROBE}/status ) | /usr/bin/head -c ${MAX_PROBE_BYTES + 1} -) & -probe=$! -( - set +m - /bin/sleep 10 - : >${GUEST_PROBE}/timed-out - kill -TERM -- "-$probe" 2>/dev/null || : - /bin/sleep 1 - kill -KILL -- "-$probe" 2>/dev/null || : -) & -watchdog=$! -wait "$probe" 2>/dev/null || : -if [ -f ${GUEST_PROBE}/timed-out ]; then - wait "$watchdog" 2>/dev/null || : - exit 124 -fi -kill -TERM -- "-$watchdog" 2>/dev/null || : -wait "$watchdog" 2>/dev/null || : -kill -TERM -- "-$probe" 2>/dev/null || : -if kill -0 -- "-$probe" 2>/dev/null; then - /bin/sleep 1 - kill -KILL -- "-$probe" 2>/dev/null || : -fi`; - return `( -umask 077 -if /bin/bash --noprofile --norc -p -c ${quote(bounded)} >${GUEST_PROBE}/stdout 2>/dev/null; then - if [ -f ${GUEST_PROBE}/status ]; then IFS= read -r status <${GUEST_PROBE}/status; else status=126; fi -else - status=$? -fi -cd ${quote(GUEST_PROBE)} || exit 125 -printf '%s\\n%s\\n' ${quote(context.environment)} "$status" >result.tmp || exit 125 -/bin/cat stdout >>result.tmp || exit 125 -/bin/mv result.tmp result || exit 125 -n=0 -while [ "$n" -lt ${READY_TIMEOUT_MS / 100} ]; do - if [ -f ${GUEST_RELEASE}/allow ]; then - IFS= read -r decision <${GUEST_RELEASE}/allow - [ "$decision" = ${quote(context.environment)} ] || exit 125 - exit 0 - fi - /bin/sleep 0.1 - n=$((n + 1)) -done -exit 125 -) || exit 125 -${command}`; -} diff --git a/src/nvx/runtime-backend.test.ts b/src/nvx/runtime-backend.test.ts index 62eddc40d..77aa50b02 100644 --- a/src/nvx/runtime-backend.test.ts +++ b/src/nvx/runtime-backend.test.ts @@ -1,12 +1,4 @@ import type { WrapperConfig } from '../types'; -import fs from 'fs'; -import os from 'os'; -import path from 'path'; -import execa from 'execa'; -import { harnessContext, observeHarness, prepareHarnessObservation } from '../harness-observation'; -import { validateCopilotModel } from '../copilot-model'; -import * as copilotModels from '../copilot-model'; -import { buildNvxKernelCommandLine } from './one-shot-arguments'; import type { MicrovmInfrastructureSnapshot } from '../microvm/infrastructure'; import type { NvxOneShotExecutionResult } from './one-shot-adapter'; import { withInputPreflight } from '../input-preflight'; @@ -115,288 +107,6 @@ describe('NvxRuntimeBackend', () => { Object.defineProperty(process, 'arch', { value: 'x64' }); }); - describe('NVX one-shot selected-harness shell transport fixture (not live NVX)', () => { - let directory: string; - let config: WrapperConfig; - let backend: ReturnType; - let guestScript: string; - let child: execa.ExecaChildProcess | undefined; - let managerConfig: Parameters[0]; - let createManager: jest.Mock; - - beforeEach(() => { - directory = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-nvx-observation-test-')); - for (const name of ['bin', 'workspace', 'api-proxy-logs']) fs.mkdirSync(path.join(directory, name)); - config = { - ...nvxConfig(), workDir: directory, allowedDomains: [], logLevel: 'error', keepContainers: false, - agentCommand: 'copilot --fixture', - additionalEnv: { - FIXTURE_DIRECTORY: directory, FIXTURE_ENV: 'command-env', - }, - }; - writeHarness('copilot', 'printf "1.2.3\\n"'); - createManager = jest.fn(options => { - managerConfig = options; - return { - execute: async () => { - let script = guestScript.split('/tmp/awf-home').join(`${directory}/home`) - .split('/home/awf').join(`${directory}/seed`) - .split("cd '/workspace'").join(`cd '${directory}/workspace'`); - // Map distro-installed fixture binaries onto the generated guest PATH. - script = script.replace("export PATH='", `export PATH='${directory}/bin:`); - for (const mount of options.execution.mounts) { - if (mount.tag.startsWith('harness-')) { - script = script.split(mount.guestTarget).join(mount.hostPath); - } - } - child = execa('/bin/sh', ['-c', script], { - env: {}, extendEnv: false, reject: false, detached: true, - }); - const abort = () => { if (child?.pid) process.kill(-child.pid, 'SIGTERM'); }; - options.execution.abortSignal.addEventListener('abort', abort, { once: true }); - if (options.execution.abortSignal.aborted) abort(); - try { - const result = await child; - return { - exitCode: result.signal ? 130 : result.exitCode, - category: result.signal ? 'cancelled' : 'success', signal: result.signal, - timedOut: false, rawStdoutTail: Buffer.from(result.stdout), - rawStderrTail: Buffer.from(result.stderr), - }; - } finally { - options.execution.abortSignal.removeEventListener('abort', abort); - } - }, - }; - }); - const { dependencies } = harness({ - identity: () => ({ uid: process.getuid!(), gid: process.getgid!() }), - createManager: createManager as NvxRuntimeBackendDependencies['createManager'], - createGuestConfigLayer: options => { - guestScript = options.runScript; - return { stage: async () => '', cleanup: async () => undefined } as never; - }, - }); - backend = nvxRuntimeTestHelpers.createBackendWithDependencies(config, dependencies); - }); - - afterEach(async () => { - await backend.stop(); - jest.restoreAllMocks(); - fs.rmSync(directory, { recursive: true, force: true }); - child = undefined; - }); - - function writeHarness(binary: string, version: string): void { - fs.writeFileSync(path.join(directory, 'bin', binary), `#!/bin/sh - if [ "$1" = --version ]; then phase=probe; else phase=command; fi - { id -u; id -g; printf '%s\\n' "$PWD" "$PATH" "$FIXTURE_ENV"; } >"$FIXTURE_DIRECTORY/$phase-context" - if [ "$phase" = probe ]; then - ${version} - else - printf 'command-output\\n' - exit 23 - fi - `, { mode: 0o700 }); - } - function report() { - return JSON.parse(fs.readFileSync(`${directory}/api-proxy-logs/harness-observation.json`, 'utf8')); - } - async function observe() { - prepareHarnessObservation(config); - await backend.start(directory, []); - return observeHarness(config, backend.probeHarness); - } - function assertCleaned() { - for (const mount of managerConfig.execution.mounts!.filter(m => m.tag.startsWith('harness-'))) { - expect(fs.existsSync(path.dirname(mount.hostPath))).toBe(false); - } - } - - it.each([ - ['copilot', 'copilot-cli', '1.2.3'], - ['claude', 'claude-code', '2.1.3 (Claude Code)'], - ['codex', 'codex-cli', 'codex-cli 0.89.0'], - ])('observes only selected %s before release, matching identity/env/PATH/non-login shell/cwd', async (binary, name, version) => { - config.agentCommand = `${binary} --fixture`; - writeHarness(binary, `printf '%s\\n' '${version}'`); - const observed = await observe(); - expect(observed).toMatchObject({ ...harnessContext(config), name, status: 'observed' }); - expect(report()).toEqual(observed); - expect(fs.existsSync(`${directory}/command-context`)).toBe(false); - expect(createManager).toHaveBeenCalledTimes(1); - expect(managerConfig.execution.mounts).toEqual(expect.arrayContaining([ - expect.objectContaining({ tag: 'harness-probe', mode: 'rw' }), - expect.objectContaining({ tag: 'harness-release', mode: 'ro' }), - ])); - // Adding the rendezvous must still fit the attested guest's x86 boot ABI. - expect(() => buildNvxKernelCommandLine({ - ...managerConfig.execution, - filesystem: { layers: [{ role: 'distro', uuid: '0'.repeat(36) }] }, - } as never)).not.toThrow(); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); - expect(createManager).toHaveBeenCalledTimes(1); - expect((await child!).stdout).toBe('command-output'); - expect(fs.readFileSync(`${directory}/probe-context`, 'utf8')) - .toBe(fs.readFileSync(`${directory}/command-context`, 'utf8')); - assertCleaned(); - }); - - it.each([ - ['printf "malformed-secret\\n"; printf "stderr-secret\\n" >&2', 'probe_output_invalid'], - ['exit 7', 'probe_failed'], - ['printf "%5000s" x', 'probe_output_limit'], - ])('sanitizes failed probes and preserves unconstrained legacy admission: %s', async (version, reason) => { - writeHarness('copilot', version); - await observe(); - expect(report()).toMatchObject({ status: 'unavailable', reason }); - expect(JSON.stringify(report())).not.toContain('secret'); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); - assertCleaned(); - }); - - it.each([ - ['printf "1.2.3\\n"', true, ''], - ['printf "1.0.0\\n"', false, 'harness_incompatible'], - ['printf "malformed\\n"', false, 'harness_unverified'], - ])('enforces only test-owned host requirements before releasing the real command: %s', async (version, admitted, error) => { - config.additionalEnv!.COPILOT_MODEL = 'gpt-6-sol'; - config.copilotGithubToken = 'fixture-token'; - const actualValidation = validateCopilotModel; - jest.spyOn(copilotModels, 'validateCopilotModel').mockImplementation((model, evidence) => - actualValidation(model, { - ...evidence, harnesses: [{ - scope: { provider: 'copilot', channel: 'copilot-cli' }, name: 'copilot-cli', - minimum: '1.2.0', scheme: 'semver', reason: 'Test-owned NVX fixture requirement', - provenance: { authority: 'maintained' }, - }], - })); - writeHarness('copilot', version); - if (admitted) { - await observe(); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); - } else { - await expect(observe()).rejects.toThrow(error); - expect(fs.existsSync(`${directory}/command-context`)).toBe(false); - await backend.stop(); - } - assertCleaned(); - }); - - it('bounds the guest version pipeline at ten seconds, then keeps legacy admission', async () => { - writeHarness('copilot', `trap '' TERM -printf '%s\\n' "$$" >"$FIXTURE_DIRECTORY/probe-pid" -sleep 30 -printf "1.2.3\\n"`); - const started = Date.now(); - await observe(); - expect(Date.now() - started).toBeGreaterThanOrEqual(9900); - expect(Date.now() - started).toBeLessThan(13000); - expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_timed_out' }); - const pid = Number(fs.readFileSync(`${directory}/probe-pid`, 'utf8')); - // A killed child can briefly remain as a zombie until the fixture's init reaps it. - const stat = fs.existsSync(`/proc/${pid}/stat`) ? fs.readFileSync(`/proc/${pid}/stat`, 'utf8') : ''; - expect(stat === '' || stat.split(' ')[2] === 'Z').toBe(true); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); - assertCleaned(); - }, 15000); - - it('collects an early startup exit without waiting for a persistent ready guest or releasing user code', async () => { - createManager.mockImplementation(() => ({ - execute: async () => ({ exitCode: 42, category: 'failure', signal: null }), - })); - await observe(); - expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 42 }); - expect(fs.existsSync(`${directory}/command-context`)).toBe(false); - }); - - it('cancels a guest waiting at the gate and collects its final exit and channel cleanup', async () => { - await observe(); - await backend.stop(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 130 }); - expect(fs.existsSync(`${directory}/command-context`)).toBe(false); - assertCleaned(); - }); - - it('does not execute a second guest when startup rejects', async () => { - createManager.mockImplementation(() => ({ execute: async () => { throw new Error('startup failed'); } })); - await observe(); - expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); - await backend.releaseHarness!(); - await expect(backend.exec(directory, [])).rejects.toThrow('startup failed'); - expect(createManager).toHaveBeenCalledTimes(1); - }); - - it('kills background probe helpers even when version execution succeeds', async () => { - writeHarness('copilot', `( trap '' TERM; exec sleep 30 ) >/dev/null 2>&1 & -printf '%s\\n' "$!" >"$FIXTURE_DIRECTORY/helper-pid" -printf '1.2.3\\n'`); - await observe(); - expect(report()).toMatchObject({ status: 'observed' }); - const pid = Number(fs.readFileSync(`${directory}/helper-pid`, 'utf8')); - const stat = fs.existsSync(`/proc/${pid}/stat`) ? fs.readFileSync(`/proc/${pid}/stat`, 'utf8') : ''; - expect(stat === '' || stat.split(' ')[2] === 'Z').toBe(true); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); - assertCleaned(); - }); - - it('cancels during version execution without waiting for the readiness deadline', async () => { - writeHarness('copilot', 'sleep 30'); - const observation = observe(); - while (!fs.existsSync(`${directory}/probe-context`)) await new Promise(resolve => setTimeout(resolve, 10)); - await backend.stop(); - await observation; - expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 130 }); - expect(fs.existsSync(`${directory}/command-context`)).toBe(false); - assertCleaned(); - }); - - it('treats a missing binary as unverified, never substituting another harness', async () => { - config.agentCommand = './copilot --fixture'; - await observe(); - expect(report()).toMatchObject({ status: 'unavailable', reason: 'binary_missing' }); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 127 }); - assertCleaned(); - }); - - it('resolves a relative selected executable in the command cwd', async () => { - fs.copyFileSync(`${directory}/bin/copilot`, `${directory}/workspace/copilot`); - config.agentCommand = './copilot --fixture'; - await observe(); - expect(report()).toMatchObject({ status: 'observed', resolvedBinary: './copilot' }); - await backend.releaseHarness!(); - expect(await backend.exec(directory, [])).toEqual({ exitCode: 23 }); - assertCleaned(); - }); - - it('never releases on an invalid run binding and cleans up the waiting guest', async () => { - createManager.mockImplementation(options => { - managerConfig = options; - const probe = options.execution.mounts.find((mount: { tag: string }) => mount.tag === 'harness-probe'); - fs.writeFileSync(`${probe.hostPath}/result`, 'wrong-environment\n0\n/bin/copilot\n1.2.3\n'); - return { - execute: () => new Promise(resolve => options.execution.abortSignal.addEventListener('abort', - () => resolve({ exitCode: 130 }), { once: true })), - }; - }); - await observe(); - expect(report()).toMatchObject({ status: 'unavailable', reason: 'probe_failed' }); - await expect(backend.releaseHarness!()).rejects.toThrow('not ready'); - await backend.stop(); - expect(fs.existsSync(`${directory}/command-context`)).toBe(false); - assertCleaned(); - }); - }); - afterEach(() => { Object.defineProperty(process, 'platform', { value: originalPlatform }); Object.defineProperty(process, 'arch', { value: originalArch }); diff --git a/src/nvx/runtime-backend.ts b/src/nvx/runtime-backend.ts index 665849a4c..580a960d1 100644 --- a/src/nvx/runtime-backend.ts +++ b/src/nvx/runtime-backend.ts @@ -28,9 +28,6 @@ import { import { buildNvxGuestEnvironment } from './guest-environment-builder'; import { buildNvxGuestRunScript } from './guest-entrypoint'; import { NvxGuestConfigLayer } from './guest-config-layer'; -import { harnessContext } from '../harness-observation'; -import { selectHarness, type HarnessProbe } from '../model-information-contract/harness-observation'; -import { NvxHarnessObservation } from './harness-observation'; import { planNvxLiveMounts, type NvxLiveMountPlan, @@ -136,30 +133,6 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { private abortController: AbortController | undefined; private activeExecution: Promise | undefined; private stopped = false; - private harnessObservation: NvxHarnessObservation | undefined; - private oneShotExecution: Promise<{ exitCode: number }> | undefined; - private executionSettled = false; - - readonly probeHarness: HarnessProbe = async () => { - if (this.oneShotExecution || !selectHarness(this.config.agentCommand)) { - throw new Error('NVX selected harness observation cannot be restarted'); - } - this.harnessObservation = new NvxHarnessObservation(harnessContext(this.config)); - // Start exactly one guest now, not a second version-only VM. Its command - // remains gated while the workflow publishes evidence and checks eligibility. - this.oneShotExecution = this.executeOnce(this.config.agentTimeout); - return Promise.race([ - this.harnessObservation.probe(''), - this.oneShotExecution.then(() => { - throw new Error('NVX guest exited before harness observation'); - }), - ]); - }; - - readonly releaseHarness = async (): Promise => { - if (!this.harnessObservation || this.executionSettled) return; - await this.harnessObservation.release(); - }; constructor( private readonly config: WrapperConfig, @@ -237,19 +210,6 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { _proxyLogsDir, agentTimeoutMinutes, ) => { - return this.oneShotExecution ?? this.executeOnce(agentTimeoutMinutes); - }; - - private async executeOnce(agentTimeoutMinutes?: number): Promise<{ exitCode: number }> { - try { - return await this.runExecution(agentTimeoutMinutes); - } finally { - this.executionSettled = true; - await this.harnessObservation?.cleanup(); - } - } - - private async runExecution(agentTimeoutMinutes?: number): Promise<{ exitCode: number }> { if (this.stopped) { throw new Error('NVX microVM execution aborted by shutdown'); } @@ -296,11 +256,6 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { exports, ); logNvxGuestEnvironment(environment, this.dependencies.logger); - const harnessMounts = await this.harnessObservation?.stage(identity.uid, identity.gid); - if (this.stopped) { - throw new Error('NVX microVM execution aborted by shutdown'); - } - const command = withInputPreflight(this.config.agentCommand, this.config.inputDirs); const guestConfigLayer = this.dependencies.createGuestConfigLayer({ stagingRoot: path.join(this.config.workDir ?? '/run/awf-nvx', 'nvx-guest-layer', runId), uid: identity.uid, @@ -308,7 +263,7 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { runScript: buildNvxGuestRunScript({ environment, workingDirectory: resolveNvxGuestWorkDir(this.config.containerWorkDir), - command: this.harnessObservation?.wrap(command) ?? command, + command: withInputPreflight(this.config.agentCommand, this.config.inputDirs), }), homePath: process.env.HOME, hostAliases: { @@ -354,7 +309,7 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { memoryMib: nvx.memoryMib, memoryMaxBytes: nvx.memoryMaxBytes, pidsMax: nvx.pidsMax, - mounts: harnessMounts ? [...mountPlan.mounts, ...harnessMounts] : mountPlan.mounts, + mounts: mountPlan.mounts, ...(timeoutMs === undefined ? {} : { timeoutMs }), abortSignal: abortController.signal, stdout: process.stdout, @@ -381,7 +336,7 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { this.activeExecution = undefined; this.abortController = undefined; } - } + }; async collectDiagnostics(): Promise { // NvxManager tears down all per-run diagnostics-bearing state (network @@ -397,7 +352,6 @@ export class NvxRuntimeBackend implements ExternalAgentRuntimeBackend { if (this.activeExecution) { await this.activeExecution.catch(() => undefined); } - await this.oneShotExecution?.catch(() => undefined); } } From c21f96255f1945730b46c1f323e0b15dec769b5f Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Wed, 4 Nov 2026 12:17:07 -0800 Subject: [PATCH 5/6] fix: cache supply-chain builds and avoid slow apt mirror Preserve daily security refreshes and local build-tools availability while caching PR image builds across hosted runners. Repair Grype database cache ownership before saving. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/workflows/supply-chain-scan.yml | 47 +++++- containers/build-tools/Dockerfile | 57 +------ docs/INTEGRATION-TESTS.md | 25 +++ scripts/ci/apt-mirror-dockerfiles.test.ts | 57 ++++++- scripts/ci/configure-docker-mirror.sh | 12 +- scripts/ci/docker-registry-ci.test.ts | 196 ++++++++++++++++++++-- 6 files changed, 328 insertions(+), 66 deletions(-) diff --git a/.github/workflows/supply-chain-scan.yml b/.github/workflows/supply-chain-scan.yml index 9a1ce33b6..958ac9853 100644 --- a/.github/workflows/supply-chain-scan.yml +++ b/.github/workflows/supply-chain-scan.yml @@ -156,8 +156,28 @@ jobs: df -h / - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: ${{ matrix.scan == 'pr-images' && 'true' || 'false' }} run: bash scripts/ci/configure-docker-mirror.sh + - name: Set up Docker Buildx for cached PR builds + if: matrix.scan == 'pr-images' + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + driver: docker + + - name: Expose GitHub Actions cache runtime for Buildx CLI + if: matrix.scan == 'pr-images' + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + for (const name of ['ACTIONS_RUNTIME_TOKEN', 'ACTIONS_RESULTS_URL']) { + const value = process.env[name]; + if (!value) throw new Error(`Missing ${name} for Buildx cache`); + if (name === 'ACTIONS_RUNTIME_TOKEN') core.setSecret(value); + core.exportVariable(name, value); + } + - name: Prepare pinned Grype scanner if: matrix.scan != 'licenses' run: docker pull ghcr.io/anchore/grype@sha256:fd4ab4d1042b522c896e73bdf09ab8bf384fa417df99d6dd0d6e1008c7e7c821 @@ -202,6 +222,10 @@ jobs: -e GRYPE_DB_CACHE_DIR=/cache \ ghcr.io/anchore/grype@sha256:fd4ab4d1042b522c896e73bdf09ab8bf384fa417df99d6dd0d6e1008c7e7c821 \ db update + # Docker creates root-owned DB directories; actions/cache runs as the + # runner user and must be able to traverse and archive every file. + sudo chown -R "$(id -u):$(id -g)" "$GRYPE_DB" + chmod -R u+rwX "$GRYPE_DB" - name: Save Grype vulnerability DB cache if: matrix.scan != 'licenses' @@ -263,9 +287,12 @@ jobs: GRYPE_DB: ${{ runner.temp }}/grype-db run: | python3 - <<'PYEOF' - import hashlib, os, subprocess, sys + import datetime, hashlib, os, subprocess, sys cwd = os.getcwd() db_cache = os.environ['GRYPE_DB'] + # Never import yesterday's package layers: refresh apt/apk security + # upgrades at least daily, while reusing all stages within the UTC day. + cache_day = datetime.datetime.now(datetime.timezone.utc).strftime('%Y-%m-%d') # The router build requires the SHA-256 of its OpenAPI contract. with open('containers/router/openapi.yaml', 'rb') as f: router_openapi_sha256 = hashlib.sha256(f.read()).hexdigest() @@ -306,12 +333,28 @@ jobs: tag = f'awf-pr-scan-{name}:pr' tar = f'/tmp/awf-pr-scan-{name}.tar' print(f'::group::docker build {name}', flush=True) - b = subprocess.run(['docker', 'build', *build_args, '-t', tag, context]) + cache_scope = f'supply-chain-v1-{name}-{cache_day}' + # The Docker driver shares the daemon's image store. Do not + # --pull enclave-agent's exact locally built build-tools base. + pull_args = [] if name == 'enclave-agent' else ['--pull'] + b = subprocess.run([ + 'docker', 'buildx', 'build', '--load', '--progress=plain', + *pull_args, + '--cache-from', f'type=gha,version=2,scope={cache_scope}', + '--cache-to', f'type=gha,version=2,mode=max,scope={cache_scope}', + *build_args, '-t', tag, context, + ]) print('::endgroup::', flush=True) prune_build_cache() if b.returncode != 0: print(f'::error::docker build failed for {name}', flush=True) rc = b.returncode + # Cache export can fail after --load has created the tag. + subprocess.run( + ['docker', 'image', 'rm', '--force', tag], + stdout=subprocess.DEVNULL, + stderr=subprocess.DEVNULL, + ) continue if name == 'build-tools': build_tools_ready = True diff --git a/containers/build-tools/Dockerfile b/containers/build-tools/Dockerfile index 9dbf1dad1..527bceb15 100644 --- a/containers/build-tools/Dockerfile +++ b/containers/build-tools/Dockerfile @@ -56,61 +56,14 @@ FROM ubuntu:26.04@sha256:f144425ff09be612d6d9ad965196e9cdc23dae1f42110a8a11a3e9a LABEL org.opencontainers.image.source="https://github.com/github/gh-aw-firewall" LABEL org.opencontainers.image.description="Build-tools sysroot for ARC/DinD agent containers" -# Reuse Azure mirror optimization for legacy and deb822 Ubuntu sources. -RUN if getent hosts azure.archive.ubuntu.com >/dev/null 2>&1; then \ - echo "Using Azure apt mirror (DNS resolved successfully)"; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' {} +; \ - fi; \ - else \ - echo "Azure apt mirror not reachable, using default archive.ubuntu.com"; \ - fi - # Install build essentials and system libraries. # This mirrors the packages available on GitHub-hosted runner VMs # (see actions/runner-images toolset-2204.json) minus language runtimes. +# Keep Ubuntu's standard archive/security mirrors: DNS reachability alone does +# not establish Azure mirror throughput, and apt timeouts do not bound slow transfers. RUN set -eux; \ - force_archive_mirror() { \ - echo "Falling back to archive.ubuntu.com mirror..." >&2; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list 2>/dev/null || true; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - rm -rf /var/lib/apt/lists/* && apt-get update; \ - }; \ - apt_update_retry() { \ - local i; for i in 1 2 3; do \ - rm -rf /var/lib/apt/lists/*; \ - if apt-get update > /tmp/apt-update.log 2>&1; then \ - cat /tmp/apt-update.log; \ - if ! grep -q "Failed to fetch" /tmp/apt-update.log; then return 0; fi; \ - else \ - cat /tmp/apt-update.log; \ - fi; \ - echo "apt-get update attempt $i/3 failed, retrying in $((i*10))s..." >&2; sleep $((i*10)); \ - done; \ - echo "All apt-get update retries failed, falling back to archive.ubuntu.com..." >&2; \ - force_archive_mirror; \ - }; \ - apt_install_retry() { \ - apt-get install -y --no-install-recommends "$@" && return 0; \ - echo "apt-get install failed, forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror; \ - apt-get install -y --no-install-recommends "$@"; \ - }; \ - apt_update_retry && \ - apt_install_retry \ + apt-get -o Acquire::Retries=3 -o APT::Update::Error-Mode=any update && \ + apt-get -o Acquire::Retries=3 install -y --no-install-recommends \ # Build toolchain build-essential gcc g++ make cmake autoconf automake libtool \ pkg-config binutils bison flex m4 \ @@ -131,7 +84,7 @@ RUN set -eux; \ libcap2-bin gosu gnupg \ && \ # Upgrade all packages for security patches - apt-get upgrade -y && \ + apt-get -o Acquire::Retries=3 upgrade -y && \ # Match the agent image: the inherited Pebble service manager is not used. rm -f /usr/bin/pebble && \ rm -rf /var/lib/apt/lists/* /tmp/* diff --git a/docs/INTEGRATION-TESTS.md b/docs/INTEGRATION-TESTS.md index 2bfc0351c..27d93277c 100644 --- a/docs/INTEGRATION-TESTS.md +++ b/docs/INTEGRATION-TESTS.md @@ -71,6 +71,31 @@ digests. Scan targets, vulnerability database updates, and the blocking High/Critical PR-image gate are unchanged. The setup script validates the merged daemon configuration before restart and refuses local or self-hosted runners. +For PR-image scans only, the runner opts into Docker's containerd image store +before pulling images, then uses Buildx's `docker` driver with `--load`. Each +image imports/exports a separate GitHub Actions v2 build cache (`mode=max`), +scoped by image and UTC date. Only the current day's scope is imported: the first +build each UTC day reruns package installation and security upgrades, rather than +indefinitely reusing stale apt/apk layers. Within that day, fresh hosted runners +can reuse the layers subject to normal Actions cache visibility/eviction. +Cache export failures remain build failures, not silently ignored warnings. + +The shared build-tools image remains in the local daemon until enclave-agent +finishes; that dependent build does not pull a replacement base. Intermediate +builder cache is pruned after each export, and scanned image archives/images are +removed sequentially to bound disk use. Build-tools retains Ubuntu's default +archive/security mirrors instead of selecting Azure based on DNS alone. Apt +retries transient fetch failures, treats incomplete index updates as errors, and +still upgrades every installed package. + +After Grype's DB warm-up, the job restores ownership and owner read/write/traverse +permissions to the runner user before `actions/cache/save` archives the DB. +Warm-up and permission-repair failures stop the job. The +`scripts/ci/docker-registry-ci.test.ts` and +`scripts/ci/apt-mirror-dockerfiles.test.ts` fixtures cover these cache, freshness, +mirror, scan-failure, base-image lifetime, and cleanup contracts; they do not +replace a Linux Docker/hosted-runner build. + ### NVX harness-observation limitation NVX currently launches the configured command through one atomic diff --git a/scripts/ci/apt-mirror-dockerfiles.test.ts b/scripts/ci/apt-mirror-dockerfiles.test.ts index 04ec7199e..891aa13af 100644 --- a/scripts/ci/apt-mirror-dockerfiles.test.ts +++ b/scripts/ci/apt-mirror-dockerfiles.test.ts @@ -4,7 +4,6 @@ import * as path from 'path'; import { spawnSync } from 'child_process'; const targets = [ - { image: 'build-tools', stage: 'main', index: 0 }, { image: 'agent', stage: 'one-shot-token-build', index: 0 }, { image: 'agent', stage: 'main', index: 1 }, ]; @@ -157,3 +156,59 @@ ${shell} }); }); }); + +describe('build-tools standard Ubuntu mirrors', () => { + const dockerfile = fs.readFileSync( + path.resolve(__dirname, '../../containers/build-tools/Dockerfile'), 'utf8', + ); + const installBlock = dockerfile.match(/^RUN set -eux;[\s\S]*?(?=\n\nCOPY)/m)![0] + .replace(/^RUN /, '') + .split('\n') + .filter(line => !line.trim().startsWith('#')) + .join('\n') + .replace(/\\\r?\n/g, ' '); + + it('does not replace archive/security sources based on Azure DNS reachability', () => { + expect(dockerfile).not.toContain('azure.archive.ubuntu.com'); + expect(dockerfile).not.toContain('getent hosts'); + expect(dockerfile).not.toMatch(/sed .*sources|force_archive_mirror/); + }); + + it.each(['success', 'update', 'install', 'upgrade'])( + 'keeps required packages, security upgrades, and hard failure on %s', + failure => { + const result = spawnSync('bash', ['-eu', '-c', ` +apt-get() { + printf 'apt-get %s\\n' "$*" + case " $* " in + *" $FAILURE "*) return 100 ;; + esac +} +rm() { printf 'rm %s\\n' "$*"; } +${installBlock} +`], { + encoding: 'utf8', + timeout: 5000, + env: { PATH: process.env.PATH, FAILURE: failure }, + }); + expect(result.error).toBeUndefined(); + expect(result.status).toBe(failure === 'success' ? 0 : 100); + expect(result.stdout).toContain('APT::Update::Error-Mode=any update'); + expect(result.stdout).toContain('Acquire::Retries=3'); + if (failure === 'update') { + expect(result.stdout).not.toContain(' install '); + } else { + expect(result.stdout).toContain('install -y --no-install-recommends'); + expect(result.stdout).toContain('build-essential gcc g++ make cmake'); + expect(result.stdout).toContain('ca-certificates curl wget git jq'); + expect(result.stdout).toContain('libcap2-bin gosu gnupg'); + } + if (failure === 'success') { + expect(result.stdout).toContain('upgrade -y'); + expect(result.stdout).toContain('rm -f /usr/bin/pebble'); + } else { + expect(result.stdout).not.toContain('rm -f /usr/bin/pebble'); + } + }, + ); +}); diff --git a/scripts/ci/configure-docker-mirror.sh b/scripts/ci/configure-docker-mirror.sh index b147dfea8..19fb4c8c1 100755 --- a/scripts/ci/configure-docker-mirror.sh +++ b/scripts/ci/configure-docker-mirror.sh @@ -18,9 +18,13 @@ else fi # Preserve runner settings and existing mirrors; never relax TLS verification. -jq --exit-status --arg mirror "$mirror" ' +jq --exit-status --arg mirror "$mirror" \ + --arg snapshotter "${AWF_DOCKER_CONTAINERD_SNAPSHOTTER:-false}" ' if type != "object" then error("Docker daemon config must be an object") else . end | .["registry-mirrors"] = ([$mirror] + ((.["registry-mirrors"] // []) | map(select(. != $mirror)))) + | if $snapshotter == "true" then .features["containerd-snapshotter"] = true + elif $snapshotter == "false" then . + else error("AWF_DOCKER_CONTAINERD_SNAPSHOTTER must be true or false") end ' "$config" > "$config.updated" mv "$config.updated" "$config" sudo dockerd --validate --config-file "$config" @@ -28,3 +32,9 @@ sudo install -m 0644 "$config" /etc/docker/daemon.json sudo systemctl restart docker docker info --format '{{json .RegistryConfig.Mirrors}}' | jq --exit-status --arg mirror "$mirror/" 'index($mirror) != null' +if [[ "${AWF_DOCKER_CONTAINERD_SNAPSHOTTER:-false}" == true ]]; then + # The Docker Buildx driver needs this store for external cache export while + # keeping locally loaded images available to dependent FROM instructions. + docker info --format '{{json .DriverStatus}}' | + jq --exit-status 'any(.[]; . == ["driver-type", "io.containerd.snapshotter.v1"])' +fi diff --git a/scripts/ci/docker-registry-ci.test.ts b/scripts/ci/docker-registry-ci.test.ts index e85aa52d9..2b898f693 100644 --- a/scripts/ci/docker-registry-ci.test.ts +++ b/scripts/ci/docker-registry-ci.test.ts @@ -56,15 +56,20 @@ describe('CI registry retrieval', () => { expect(buildTools).toContain('test "$(gosu nobody id -u)" = 65534'); }); - it.each(['success', 'base-build', 'agent-build', 'scan', 'save'])( - 'retains the shared PR base through dependent builds and cleans up on %s', - (failure) => { + it.each([ + ['success', '2026-11-04'], + ['success', '2026-11-05'], + ...['base-build', 'agent-build', 'cache-export', 'scan', 'save'] + .map(failure => [failure, '2026-11-04']), + ])( + 'retains the shared PR base through dependent builds and cleans up on %s (%s)', + (failure, day) => { const step = jobs('supply-chain-scan.yml')['image-scans'].steps.find( (entry) => entry.name?.startsWith('Build and scan PR container images'), )!; const python = step.run!.split("<<'PYEOF'\n")[1].split('\nPYEOF')[0]; const result = spawnSync('python3', ['-c', ` -import contextlib, io, json, os, subprocess, sys +import contextlib, datetime, io, json, os, subprocess, sys from unittest.mock import patch code = sys.stdin.read() live = set() @@ -73,17 +78,25 @@ cache = set() calls = [] saves = [] failure = sys.argv[1] +class Clock(datetime.datetime): + @classmethod + def now(cls, tz=None): + return cls.fromisoformat(sys.argv[2]).replace(tzinfo=tz) base = 'awf-pr-scan-build-tools:pr' agent = 'awf-pr-scan-enclave-agent:pr' def run(args, **kwargs): calls.append(args) rc = 0 - if args[:2] == ['docker', 'build']: + if args[:3] == ['docker', 'buildx', 'build']: tag = args[args.index('-t') + 1] if tag == agent and base not in live: raise AssertionError('base removed before enclave-agent build') cache.add(tag) - if (failure == 'base-build' and tag == base) or (failure == 'agent-build' and tag == agent): + if failure == 'cache-export': + # Buildx may load the result before the remote cache exporter fails. + live.add(tag) + if ((failure == 'base-build' and tag == base) or (failure == 'agent-build' and tag == agent) + or (failure == 'cache-export' and tag == 'awf-pr-scan-api-proxy:pr')): rc = 1 else: live.add(tag) @@ -107,7 +120,8 @@ def run(args, **kwargs): raise AssertionError('unexpected image/system prune: ' + ' '.join(args)) return subprocess.CompletedProcess(args, rc) exit_code = 0 -with patch('subprocess.run', run), patch.dict(os.environ, {'GRYPE_DB': '/tmp/mock-db'}), \\ +with patch('subprocess.run', run), patch('datetime.datetime', Clock), \\ + patch.dict(os.environ, {'GRYPE_DB': '/tmp/mock-db'}), \\ patch('os.path.exists', lambda file: file in archives), patch('os.remove', archives.remove): with contextlib.redirect_stdout(io.StringIO()): try: @@ -118,7 +132,7 @@ with patch('subprocess.run', run), patch.dict(os.environ, {'GRYPE_DB': '/tmp/moc exit_code = error.returncode print(json.dumps({'live': sorted(live), 'archives': sorted(archives), 'cache': sorted(cache), 'saves': saves, 'calls': calls, 'exit': exit_code})) -`, failure], { cwd: root, input: python, encoding: 'utf8' }); +`, failure, day], { cwd: root, input: python, encoding: 'utf8' }); expect(result.stderr).toBe(''); expect(result.status).toBe(0); const trace = JSON.parse(result.stdout) as { @@ -140,13 +154,31 @@ print(json.dumps({'live': sorted(live), 'archives': sorted(archives), 'cache': s } expect(trace.exit).toBe(failure === 'success' ? 0 : failure === 'scan' ? 2 : 1); const agentBuild = trace.calls.find((args) => - args[1] === 'build' && args.includes('awf-pr-scan-enclave-agent:pr')); + args[1] === 'buildx' && args.includes('awf-pr-scan-enclave-agent:pr')); if (failure === 'base-build' || failure === 'save') { expect(agentBuild).toBeUndefined(); } else { expect(agentBuild).toBeDefined(); } const scans = trace.calls.filter((args) => args[1] === 'run'); + const builds = trace.calls.filter((args) => args[1] === 'buildx'); + expect(builds.length).toBeGreaterThan(0); + const scopes = new Set(); + for (const args of builds) { + const tag = args[args.indexOf('-t') + 1]; + const name = tag.slice('awf-pr-scan-'.length, -':pr'.length); + const scope = `supply-chain-v1-${name}-${day}`; + scopes.add(scope); + expect(args).toContain('--load'); + expect(args[args.indexOf('--cache-from') + 1]).toBe(`type=gha,version=2,scope=${scope}`); + expect(args[args.indexOf('--cache-to') + 1]).toBe(`type=gha,version=2,mode=max,scope=${scope}`); + expect(args.includes('--pull')).toBe(name !== 'enclave-agent'); + expect(args.join(' ')).not.toMatch(/ignore-error|no-cache/); + } + expect(scopes.size).toBe(builds.length); + if (agentBuild) { + expect(agentBuild).toContain('BUILD_TOOLS_IMAGE=awf-pr-scan-build-tools:pr'); + } for (const args of scans) { expect(args).toContain(grype); expect(args.slice(args.indexOf('--fail-on'), args.indexOf('--fail-on') + 2)) @@ -155,6 +187,121 @@ print(json.dumps({'live': sorted(live), 'archives': sorted(archives), 'cache': s if (failure === 'success' || failure === 'scan') { expect(scans).toHaveLength(9); } + if (failure === 'cache-export') { + expect(scans).toHaveLength(8); + expect(scans.flat()).not.toContain('docker-archive:/tmp/awf-pr-scan-api-proxy.tar'); + } + }, + ); + + it('sets up an external-cache-capable Docker driver before pulling scanners', () => { + const workflow = jobs('supply-chain-scan.yml'); + const steps = workflow['image-scans'].steps; + const mirror = steps.findIndex(step => step.name === 'Configure Docker Hub cache'); + expect(steps[mirror].env?.AWF_DOCKER_CONTAINERD_SNAPSHOTTER) + .toBe("${{ matrix.scan == 'pr-images' && 'true' || 'false' }}"); + const setup = steps.findIndex(step => step.name === 'Set up Docker Buildx for cached PR builds'); + expect(setup).toBeGreaterThan(mirror); + expect(setup).toBeLessThan(steps.findIndex(step => step.run?.startsWith('docker pull'))); + expect(steps[setup].uses) + .toBe('docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069'); + expect(steps[setup].with?.driver).toBe('docker'); + expect(steps[setup].if).toBe("matrix.scan == 'pr-images'"); + expect(steps[setup]['continue-on-error']).toBeUndefined(); + expect(workflow.compile.steps.some(step => step.env?.AWF_DOCKER_CONTAINERD_SNAPSHOTTER)) + .toBe(false); + }); + + it.each(['complete', 'missing-token', 'missing-url'])( + 'masks the runtime token and fails closed on missing Buildx cache credentials (%s)', + state => { + const step = jobs('supply-chain-scan.yml')['image-scans'].steps.find( + entry => entry.name === 'Expose GitHub Actions cache runtime for Buildx CLI', + )!; + expect(step.if).toBe("matrix.scan == 'pr-images'"); + expect(step.uses).toBe('actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'); + const result = spawnSync(process.execPath, ['-e', ` +const calls = []; +const core = { + setSecret: value => calls.push(['mask', value]), + exportVariable: (name, value) => calls.push(['export', name, value]), +}; +const env = { + ...(process.argv[1] === 'missing-token' ? {} : { ACTIONS_RUNTIME_TOKEN: 'fixture-token' }), + ...(process.argv[1] === 'missing-url' ? {} : { ACTIONS_RESULTS_URL: 'https://cache.example/' }), +}; +try { + new Function('core', 'process', ${JSON.stringify(step.with?.script)})(core, { env }); +} catch (error) { + process.exitCode = 1; +} +console.log(JSON.stringify(calls)); +`, state], { encoding: 'utf8' }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(state === 'complete' ? 0 : 1); + const calls = JSON.parse(result.stdout) as string[][]; + if (state !== 'missing-token') { + expect(calls.slice(0, 2)).toEqual([ + ['mask', 'fixture-token'], + ['export', 'ACTIONS_RUNTIME_TOKEN', 'fixture-token'], + ]); + } + if (state === 'complete') { + expect(calls).toHaveLength(3); + expect(calls[2]).toEqual(['export', 'ACTIONS_RESULTS_URL', 'https://cache.example/']); + } + }, + ); + + it.each(['success', 'warm-failure', 'chown-failure'])( + 'repairs Grype cache ownership and traversal before saving (%s)', + failure => { + const steps = jobs('supply-chain-scan.yml')['image-scans'].steps; + const warm = steps.findIndex(step => step.name === 'Warm Grype vulnerability DB'); + expect(steps[warm + 1].name).toBe('Save Grype vulnerability DB cache'); + const temp = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-grype-cache-')); + const db = path.join(temp, 'db'); + try { + fs.writeFileSync(path.join(temp, 'docker'), `#!/usr/bin/env bash +set -euo pipefail +echo docker >> "$TRACE" +[[ "$FAILURE" != warm-failure ]] || exit 100 +mkdir -p "$GRYPE_DB/6" +echo fixture-db > "$GRYPE_DB/6/vulnerability.db" +chmod 0500 "$GRYPE_DB/6" +chmod 0400 "$GRYPE_DB/6/vulnerability.db" +`, { mode: 0o755 }); + fs.writeFileSync(path.join(temp, 'sudo'), `#!/usr/bin/env bash +set -euo pipefail +echo "$*" >> "$TRACE" +[[ "$1" == chown && "$2" == -R && "$3" == "$(id -u):$(id -g)" && "$4" == "$GRYPE_DB" ]] +[[ "$FAILURE" != chown-failure ]] || exit 101 +`, { mode: 0o755 }); + const result = spawnSync('bash', ['-e', '-c', steps[warm].run!], { + encoding: 'utf8', + env: { + ...process.env, + PATH: `${temp}${path.delimiter}${process.env.PATH}`, + GRYPE_DB: db, + TRACE: path.join(temp, 'trace'), + FAILURE: failure, + }, + }); + expect(result.stderr).toBe(''); + expect(result.status).toBe(failure === 'success' ? 0 : failure === 'warm-failure' ? 100 : 101); + const trace = fs.readFileSync(path.join(temp, 'trace'), 'utf8').trim().split('\n'); + expect(trace).toHaveLength(failure === 'warm-failure' ? 1 : 2); + if (failure === 'success') { + expect(trace[1]).toBe(`chown -R ${process.getuid!()}:${process.getgid!()} ${db}`); + expect(fs.statSync(path.join(db, '6')).mode & 0o700).toBe(0o700); + expect(fs.statSync(path.join(db, '6/vulnerability.db')).mode & 0o600).toBe(0o600); + const archive = spawnSync('tar', ['-cf', path.join(temp, 'cache.tar'), '-C', db, '.']); + expect(archive.status).toBe(0); + } + } finally { + if (fs.existsSync(path.join(db, '6'))) fs.chmodSync(path.join(db, '6'), 0o700); + fs.rmSync(temp, { recursive: true, force: true }); + } }, ); @@ -376,7 +523,11 @@ esac fs.writeFileSync(path.join(temp, 'docker'), `#!/usr/bin/env bash set -euo pipefail echo docker >> "$TRACE" -printf '%s\\n' "\${DOCKER_MIRRORS:-[\\"https://mirror.gcr.io/\\"]}" +if [[ "$*" == *DriverStatus* ]]; then + printf '%s\\n' "\${DRIVER_STATUS:-[[\\"driver-type\\",\\"io.containerd.snapshotter.v1\\"]]}" +else + printf '%s\\n' "\${DOCKER_MIRRORS:-[\\"https://mirror.gcr.io/\\"]}" +fi `, { mode: 0o755 }); }); @@ -423,6 +574,31 @@ printf '%s\\n' "\${DOCKER_MIRRORS:-[\\"https://mirror.gcr.io/\\"]}" }); }); + it('opts into the containerd store without losing other daemon features', () => { + fs.writeFileSync(path.join(temp, 'daemon.json'), JSON.stringify({ + features: { other: true, 'containerd-snapshotter': false }, + })); + expect(run({ AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' }).status).toBe(0); + expect(JSON.parse(fs.readFileSync(path.join(temp, 'daemon.json'), 'utf8'))).toEqual({ + features: { other: true, 'containerd-snapshotter': true }, + 'registry-mirrors': ['https://mirror.gcr.io'], + }); + expect(fs.readFileSync(path.join(temp, 'trace'), 'utf8').trim().split('\n').slice(-2)) + .toEqual(['docker', 'docker']); + }); + + it('does not silently proceed with an unsupported external cache store', () => { + expect(run({ + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true', + DRIVER_STATUS: '[["Backing Filesystem","extfs"]]', + }).status).not.toBe(0); + }); + + it('rejects invalid snapshotter settings before restarting Docker', () => { + expect(run({ AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'yes' }).status).not.toBe(0); + expect(fs.readFileSync(path.join(temp, 'trace'), 'utf8')).not.toContain('systemctl'); + }); + it.each(['not-json', '[]', '{"registry-mirrors":42}'])('rejects invalid config %s without restarting', (config) => { fs.writeFileSync(path.join(temp, 'daemon.json'), config); expect(run().status).not.toBe(0); From f71888c37580275ad1403dcff00971d94c45f884 Mon Sep 17 00:00:00 2001 From: Landon Cox Date: Wed, 4 Nov 2026 12:39:09 -0800 Subject: [PATCH 6/6] fix: cache chroot integration images and use standard apt mirrors Reuse daily GitHub Actions build layers across hosted runners while retaining exact local test images, security refreshes, failure reporting and cleanup. Stop selecting Azure mirrors based only on DNS in the agent image. Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../actions/build-chroot-images/action.yml | 34 +++ .github/workflows/test-chroot.yml | 38 ++- containers/agent/Dockerfile | 105 +------- docs/INTEGRATION-TESTS.md | 20 ++ scripts/ci/apt-mirror-dockerfiles.test.ts | 245 +++++------------- scripts/ci/build-chroot-images.sh | 46 ++++ scripts/ci/chroot-image-cache.test.ts | 169 ++++++++++++ scripts/ci/docker-registry-ci.test.ts | 3 +- 8 files changed, 365 insertions(+), 295 deletions(-) create mode 100644 .github/actions/build-chroot-images/action.yml create mode 100644 scripts/ci/build-chroot-images.sh create mode 100644 scripts/ci/chroot-image-cache.test.ts diff --git a/.github/actions/build-chroot-images/action.yml b/.github/actions/build-chroot-images/action.yml new file mode 100644 index 000000000..e86c6239f --- /dev/null +++ b/.github/actions/build-chroot-images/action.yml @@ -0,0 +1,34 @@ +name: Build cached chroot images +description: Load checkout-built integration images using daily GitHub Actions layer caches +inputs: + browser: + description: Include the API proxy image used by browser tests + default: 'false' + runner-variant: + description: Distinguish the browser runner matrix caches + default: ubuntu-latest +runs: + using: composite + steps: + - name: Set up Docker Buildx + uses: docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069 # v4.4.1 + with: + driver: docker + + - name: Expose GitHub Actions cache runtime for Buildx CLI + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 # v9.0.0 + with: + script: | + for (const name of ['ACTIONS_RUNTIME_TOKEN', 'ACTIONS_RESULTS_URL']) { + const value = process.env[name]; + if (!value) throw new Error(`Missing ${name} for Buildx cache`); + if (name === 'ACTIONS_RUNTIME_TOKEN') core.setSecret(value); + core.exportVariable(name, value); + } + + - name: Build and verify local integration images + shell: bash + env: + CHROOT_BROWSER: ${{ inputs.browser }} + CHROOT_CACHE_VARIANT: ${{ github.job }}-${{ inputs.runner-variant }}-${{ runner.arch }} + run: bash scripts/ci/build-chroot-images.sh diff --git a/.github/workflows/test-chroot.yml b/.github/workflows/test-chroot.yml index 32551fc49..4eef735b5 100644 --- a/.github/workflows/test-chroot.yml +++ b/.github/workflows/test-chroot.yml @@ -26,6 +26,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -41,10 +43,10 @@ jobs: run: /opt/google/chrome/chrome --version - name: Build local containers - run: | - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ - docker build -t ghcr.io/github/gh-aw-firewall/api-proxy:latest containers/api-proxy/ + uses: ./.github/actions/build-chroot-images + with: + browser: 'true' + runner-variant: ${{ matrix.os }} - name: Run real chroot browser launch run: npm run test:integration -- --testPathPatterns=chroot-browser --verbose @@ -63,6 +65,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -136,10 +140,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | @@ -181,6 +182,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -283,10 +286,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | @@ -327,6 +327,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -360,10 +362,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | @@ -404,6 +403,8 @@ jobs: uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v4 - name: Configure Docker Hub cache + env: + AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' run: bash scripts/ci/configure-docker-mirror.sh - name: Setup Node.js @@ -419,10 +420,7 @@ jobs: run: npm run build - name: Build local containers - run: | - echo "=== Building local containers ===" - docker build -t ghcr.io/github/gh-aw-firewall/squid:latest containers/squid/ - docker build -t ghcr.io/github/gh-aw-firewall/agent:latest containers/agent/ + uses: ./.github/actions/build-chroot-images - name: Pre-test cleanup run: | diff --git a/containers/agent/Dockerfile b/containers/agent/Dockerfile index a04381e49..b7b580468 100644 --- a/containers/agent/Dockerfile +++ b/containers/agent/Dockerfile @@ -41,7 +41,7 @@ FROM ubuntu:22.04@sha256:0a9887931b0e38af2e3487ed39e29436b0535c4f3f52e57745baaf7 RUN set -eux; \ BROWSER_PKGS="libasound2 libatk-bridge2.0-0 libatk1.0-0 libatspi2.0-0 libcairo2 libcups2 libdbus-1-3 libdrm2 libexpat1 libgbm1 libglib2.0-0 libnspr4 libnss3 libpango-1.0-0 libpangocairo-1.0-0 libudev1 libx11-6 libxcb1 libxcomposite1 libxdamage1 libxext6 libxfixes3 libxkbcommon0 libxrandr2 libxrender1 libxshmfence1 fonts-liberation"; \ - apt-get -o Acquire::Retries=3 update && \ + apt-get -o Acquire::Retries=3 -o APT::Update::Error-Mode=any update && \ apt-get -o Acquire::Retries=3 install -y --no-install-recommends $BROWSER_PKGS && \ apt-get -o Acquire::Retries=3 upgrade -y --no-install-recommends && \ # Include dependencies already in the base image (e.g. libpcre3), not just @@ -65,42 +65,12 @@ RUN set -eux; \ FROM ${BASE_IMAGE} AS one-shot-token-build COPY one-shot-token/one-shot-token.c /tmp/one-shot-token.c +# Use the base image's standard archive/security mirrors, not DNS-only Azure selection. RUN set -eux; \ - force_archive_mirror() { \ - echo "Falling back to archive.ubuntu.com mirror..." >&2; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list 2>/dev/null || true; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - rm -rf /var/lib/apt/lists/* && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update; \ - }; \ - apt_install_retry() { \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - install -y --no-install-recommends "$@" && return 0; \ - echo "apt-get install failed (likely mirror fetch timeout), forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror; \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - install -y --no-install-recommends "$@"; \ - }; \ - if getent hosts azure.archive.ubuntu.com >/dev/null 2>&1; then \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' {} +; \ - fi; \ - fi && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update && \ - apt_install_retry gcc libc6-dev binutils && \ + apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + -o APT::Update::Error-Mode=any update && \ + apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + install -y --no-install-recommends gcc libc6-dev binutils && \ gcc -shared -fPIC -fvisibility=hidden -O2 -Wall -s \ -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=0 \ -o /tmp/one-shot-token.so /tmp/one-shot-token.c -ldl -lpthread && \ @@ -110,85 +80,34 @@ FROM ${BASE_IMAGE} COPY --from=browser-libs /usr/local/share/awf/ /usr/local/share/awf/ -# Optionally switch to Azure apt mirror for faster package fetches in CI -# Only rewrite if azure.archive.ubuntu.com is resolvable (BuildKit DNS can fail) -# Falls back to default archive.ubuntu.com which is universally reachable -RUN if getent hosts azure.archive.ubuntu.com >/dev/null 2>&1; then \ - echo "Using Azure apt mirror (DNS resolved successfully)"; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' /etc/apt/sources.list; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i 's|http://archive.ubuntu.com|http://azure.archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i 's|http://security.ubuntu.com|http://azure.archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - else \ - echo "Azure apt mirror not reachable, using default archive.ubuntu.com"; \ - fi - # Install required and runner-parity packages, apply security upgrades, then install # Node.js 22.23.2 and npm 12.2.1. Keeping apt work in one layer avoids repeatedly # downloading package indexes during cold CI builds. # Note: Some packages may already exist in runner-like base images, apt handles this gracefully -# apt_update_retry: retries up to 3 times with backoff; if all fail, reverts to archive.ubuntu.com +# Retain the base image's mirrors; apt retries fetch failures and rejects partial indexes. RUN set -eux; \ - force_archive_mirror() { \ - echo "Falling back to archive.ubuntu.com mirror..." >&2; \ - if [ -f /etc/apt/sources.list ]; then \ - sed -i 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list; \ - sed -i 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' /etc/apt/sources.list 2>/dev/null || true; \ - fi; \ - if [ -d /etc/apt/sources.list.d ]; then \ - find /etc/apt/sources.list.d -name '*.sources' -exec \ - sed -i -e 's|http://azure.archive.ubuntu.com|http://archive.ubuntu.com|g' \ - -e 's|http://security.ubuntu.com|http://archive.ubuntu.com|g' {} + 2>/dev/null || true; \ - fi; \ - rm -rf /var/lib/apt/lists/* && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 update; \ - }; \ apt_update_retry() { \ - local i; for i in 1 2 3; do \ - rm -rf /var/lib/apt/lists/*; \ - if apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - update > /tmp/apt-update.log 2>&1; then \ - cat /tmp/apt-update.log; \ - if ! grep -q "Failed to fetch" /tmp/apt-update.log; then return 0; fi; \ - else \ - cat /tmp/apt-update.log; \ - fi; \ - echo "apt-get update attempt $i/3 failed or had fetch failures, retrying in $((i*10))s..." >&2; sleep $((i*10)); \ - done; \ - echo "All apt-get update retries failed, falling back to archive.ubuntu.com..." >&2; \ - force_archive_mirror; \ + apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ + -o APT::Update::Error-Mode=any update; \ }; \ apt_install_retry() { \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - install -y --no-install-recommends "$@" && return 0; \ - echo "apt-get install failed (likely mirror fetch timeout), forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror; \ apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ install -y --no-install-recommends "$@"; \ }; \ apt_upgrade_retry() { \ apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 \ - upgrade -y && return 0; \ - echo "apt-get upgrade failed (likely mirror fetch timeout), forcing archive.ubuntu.com and retrying..." >&2; \ - force_archive_mirror && \ - apt-get -o Acquire::Retries=3 -o Acquire::http::Timeout=30 -o Acquire::https::Timeout=30 upgrade -y; \ + upgrade -y; \ }; \ PKGS="iptables curl ca-certificates git gnupg dnsutils net-tools netcat-openbsd libcap2-bin libgdiplus libev-dev libssl-dev php-intl php-gd python3"; \ apt_update_retry && \ apt_install_retry $PKGS && \ # Native packages serve non-chroot execution. Chroot execution uses the # independent Ubuntu 22.04 payload above, never these newer image libraries. - BROWSER_PKGS="$(cat /usr/local/share/awf/browser-packages.txt)"; \ + BROWSER_PKGS="$(cat /usr/local/share/awf/browser-packages.txt)" && \ # Ubuntu 24.04 renamed several of these to time_t-64 variants (e.g. libasound2t64), # and the old names became ambiguous virtual packages. Prefer the t64 package when # the base image provides one, otherwise keep the 22.04 name. - BROWSER_ACTUAL_PKGS=""; \ + BROWSER_ACTUAL_PKGS="" && \ for pkg in $BROWSER_PKGS; do \ if apt-cache show "${pkg}t64" >/dev/null 2>&1; then \ BROWSER_ACTUAL_PKGS="$BROWSER_ACTUAL_PKGS ${pkg}t64"; \ diff --git a/docs/INTEGRATION-TESTS.md b/docs/INTEGRATION-TESTS.md index 27d93277c..fa78fde1d 100644 --- a/docs/INTEGRATION-TESTS.md +++ b/docs/INTEGRATION-TESTS.md @@ -96,6 +96,26 @@ Warm-up and permission-repair failures stop the job. The mirror, scan-failure, base-image lifetime, and cleanup contracts; they do not replace a Linux Docker/hosted-runner build. +All five chroot job definitions (including both browser runner variants) use +`.github/actions/build-chroot-images` to build the checkout's Squid and agent, +plus API proxy for browser tests, with the exact existing `:latest` local tags. +The composite action uses the same Docker-driver/containerd-store and daily +GitHub Actions v2 cache policy. Its scopes are separate by image, job, runner +variant, and architecture to avoid concurrent matrix writers colliding; no +previous-day scopes are imported. It verifies loaded images and prunes only +intermediate build cache after export, keeping the images needed by tests. +Build, cache export, inspection, and pruning errors fail preparation rather than +running tests against incomplete images. Existing suites, runner matrix, cleanup, +network isolation, and job/test timeout limits are unchanged. + +The agent's token-compiler and runtime stages now retain their base image's apt +mirrors rather than selecting Azure via DNS; all Ubuntu stages reject partial +index updates, retain fetch retries, and preserve required packages and runtime +security upgrades. The oldest-runner browser payload and native t64 dependency +resolution are unchanged. `scripts/ci/chroot-image-cache.test.ts` exercises the +shared builder with Docker test doubles; actual Linux chroot execution remains +the responsibility of the integration jobs. Grype is not used by these jobs. + ### NVX harness-observation limitation NVX currently launches the configured command through one atomic diff --git a/scripts/ci/apt-mirror-dockerfiles.test.ts b/scripts/ci/apt-mirror-dockerfiles.test.ts index 891aa13af..47b07dc76 100644 --- a/scripts/ci/apt-mirror-dockerfiles.test.ts +++ b/scripts/ci/apt-mirror-dockerfiles.test.ts @@ -1,182 +1,73 @@ import * as fs from 'fs'; -import * as os from 'os'; import * as path from 'path'; import { spawnSync } from 'child_process'; -const targets = [ - { image: 'agent', stage: 'one-shot-token-build', index: 0 }, - { image: 'agent', stage: 'main', index: 1 }, -]; - -const legacySources = [ - 'deb http://archive.ubuntu.com/ubuntu resolute main universe', - 'deb http://security.ubuntu.com/ubuntu resolute-security main universe', - 'deb https://download.docker.com/linux/ubuntu resolute stable', - '', -].join('\n'); - -const deb822Sources = [ - 'Types: deb', - 'URIs: http://archive.ubuntu.com/ubuntu/', - 'Suites: resolute resolute-updates resolute-backports', - 'Components: main universe', - 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg', - '', - 'Types: deb', - 'URIs: http://security.ubuntu.com/ubuntu/', - 'Suites: resolute-security', - 'Components: main universe', - 'Signed-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg', - '', -].join('\n'); +const read = (image: string) => fs.readFileSync( + path.resolve(__dirname, `../../containers/${image}/Dockerfile`), 'utf8', +); +const instructions = (source: string) => source + .replace(/^[ \t]*#.*\r?\n/gm, '') + .replace(/\\\r?\n/g, ' ') + .split('\n'); -const thirdPartySources = 'Types: deb\nURIs: https://example.com/packages\nSuites: stable\n'; +describe.each(['build-tools', 'agent'])('%s standard Ubuntu mirrors', image => { + const dockerfile = read(image); -describe.each(targets)('$image Dockerfile ($stage) apt mirrors', ({ image, index }) => { - const dockerfile = fs.readFileSync( - path.resolve(__dirname, `../../containers/${image}/Dockerfile`), 'utf8', - ); - const selectionBlocks = dockerfile.match( - /if getent hosts azure\.archive\.ubuntu\.com[\s\S]*?^ fi/gm, - ) ?? []; - const fallbackBlocks = dockerfile.match( - /force_archive_mirror\(\) \{[\s\S]*?^ \};/gm, - ) ?? []; - - it('covers every mirror selection and fallback block', () => { - const expected = targets.filter(target => target.image === image).length; - expect(selectionBlocks).toHaveLength(expected); - expect(fallbackBlocks).toHaveLength(expected); + it('retains the base image archive/security sources instead of DNS-only Azure selection', () => { + expect(dockerfile).not.toContain('azure.archive.ubuntu.com'); + expect(dockerfile).not.toContain('getent hosts'); + expect(dockerfile).not.toMatch(/sed .*sources|force_archive_mirror/); }); - describe.each(['legacy', 'deb822', 'mixed', 'missing'])('%s sources', layout => { - let directory: string; - let originals: Map; - - beforeEach(() => { - directory = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-apt-mirror-')); - originals = new Map(); - if (layout === 'legacy' || layout === 'mixed') { - originals.set('sources.list', legacySources); - } - if (layout === 'deb822' || layout === 'mixed') { - originals.set('sources.list.d/ubuntu.sources', deb822Sources); - originals.set('sources.list.d/third-party.sources', thirdPartySources); - } - for (const [file, contents] of originals) { - const destination = path.join(directory, 'apt', file); - fs.mkdirSync(path.dirname(destination), { recursive: true }); - fs.writeFileSync(destination, contents); - } - }); - - afterEach(() => { - fs.rmSync(directory, { recursive: true, force: true }); - }); - - const run = (script: string, dnsStatus = 0, updateStatus = 0) => { - let shell = script - .replace(/\\\r?\n/g, ' ') - .replace(/\/etc\/apt/g, '"$FIXTURE_APT"') - .replace(/\/var\/lib\/apt\/lists/g, '"$FIXTURE_APT/lists"'); - // Docker uses GNU sed; adapt only its in-place flag for local macOS runs. - if (process.platform === 'darwin') { - shell = shell.replace(/sed -i /g, "sed -i '' "); - } - return spawnSync('bash', ['-eu', '-c', ` -getent() { return "$DNS_STATUS"; } -rm() { printf 'rm %s\\n' "$*"; } -apt-get() { printf 'apt-get %s\\n' "$*"; return "$UPDATE_STATUS"; } -${shell} -`], { - encoding: 'utf8', - timeout: 5000, - env: { - PATH: process.env.PATH, - FIXTURE_APT: path.join(directory, 'apt'), - DNS_STATUS: String(dnsStatus), - UPDATE_STATUS: String(updateStatus), - }, - }); - }; - - const expectSources = (mirror?: 'azure' | 'archive') => { - for (const [file, original] of originals) { - const expected = mirror - ? original.replace( - /http:\/\/(?:archive|security)\.ubuntu\.com/g, - `http://${mirror === 'azure' ? 'azure.archive' : 'archive'}.ubuntu.com`, - ) - : original; - expect(fs.readFileSync(path.join(directory, 'apt', file), 'utf8')).toBe(expected); - } - }; - - it('selects Azure for archive and security sources when DNS resolves', () => { - const result = run(selectionBlocks[index]); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expectSources('azure'); - }); - - it('leaves sources unchanged when Azure DNS fails', () => { - const result = run(selectionBlocks[index], 1); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expectSources(); - }); - - it('falls back from Azure to archive and refreshes package indexes', () => { - const selected = run(selectionBlocks[index]); - expect(selected.status).toBe(0); - expectSources('azure'); - const result = run(`${fallbackBlocks[index]}\nforce_archive_mirror`); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expect(result.stderr).toContain('Falling back to archive.ubuntu.com mirror'); - expect(result.stdout).toContain(`rm -rf ${path.join(directory, 'apt/lists')}/*`); - expect(result.stdout).toMatch(/apt-get .*update/); - expectSources('archive'); - }); - - it('normalizes default security sources during fallback', () => { - const result = run(`${fallbackBlocks[index]}\nforce_archive_mirror`); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(0); - expectSources('archive'); - }); - - it('propagates apt update failures after switching back to archive', () => { - const selected = run(selectionBlocks[index]); - expect(selected.status).toBe(0); - const result = run(`${fallbackBlocks[index]}\nforce_archive_mirror`, 0, 100); - expect(result.error).toBeUndefined(); - expect(result.status).toBe(100); - expectSources('archive'); - }); + it('retries fetches and rejects incomplete package indexes in every Ubuntu stage', () => { + const updates = dockerfile.match(/apt-get [^;]*?\bupdate/g) ?? []; + expect(updates).toHaveLength(image === 'agent' ? 3 : 1); + for (const command of updates) { + expect(command).toContain('Acquire::Retries=3'); + expect(command).toContain('APT::Update::Error-Mode=any'); + } }); }); -describe('build-tools standard Ubuntu mirrors', () => { - const dockerfile = fs.readFileSync( - path.resolve(__dirname, '../../containers/build-tools/Dockerfile'), 'utf8', - ); - const installBlock = dockerfile.match(/^RUN set -eux;[\s\S]*?(?=\n\nCOPY)/m)![0] - .replace(/^RUN /, '') - .split('\n') - .filter(line => !line.trim().startsWith('#')) - .join('\n') - .replace(/\\\r?\n/g, ' '); - - it('does not replace archive/security sources based on Azure DNS reachability', () => { - expect(dockerfile).not.toContain('azure.archive.ubuntu.com'); - expect(dockerfile).not.toContain('getent hosts'); - expect(dockerfile).not.toMatch(/sed .*sources|force_archive_mirror/); - }); +const agentInstructions = instructions(read('agent')); +const cases = [ + { + stage: 'build-tools', + instruction: instructions(read('build-tools')).find(line => line.includes('libcap2-bin gosu gnupg'))!, + stop: 'rm -f /usr/bin/pebble', + packages: ['build-essential gcc g++ make cmake', 'ca-certificates curl wget git jq', 'libcap2-bin gosu gnupg'], + upgrade: true, + }, + { + stage: 'agent token compiler', + instruction: agentInstructions.find(line => line.includes('gcc -shared'))!, + stop: 'gcc -shared', + packages: ['gcc libc6-dev binutils'], + upgrade: false, + }, + { + stage: 'agent browser libraries', + instruction: agentInstructions.find(line => line.startsWith('RUN ') && line.includes('BROWSER_PKGS="'))!, + stop: 'apt-cache depends', + packages: ['libasound2', 'libudev1', 'fonts-liberation'], + upgrade: true, + }, + { + stage: 'agent runtime', + instruction: agentInstructions.find(line => line.includes('NPM_TGZ_URL='))!, + stop: 'rm -f /usr/bin/pebble', + packages: ['iptables curl ca-certificates git gnupg', 'libcap2-bin libgdiplus libev-dev libssl-dev php-intl php-gd python3'], + upgrade: true, + }, +]; - it.each(['success', 'update', 'install', 'upgrade'])( - 'keeps required packages, security upgrades, and hard failure on %s', +describe.each(cases)('$stage apt failure handling', ({ instruction, stop, packages, upgrade }) => { + it.each(['success', 'update', 'install', ...(upgrade ? ['upgrade'] : [])])( + 'preserves required packages and stops on %s failure', failure => { + expect(instruction).toBeDefined(); + expect(instruction.indexOf(stop)).toBeGreaterThan(0); + const script = instruction.slice('RUN '.length, instruction.indexOf(stop)); const result = spawnSync('bash', ['-eu', '-c', ` apt-get() { printf 'apt-get %s\\n' "$*" @@ -184,8 +75,9 @@ apt-get() { *" $FAILURE "*) return 100 ;; esac } -rm() { printf 'rm %s\\n' "$*"; } -${installBlock} +cat() { printf 'libasound2 libudev1\\n'; } +apt-cache() { return 100; } +${script} printf 'apt-complete\\n' `], { encoding: 'utf8', timeout: 5000, @@ -194,20 +86,11 @@ ${installBlock} expect(result.error).toBeUndefined(); expect(result.status).toBe(failure === 'success' ? 0 : 100); expect(result.stdout).toContain('APT::Update::Error-Mode=any update'); - expect(result.stdout).toContain('Acquire::Retries=3'); - if (failure === 'update') { - expect(result.stdout).not.toContain(' install '); - } else { - expect(result.stdout).toContain('install -y --no-install-recommends'); - expect(result.stdout).toContain('build-essential gcc g++ make cmake'); - expect(result.stdout).toContain('ca-certificates curl wget git jq'); - expect(result.stdout).toContain('libcap2-bin gosu gnupg'); - } + expect(result.stdout.includes('apt-complete')).toBe(failure === 'success'); if (failure === 'success') { - expect(result.stdout).toContain('upgrade -y'); - expect(result.stdout).toContain('rm -f /usr/bin/pebble'); - } else { - expect(result.stdout).not.toContain('rm -f /usr/bin/pebble'); + expect(result.stdout).toContain('install -y --no-install-recommends'); + for (const required of packages) expect(result.stdout).toContain(required); + expect(result.stdout.includes('upgrade -y')).toBe(upgrade); } }, ); diff --git a/scripts/ci/build-chroot-images.sh b/scripts/ci/build-chroot-images.sh new file mode 100644 index 000000000..7f1b092dd --- /dev/null +++ b/scripts/ci/build-chroot-images.sh @@ -0,0 +1,46 @@ +#!/usr/bin/env bash +set -euo pipefail + +if [[ "${GITHUB_ACTIONS:-}" != true || "${RUNNER_ENVIRONMENT:-}" != github-hosted || "${RUNNER_OS:-}" != Linux ]]; then + echo "Cached chroot image builds require a GitHub-hosted Linux Actions runner" >&2 + exit 1 +fi + +: "${ACTIONS_RUNTIME_TOKEN:?Buildx cache runtime token is required}" +: "${ACTIONS_RESULTS_URL:?Buildx cache results URL is required}" +: "${CHROOT_CACHE_VARIANT:?Chroot cache variant is required}" +if [[ ! "$CHROOT_CACHE_VARIANT" =~ ^[a-zA-Z0-9._-]+$ ]]; then + echo "Invalid chroot cache variant" >&2 + exit 1 +fi +case "${CHROOT_BROWSER:-false}" in + true) images=(squid agent api-proxy) ;; + false) images=(squid agent) ;; + *) echo "CHROOT_BROWSER must be true or false" >&2; exit 1 ;; +esac + +# Import only today's package layers; never freeze apt/apk security updates. +cache_day=$(date -u +%F) +for image in "${images[@]}"; do + tag="ghcr.io/github/gh-aw-firewall/${image}:latest" + scope="chroot-v1-${CHROOT_CACHE_VARIANT}-${image}-${cache_day}" + echo "::group::Build chroot image ${image}" + status=0 + docker buildx build --load --pull --progress=plain \ + --cache-from "type=gha,version=2,scope=${scope}" \ + --cache-to "type=gha,version=2,mode=max,scope=${scope}" \ + --tag "$tag" "containers/${image}/" || status=$? + echo "::endgroup::" + if (( status == 0 )); then + docker image inspect "$tag" >/dev/null || status=$? + fi + if (( status != 0 )); then + echo "::error::Chroot image build/cache export/inspection failed for ${image} (exit ${status})" >&2 + # Export can fail after --load has already created the tag. + docker image rm --force "$tag" >/dev/null 2>&1 || true + docker builder prune --all --force || true + exit "$status" + fi + # Retain exact loaded images for integration tests, not intermediate layers. + docker builder prune --all --force +done diff --git a/scripts/ci/chroot-image-cache.test.ts b/scripts/ci/chroot-image-cache.test.ts new file mode 100644 index 000000000..c8686c23b --- /dev/null +++ b/scripts/ci/chroot-image-cache.test.ts @@ -0,0 +1,169 @@ +import * as fs from 'fs'; +import * as os from 'os'; +import * as path from 'path'; +import { spawnSync } from 'child_process'; +import * as yaml from 'js-yaml'; + +const root = path.resolve(__dirname, '../..'); +interface Step { + name?: string; + run?: string; + uses?: string; + env?: Record; + with?: Record; +} +const workflow = yaml.load(fs.readFileSync(path.join(root, '.github/workflows/test-chroot.yml'), 'utf8')) as { + permissions: Record; + jobs: Record; +}; +const action = yaml.load(fs.readFileSync(path.join(root, '.github/actions/build-chroot-images/action.yml'), 'utf8')) as { + runs: { using: string; steps: Step[] }; +}; + +describe('chroot cached image wiring', () => { + it('keeps every job, suite, timeout and cleanup while using the shared cache builder', () => { + const expected = [ + ['test-chroot-browser', 'chroot-browser', 30], + ['test-chroot-languages', 'chroot-languages', 30], + ['test-chroot-package-managers', 'chroot-package-managers', 45], + ['test-chroot-procfs', 'chroot-procfs', 30], + ['test-chroot-edge-cases', 'chroot-edge-cases', 30], + ] as const; + expect(Object.keys(workflow.jobs)).toEqual(expected.map(([name]) => name)); + expect(workflow.permissions).toEqual({ contents: 'read' }); + for (const [name, suite, minutes] of expected) { + const job = workflow.jobs[name]; + expect(job['timeout-minutes']).toBe(minutes); + const configure = job.steps.findIndex(step => step.name === 'Configure Docker Hub cache'); + const build = job.steps.findIndex(step => step.name === 'Build local containers'); + const test = job.steps.findIndex(step => step.run?.includes(`--testPathPatterns=${suite}`) + || step.run?.includes(`--testPathPatterns="${suite}"`)); + expect(configure).toBeGreaterThan(0); + expect(job.steps[configure].env).toEqual({ AWF_DOCKER_CONTAINERD_SNAPSHOTTER: 'true' }); + expect(configure).toBeLessThan(build); + expect(build).toBeLessThan(test); + expect(job.steps[build].uses).toBe('./.github/actions/build-chroot-images'); + expect(job.steps.some(step => step.name === 'Post-test cleanup')).toBe(true); + expect(job.steps.some(step => step.run?.includes('docker build'))).toBe(false); + } + const browser = workflow.jobs['test-chroot-browser']; + expect(browser.strategy).toEqual({ + 'fail-fast': false, matrix: { os: ['ubuntu-22.04', 'ubuntu-24.04'] }, + }); + expect(browser.steps.find(step => step.name === 'Build local containers')?.with) + .toEqual({ browser: 'true', 'runner-variant': '${{ matrix.os }}' }); + }); + + it('uses the pinned Docker driver and masks cache credentials before export', () => { + expect(action.runs.using).toBe('composite'); + expect(action.runs.steps[0].uses) + .toBe('docker/setup-buildx-action@f87e5991a6d7451dcb8d9637bfbc97413f497069'); + expect(action.runs.steps[0].with?.driver).toBe('docker'); + const runtime = action.runs.steps[1]; + expect(runtime.uses).toBe('actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3'); + expect(runtime.with?.script).toContain('core.setSecret(value)'); + expect(runtime.with?.script).toContain('throw new Error'); + expect(runtime.with?.script?.indexOf('core.setSecret(value)')) + .toBeLessThan(runtime.with!.script.indexOf('core.exportVariable(name, value)')); + expect(action.runs.steps[2].env?.CHROOT_CACHE_VARIANT) + .toBe('${{ github.job }}-${{ inputs.runner-variant }}-${{ runner.arch }}'); + }); +}); + +describe('cached chroot image builder', () => { + let temp: string; + beforeEach(() => { + temp = fs.mkdtempSync(path.join(os.tmpdir(), 'awf-chroot-cache-')); + fs.writeFileSync(path.join(temp, 'docker'), `#!/usr/bin/env bash +set -euo pipefail +printf '%s\\n' "$*" >> "$TRACE" +if [[ "$*" == "buildx build"* && "$*" == *"/agent:latest"* && "\${FAILURE:-}" == build ]]; then exit 17; fi +if [[ "$*" == "image inspect"* && "\${FAILURE:-}" == inspect ]]; then exit 18; fi +if [[ "$*" == "builder prune"* && "\${FAILURE:-}" == prune ]]; then exit 19; fi +`, { mode: 0o755 }); + fs.writeFileSync(path.join(temp, 'date'), `#!/usr/bin/env bash +[[ "$*" == "-u +%F" ]] || exit 99 +printf '%s\\n' "$FIXTURE_DAY" +`, { mode: 0o755 }); + }); + afterEach(() => fs.rmSync(temp, { recursive: true, force: true })); + + function run(extra: NodeJS.ProcessEnv = {}) { + return spawnSync('bash', [path.join(root, 'scripts/ci/build-chroot-images.sh')], { + encoding: 'utf8', + timeout: 5000, + env: { + ...process.env, + PATH: `${temp}${path.delimiter}${process.env.PATH}`, + TRACE: path.join(temp, 'trace'), + FIXTURE_DAY: '2026-11-04', + GITHUB_ACTIONS: 'true', + RUNNER_ENVIRONMENT: 'github-hosted', + RUNNER_OS: 'Linux', + ACTIONS_RUNTIME_TOKEN: 'fixture-token', + ACTIONS_RESULTS_URL: 'https://cache.example/', + CHROOT_CACHE_VARIANT: 'test-chroot-languages-ubuntu-latest-X64', + CHROOT_BROWSER: 'false', + ...extra, + }, + }); + } + function trace() { + return fs.readFileSync(path.join(temp, 'trace'), 'utf8').trim().split('\n'); + } + + it.each(['2026-11-04', '2026-11-05'])('imports only %s layers and retains exact local tags', day => { + const result = run({ FIXTURE_DAY: day }); + expect(result.status).toBe(0); + expect(result.stdout + result.stderr).not.toContain('fixture-token'); + const calls = trace(); + expect(calls).toHaveLength(6); + ['squid', 'agent'].forEach((image, index) => { + const scope = `chroot-v1-test-chroot-languages-ubuntu-latest-X64-${image}-${day}`; + expect(calls[index * 3]).toBe( + 'buildx build --load --pull --progress=plain ' + + `--cache-from type=gha,version=2,scope=${scope} ` + + `--cache-to type=gha,version=2,mode=max,scope=${scope} ` + + `--tag ghcr.io/github/gh-aw-firewall/${image}:latest containers/${image}/`, + ); + expect(calls[index * 3 + 1]).toBe(`image inspect ghcr.io/github/gh-aw-firewall/${image}:latest`); + expect(calls[index * 3 + 2]).toBe('builder prune --all --force'); + }); + expect(calls.join('\n')).not.toMatch(/image rm|image prune|system prune|ignore-error/); + }); + + it('includes the browser API proxy but no other unrelated images', () => { + expect(run({ CHROOT_BROWSER: 'true' }).status).toBe(0); + expect(trace().filter(call => call.startsWith('buildx build'))).toHaveLength(3); + expect(trace()[7]).toBe('image inspect ghcr.io/github/gh-aw-firewall/api-proxy:latest'); + }); + + it.each([ + ['build', 17], ['inspect', 18], ['prune', 19], + ])('propagates %s failures instead of running tests on incomplete images', (failure, code) => { + const result = run({ FAILURE: String(failure), CHROOT_BROWSER: 'true' }); + expect(result.status).toBe(code); + const calls = trace(); + expect(calls.join('\n')).not.toContain('api-proxy'); + if (failure === 'build') { + expect(result.stderr).toContain('::error::Chroot image build/cache export/inspection failed for agent'); + expect(calls.slice(-2)).toEqual([ + 'image rm --force ghcr.io/github/gh-aw-firewall/agent:latest', 'builder prune --all --force', + ]); + } + if (failure === 'inspect') { + expect(calls.slice(-2)).toEqual([ + 'image rm --force ghcr.io/github/gh-aw-firewall/squid:latest', 'builder prune --all --force', + ]); + } + }); + + it.each([ + { GITHUB_ACTIONS: 'false' }, { RUNNER_ENVIRONMENT: 'self-hosted' }, { RUNNER_OS: 'macOS' }, + { ACTIONS_RUNTIME_TOKEN: '' }, { ACTIONS_RESULTS_URL: '' }, { CHROOT_CACHE_VARIANT: '' }, + { CHROOT_CACHE_VARIANT: 'bad,scope=oops' }, { CHROOT_BROWSER: 'maybe' }, + ])('fails before Docker on unsupported environment %j', extra => { + expect(run(extra).status).not.toBe(0); + expect(fs.existsSync(path.join(temp, 'trace'))).toBe(false); + }); +}); diff --git a/scripts/ci/docker-registry-ci.test.ts b/scripts/ci/docker-registry-ci.test.ts index 2b898f693..5ce8b0ee0 100644 --- a/scripts/ci/docker-registry-ci.test.ts +++ b/scripts/ci/docker-registry-ci.test.ts @@ -316,7 +316,8 @@ echo "$*" >> "$TRACE" it.each(affected)('configures the runner mirror before Docker use in %s / %s', (file, job) => { const steps = jobs(file)[job].steps; const setup = steps.findIndex((step) => step.run === 'bash scripts/ci/configure-docker-mirror.sh'); - const docker = steps.findIndex((step) => step.run?.includes('docker ')); + const docker = steps.findIndex((step) => step.run?.includes('docker ') + || step.uses === './.github/actions/build-chroot-images'); expect(setup).toBeGreaterThanOrEqual(0); expect(setup).toBeLessThan(docker); expect(steps[setup].if).toBeUndefined();