From e1e8290b756a95f75e3803790fa4efa869032e53 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 8 Oct 2026 10:10:37 -0700 Subject: [PATCH 1/4] fix(e2e): select candidate runtime and scope image prerequisites --- .github/workflows/e2e.yaml | 22 +++- scripts/checks/dependency-pins.mts | 2 +- scripts/checks/extract-installer-pins.mts | 29 +++-- test/e2e/README.md | 9 ++ ...mage-publication-workflow-boundary.test.ts | 5 +- .../candidate-openshell-version.test.ts | 105 ++++++++++++++++++ ...ay-auth-contract-workflow-boundary.test.ts | 4 +- .../e2e/support/release-qualification.test.ts | 59 ++++++++++ .../support/workflow-plan-test-assertions.ts | 2 + .../support/workflow-prerequisites.test.ts | 90 +++++++++++++++ test/repository/dependency-pins-check.test.ts | 4 +- tools/e2e/candidate-openshell-version.mts | 66 +++++++++++ ...ateway-auth-contract-workflow-boundary.mts | 2 +- tools/e2e/operations-workflow-boundary.mts | 14 ++- tools/e2e/pre-candidate-workflow-contract.mts | 5 + tools/e2e/release-qualification.mts | 18 ++- tools/e2e/workflow-boundary.mts | 26 +++++ tools/e2e/workflow-plan.mts | 2 + tools/e2e/workflow-prerequisites.mts | 26 +++++ tools/pr-review-advisor/REVIEW-QUEUE.md | 7 +- 20 files changed, 471 insertions(+), 26 deletions(-) create mode 100644 test/e2e/support/candidate-openshell-version.test.ts create mode 100644 test/e2e/support/workflow-prerequisites.test.ts create mode 100644 tools/e2e/candidate-openshell-version.mts create mode 100644 tools/e2e/workflow-prerequisites.mts diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 3c373ae006f..7dcef34c464 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -177,6 +177,8 @@ jobs: retention-days: 1 base-image-publication: + needs: generate-matrix + if: ${{ needs.generate-matrix.outputs.managed_image_required != 'false' }} runs-on: ubuntu-latest timeout-minutes: 55 outputs: @@ -356,7 +358,6 @@ jobs: run: node --no-warnings tools/e2e/managed-image-cohort-contract.mts "${RUNNER_TEMP}/managed-image-cohort/cohort.json" generate-matrix: - needs: base-image-publication runs-on: ubuntu-latest timeout-minutes: 10 permissions: @@ -374,6 +375,8 @@ jobs: release_required_jobs: ${{ steps.matrix.outputs.release_required_jobs }} selected_jobs: ${{ steps.matrix.outputs.selected_jobs }} selected_workflow_jobs: ${{ steps.matrix.outputs.selected_workflow_jobs }} + managed_image_required: ${{ steps.matrix.outputs.managed_image_required }} + openshell_version: ${{ steps.openshell_version.outputs.version }} catalogue_standard_matrix: ${{ steps.matrix.outputs.catalogue_standard_matrix }} catalogue_nvidia_api_matrix: ${{ steps.matrix.outputs.catalogue_nvidia_api_matrix }} catalogue_nvidia_inference_matrix: ${{ steps.matrix.outputs.catalogue_nvidia_inference_matrix }} @@ -697,6 +700,14 @@ jobs: fi npx --no-install tsx tools/e2e/workflow-plan.mts --ci-output + - id: openshell_version + name: Resolve reviewed candidate OpenShell version + env: + CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository || github.repository }} + CANDIDATE_SHA: ${{ inputs.checkout_sha || github.sha }} + GITHUB_TOKEN: ${{ github.token }} + run: node --no-warnings tools/e2e/candidate-openshell-version.mts + # Publish immutable source-run toolchains before candidate checkout or # candidate-controlled workspace preparation can execute on this runner. - name: Stage immutable native Podman E2E toolchains @@ -3468,8 +3479,8 @@ jobs: E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/openshell-gateway-auth-contract NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_NON_INTERACTIVE: "1" - NEMOCLAW_CANDIDATE_VERSION: "0.0.116" - NEMOCLAW_OPENSHELL_PIN_VERSION: "0.0.116" + NEMOCLAW_CANDIDATE_VERSION: ${{ needs.generate-matrix.outputs.openshell_version }} + NEMOCLAW_OPENSHELL_PIN_VERSION: ${{ needs.generate-matrix.outputs.openshell_version }} DOCKER_GRPC_PROBE_IMAGE: "node:24.18.1-trixie-slim@sha256:ac39e4b5fcb2b1b34b20364fd58b2e898f3bb80731ee6f62a7536f9df3d6aadc" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -3543,11 +3554,11 @@ jobs: E2E_TARGET_ID: "external-gateway-health" E2E_AGENT_RUNTIME: "none" E2E_OBSERVABLE_OUTCOME: "The exact Blueprint Runner observes public gateway health over explicit HTTPS and CA" - E2E_ENVIRONMENT_OR_INFERENCE_ENDPOINT: "Ubuntu host with OpenShell 0.0.116; no inference endpoint" + E2E_ENVIRONMENT_OR_INFERENCE_ENDPOINT: "Ubuntu host with reviewed candidate OpenShell; no inference endpoint" E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/external-gateway-health NEMOCLAW_RUN_LIVE_E2E: "1" NEMOCLAW_NON_INTERACTIVE: "1" - NEMOCLAW_OPENSHELL_PIN_VERSION: "0.0.116" + NEMOCLAW_OPENSHELL_PIN_VERSION: ${{ needs.generate-matrix.outputs.openshell_version }} NEMOCLAW_E2E_REQUIRE_EXECUTED_TEST: "1" steps: - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1 @@ -6308,6 +6319,7 @@ jobs: sparse-checkout-cone-mode: false - name: Require every selected E2E result env: + MANAGED_IMAGE_REQUIRED: ${{ needs.generate-matrix.outputs.managed_image_required }} NEEDS_JSON: ${{ toJSON(needs) }} RELEASE_REQUIRED_JOBS: ${{ needs.generate-matrix.outputs.selected_workflow_jobs }} E2E_RESULT_PATH: ${{ inputs.checkout_sha != '' && format('{0}/review-queue-e2e-result.json', runner.temp) || '' }} diff --git a/scripts/checks/dependency-pins.mts b/scripts/checks/dependency-pins.mts index 78997083011..0bf9d8a6f6c 100644 --- a/scripts/checks/dependency-pins.mts +++ b/scripts/checks/dependency-pins.mts @@ -427,7 +427,7 @@ function verifyOpenShellPins( ".github/workflows/e2e.yaml gateway auth OpenShell version", failures, ), - pins.maxVersion, + "${{ needs.generate-matrix.outputs.openshell_version }}", ".github/workflows/e2e.yaml gateway auth OpenShell version", failures, ); diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index e0925816242..72795e208b5 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -1764,15 +1764,14 @@ function parseCliOptions(argv: string[]): CliOptions { return { blueprint, brevInstaller, format, installer, supervisorRuntime }; } -function runCli(): void { - const options = parseCliOptions(process.argv.slice(2)); - const blueprintSource = readInstallerInput(options.blueprint, "blueprint"); - const installerSource = readInstallerInput(options.installer, "installer"); - const brevInstallerSource = readInstallerInput(options.brevInstaller, "Brev launchable"); - const supervisorRuntimeSource = readInstallerInput( - options.supervisorRuntime, - "supervisor runtime", - ); +export function validateInstallerSources(sources: { + blueprintSource: string; + installerSource: string; + brevInstallerSource: string; + supervisorRuntimeSource: string; +}) { + const { blueprintSource, installerSource, brevInstallerSource, supervisorRuntimeSource } = + sources; const installerPins = extractInstallerPins(installerSource, { functionName: "openshell_pinned_sha256", sourceLabel: "installer", @@ -1851,6 +1850,18 @@ function runCli(): void { fail(`installer pin-table release ${releaseVersion} must match ${label} ${runtimeVersion}`); } } + return { releaseVersion, pins, installerReleases, installerTemplateSha256, brevTemplateSha256 }; +} + +function runCli(): void { + const options = parseCliOptions(process.argv.slice(2)); + const { pins, installerReleases, installerTemplateSha256, brevTemplateSha256 } = + validateInstallerSources({ + blueprintSource: readInstallerInput(options.blueprint, "blueprint"), + installerSource: readInstallerInput(options.installer, "installer"), + brevInstallerSource: readInstallerInput(options.brevInstaller, "Brev launchable"), + supervisorRuntimeSource: readInstallerInput(options.supervisorRuntime, "supervisor runtime"), + }); if (options.format === "json") { process.stdout.write( `${JSON.stringify( diff --git a/test/e2e/README.md b/test/e2e/README.md index ee7c04d87cb..470c93d48c9 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -1836,6 +1836,15 @@ The API must report `NVIDIA/NemoClaw` as the PR source repository. Empty `jobs` A same-repository PR may also select any supported E2E job or target. Main and manual PR runs use the same typed planner from the trusted workflow revision. +The planner derives managed-image prerequisites from the selected jobs' dependency graph. +Gateway auth and external gateway health can run without managed-agent image publication; +selecting an image consumer alongside them retains that consumer's publication gate. +Before candidate execution, the trusted installer verifier reads the exact candidate's blueprint, +installer, Brev installer, and supervisor pins as data and selects its reviewed OpenShell release. +Gateway auth and external gateway health use that version, not the version pinned on `main`. +Unreviewed releases, inconsistent pins, and modified installer templates fail admission. +Adding release trust remains a reviewed change; selecting an already trusted version needs no +version-specific workflow change. A focused pass is not full release qualification. PRs from forks, including other NVIDIA repositories, are rejected before candidate execution. The run skips `jetson-nvmap-gpu` unless `allow_jetson_dispatch` is `true`. Jetson and Launchable retain their operator and image-producer requirements. diff --git a/test/e2e/support/base-image-publication-workflow-boundary.test.ts b/test/e2e/support/base-image-publication-workflow-boundary.test.ts index dbfafa63f93..8863b624e75 100644 --- a/test/e2e/support/base-image-publication-workflow-boundary.test.ts +++ b/test/e2e/support/base-image-publication-workflow-boundary.test.ts @@ -312,7 +312,10 @@ describe("base-image publication workflow boundary (#7372)", () => { "node tools/e2e/dcode-base-image-contract.mts contract.json"), ], ["step count", (value) => gateSteps(value).push({ name: "Unreviewed step", run: "true" })], - ["matrix publication dependency", (value) => (value.jobs["generate-matrix"].needs = [])], + [ + "matrix publication dependency", + (value) => (value.jobs["generate-matrix"].needs = ["base-image-publication"]), + ], ["live publication dependency", (value) => (value.jobs.live.needs = ["generate-matrix"])], [ "live SDK dependency", diff --git a/test/e2e/support/candidate-openshell-version.test.ts b/test/e2e/support/candidate-openshell-version.test.ts new file mode 100644 index 00000000000..d922e87780f --- /dev/null +++ b/test/e2e/support/candidate-openshell-version.test.ts @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import { describe, expect, it, vi } from "vitest"; +import { candidateOpenShellVersion } from "../../../tools/e2e/candidate-openshell-version.mts"; + +const sha = "a".repeat(40); +const repository = "NVIDIA/NemoClaw"; +function sourceResponse(url: string) { + const parsed = new URL(url, "https://api.github.com"); + expect(parsed.searchParams.get("ref")).toBe(sha); + const path = parsed.pathname.replace(`/repos/${repository}/contents/`, ""); + const source = readFileSync(new URL(`../../../${path}`, import.meta.url)); + return { + type: "file", + path, + encoding: "base64", + size: source.length, + content: source.toString("base64"), + }; +} + +describe("candidate OpenShell selection", () => { + it("reads only immutable candidate data and selects the reviewed runtime", async () => { + const request = vi.fn(async (url: string) => sourceResponse(url)); + await expect(candidateOpenShellVersion(repository, sha, request)).resolves.toBe("0.0.116"); + expect(request).toHaveBeenCalledTimes(4); + }); + + it.each(["main", "a".repeat(39), `${sha}\nversion=9.9.9`])( + "rejects mutable or malformed revision %s", + async (revision) => { + const request = vi.fn(); + await expect(candidateOpenShellVersion(repository, revision, request)).rejects.toThrow( + "exact", + ); + expect(request).not.toHaveBeenCalled(); + }, + ); + + it("rejects a fork before reading it", async () => { + const request = vi.fn(); + await expect(candidateOpenShellVersion("other/NemoClaw", sha, request)).rejects.toThrow( + "exact", + ); + expect(request).not.toHaveBeenCalled(); + }); + + it.each([ + { type: "symlink" }, + { size: 1024 * 1024 + 1 }, + { encoding: "none" }, + { path: "other" }, + { content: "AA==" }, + { size: 0 }, + ])("rejects invalid candidate files %j", async (mutation) => { + await expect( + candidateOpenShellVersion(repository, sha, async (url) => ({ + ...sourceResponse(url), + ...mutation, + })), + ).rejects.toThrow("Invalid candidate"); + }); + + it("propagates API failure without falling back to main", async () => { + await expect( + candidateOpenShellVersion(repository, sha, async () => { + throw new Error("API denied"); + }), + ).rejects.toThrow("API denied"); + }); + + it.each([ + { + name: "unknown release", + target: /.*/, + rewrite: (source: string) => source.replaceAll("0.0.116", "9.9.9"), + }, + { + name: "mismatched blueprint", + target: /blueprint\.yaml$/, + rewrite: (source: string) => + source.replace(/max_openshell_version: .*/, 'max_openshell_version: "9.9.9"'), + }, + { + name: "modified installer", + target: /install-openshell\.sh$/, + rewrite: (source: string) => `${source}\nprintf "unreviewed command"\n`, + }, + ])("rejects $name through the trusted verifier", async ({ target, rewrite }) => { + await expect( + candidateOpenShellVersion(repository, sha, async (url) => { + const blob = sourceResponse(url); + const original = Buffer.from(blob.content, "base64").toString("utf8"); + const source = target.test(blob.path) ? rewrite(original) : original; + return { + ...blob, + size: Buffer.byteLength(source), + content: Buffer.from(source).toString("base64"), + }; + }), + ).rejects.toThrow(); + }); +}); diff --git a/test/e2e/support/openshell-gateway-auth-contract-workflow-boundary.test.ts b/test/e2e/support/openshell-gateway-auth-contract-workflow-boundary.test.ts index e3e3533d2e6..e7f71464313 100644 --- a/test/e2e/support/openshell-gateway-auth-contract-workflow-boundary.test.ts +++ b/test/e2e/support/openshell-gateway-auth-contract-workflow-boundary.test.ts @@ -72,8 +72,8 @@ describe("OpenShell gateway auth contract workflow boundary", () => { "openshell-gateway-auth-contract must retain its 20 minute resource budget", "openshell-gateway-auth-contract must set DOCKER_GRPC_PROBE_IMAGE=node:24.18.1-trixie-slim@sha256:ac39e4b5fcb2b1b34b20364fd58b2e898f3bb80731ee6f62a7536f9df3d6aadc", "openshell-gateway-auth-contract must set E2E_ARTIFACT_DIR=${{ github.workspace }}/e2e-artifacts/live/openshell-gateway-auth-contract", - "openshell-gateway-auth-contract must set NEMOCLAW_CANDIDATE_VERSION=0.0.116", - "openshell-gateway-auth-contract must set NEMOCLAW_OPENSHELL_PIN_VERSION=0.0.116", + "openshell-gateway-auth-contract must set NEMOCLAW_CANDIDATE_VERSION=${{ needs.generate-matrix.outputs.openshell_version }}", + "openshell-gateway-auth-contract must set NEMOCLAW_OPENSHELL_PIN_VERSION=${{ needs.generate-matrix.outputs.openshell_version }}", "openshell-gateway-auth-contract must not expose NVIDIA_API_KEY at job scope", "openshell-gateway-auth-contract action 'actions/checkout@v6' must pin a full SHA", "openshell-gateway-auth-contract checkout must disable persisted credentials", diff --git a/test/e2e/support/release-qualification.test.ts b/test/e2e/support/release-qualification.test.ts index 6941b53731b..9d5bbf3c1b8 100644 --- a/test/e2e/support/release-qualification.test.ts +++ b/test/e2e/support/release-qualification.test.ts @@ -21,6 +21,65 @@ const successfulNeeds = { }; describe("release qualification", () => { + it("records a skipped image gate without claiming image qualification", ({ onTestFinished }) => { + const directory = mkdtempSync(path.join(tmpdir(), "e2e-independent-result-")); + onTestFinished(() => rmSync(directory, { recursive: true, force: true })); + const outputPath = path.join(directory, "result.json"); + assertReleaseQualification( + JSON.stringify({ + "generate-matrix": { result: "success" }, + "base-image-publication": { result: "skipped" }, + gateway: { result: "success" }, + }), + '["gateway"]', + { outputPath, runId: "123", attempt: "1" }, + false, + ); + const receipt = JSON.parse(readFileSync(outputPath, "utf8")); + expect(receipt.status).toBe("pass"); + expect(receipt.managedImageRequired).toBe(false); + expect(receipt.selectedWorkflowJobs).toEqual(["gateway"]); + expect(receipt.results).toContainEqual({ job: "base-image-publication", result: "skipped" }); + }); + it("accepts a deliberately skipped image prerequisite only for an independent selection", () => { + const needs = { + ...successfulNeeds, + "base-image-publication": { result: "skipped" }, + gateway: { result: "success" }, + }; + expect(failedReleaseQualificationJobs(needs, ["gateway"], false)).toEqual([]); + expect(failedReleaseQualificationJobs(needs, ["gateway"])).toEqual(["base-image-publication"]); + expect( + failedReleaseQualificationJobs( + { ...needs, gateway: { result: "skipped" } }, + ["gateway"], + false, + ), + ).toEqual(["gateway"]); + expect( + failedReleaseQualificationJobs( + { ...needs, "generate-matrix": { result: "failure" } }, + ["gateway"], + false, + ), + ).toEqual(["generate-matrix"]); + }); + it.each(["failure", "cancelled", undefined])( + "rejects image prerequisite result %s even for an independent selection", + (result) => { + expect( + failedReleaseQualificationJobs( + { + ...successfulNeeds, + gateway: { result: "success" }, + "base-image-publication": { result }, + }, + ["gateway"], + false, + ), + ).toEqual(["base-image-publication"]); + }, + ); it("records passing PR evidence and refuses to overwrite it (#11489)", ({ onTestFinished }) => { const directory = mkdtempSync(path.join(tmpdir(), "e2e-result-")); onTestFinished(() => rmSync(directory, { recursive: true, force: true })); diff --git a/test/e2e/support/workflow-plan-test-assertions.ts b/test/e2e/support/workflow-plan-test-assertions.ts index 4e29c6bbf20..4b5116fa3fe 100644 --- a/test/e2e/support/workflow-plan-test-assertions.ts +++ b/test/e2e/support/workflow-plan-test-assertions.ts @@ -6,6 +6,7 @@ import { releaseRequiredWorkflowJobs, selectedWorkflowJobs, } from "../../../tools/e2e/workflow-plan.mts"; +import { requiresManagedImages } from "../../../tools/e2e/workflow-prerequisites.mts"; export function expectedWorkflowPlanCiOutput( plan: ReturnType, @@ -21,6 +22,7 @@ export function expectedWorkflowPlanCiOutput( `runtime_providers_by_job=${JSON.stringify(plan.runtimeProvidersByJob)}`, `selected_jobs=${JSON.stringify(plan.selectedJobs)}`, `selected_workflow_jobs=${JSON.stringify(selectedWorkflowJobs(plan))}`, + `managed_image_required=${requiresManagedImages(selectedWorkflowJobs(plan))}`, `hermes_selected=${plan.hermesSelected}`, `explicit_only_jobs=${plan.explicitOnlyJobs.join(",")}`, `release_required_jobs=${JSON.stringify(releaseRequiredWorkflowJobs())}`, diff --git a/test/e2e/support/workflow-prerequisites.test.ts b/test/e2e/support/workflow-prerequisites.test.ts new file mode 100644 index 00000000000..c4810553565 --- /dev/null +++ b/test/e2e/support/workflow-prerequisites.test.ts @@ -0,0 +1,90 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it } from "vitest"; +import { requiresManagedImages } from "../../../tools/e2e/workflow-prerequisites.mts"; +import { validateE2eWorkflow } from "../../../tools/e2e/workflow-boundary.mts"; +import { readWorkflow, type Workflow } from "../../helpers/e2e-workflow-contract.ts"; +import { buildE2eWorkflowPlan, selectedWorkflowJobs } from "../../../tools/e2e/workflow-plan.mts"; + +describe("selected E2E prerequisites", () => { + it.each([ + { + name: "version output", + mutate: (workflow: Workflow) => { + workflow.jobs["generate-matrix"]!.outputs!.openshell_version = "0.0.116"; + }, + }, + { + name: "version command", + mutate: (workflow: Workflow) => { + workflow.jobs["generate-matrix"]!.steps!.find( + (step) => step.id === "openshell_version", + )!.run = "echo version=0.0.116 >> $GITHUB_OUTPUT"; + }, + }, + { + name: "version identity", + mutate: (workflow: Workflow) => { + workflow.jobs["generate-matrix"]!.steps!.find( + (step) => step.id === "openshell_version", + )!.env!.CANDIDATE_SHA = "${{ inputs.base_sha }}"; + }, + }, + { + name: "health version", + mutate: (workflow: Workflow) => { + workflow.jobs["external-gateway-health"]!.env!.NEMOCLAW_OPENSHELL_PIN_VERSION = "0.0.116"; + }, + }, + { + name: "publication selector", + mutate: (workflow: Workflow) => { + workflow.jobs["base-image-publication"]!.if = "false"; + }, + }, + { + name: "full release bypass", + mutate: (workflow: Workflow) => { + workflow.jobs["release-qualification"]!.steps![1]!.env!.MANAGED_IMAGE_REQUIRED = "false"; + }, + }, + ])("rejects an altered $name boundary", ({ mutate }) => { + const workflow = structuredClone(readWorkflow()) as unknown as Workflow; + mutate(workflow); + expect(validateE2eWorkflow(workflow).length).toBeGreaterThan(0); + }); + it.each([ + ["openshell-gateway-auth-contract", false], + ["external-gateway-health", false], + ["openshell-gateway-auth-contract,external-gateway-health", false], + ["openshell-gateway-auth-contract,mcp-bridge", true], + ["managed-image-protected-runtime", true], + ["", true], + ])("requires managed images for %s: %s", (jobs, expected) => { + expect(requiresManagedImages(selectedWorkflowJobs(buildE2eWorkflowPlan({ jobs })))).toBe( + expected, + ); + }); + + it("follows transitive consumers and checks every selected dependency", () => { + const jobs = { + "base-image-publication": {}, + consumer: { needs: "base-image-publication" }, + nested: { needs: "consumer" }, + independent: {}, + }; + expect(requiresManagedImages(["nested", "independent"], jobs)).toBe(true); + expect(() => requiresManagedImages(["nested", "unknown"], jobs)).toThrow("Unknown"); + expect(requiresManagedImages([], jobs)).toBe(false); + }); + + it("rejects cycles and malformed dependencies", () => { + expect(() => requiresManagedImages(["a"], { a: { needs: "b" }, b: { needs: "a" } })).toThrow( + "Cyclic", + ); + expect(() => + requiresManagedImages(["a"], { a: { needs: [42] as unknown as string[] } }), + ).toThrow("Invalid"); + }); +}); diff --git a/test/repository/dependency-pins-check.test.ts b/test/repository/dependency-pins-check.test.ts index 0634580122b..68d00715315 100644 --- a/test/repository/dependency-pins-check.test.ts +++ b/test/repository/dependency-pins-check.test.ts @@ -100,7 +100,7 @@ esac jobs: openshell-gateway-auth-contract: env: - NEMOCLAW_OPENSHELL_PIN_VERSION: "${overrides.workflowPinVersion ?? openshellMax}" + NEMOCLAW_OPENSHELL_PIN_VERSION: "${overrides.workflowPinVersion ?? "${{ needs.generate-matrix.outputs.openshell_version }}"}" `, [`src/lib/actions/sandbox/${credentialManifestName}`]: JSON.stringify({ openshellCommit: "f".repeat(40), @@ -278,7 +278,7 @@ describe("dependency pin drift check", () => { "OpenShell supervisor manifest digest map: expected a reference to 1.2.4", "OpenShell sandbox build version map: expected a reference to 1.2.4", "Brev launchable stable OpenShell default: expected 1.2.4, found 1.2.3", - ".github/workflows/e2e.yaml gateway auth OpenShell version: expected 1.2.4, found 1.2.3", + ".github/workflows/e2e.yaml gateway auth OpenShell version: expected ${{ needs.generate-matrix.outputs.openshell_version }}, found 1.2.3", "OpenShell credential-boundary manifest version: expected 1.2.4, found 1.2.3", "OpenShell credential-boundary import: expected 1.2.4, found 1.2.3", "Hermes Dockerfile credential-boundary manifest version: expected 1.2.4, found 1.2.3", diff --git a/tools/e2e/candidate-openshell-version.mts b/tools/e2e/candidate-openshell-version.mts new file mode 100644 index 00000000000..fc597acdc58 --- /dev/null +++ b/tools/e2e/candidate-openshell-version.mts @@ -0,0 +1,66 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { appendFileSync } from "node:fs"; +import { pathToFileURL } from "node:url"; +import { validateInstallerSources } from "../../scripts/checks/extract-installer-pins.mts"; +import { githubRequest } from "./base-image-publication.mts"; + +const SOURCE_PATHS = { + blueprintSource: "nemoclaw-blueprint/blueprint.yaml", + installerSource: "scripts/install-openshell.sh", + brevInstallerSource: "scripts/brev-launchable-ci-cpu.sh", + supervisorRuntimeSource: "src/lib/onboard/docker-driver-gateway-runtime.ts", +} as const; + +// Runs from the trusted workflow checkout, before any candidate code executes. +// Candidate files are inert inputs to the existing release/template verifier. +export async function candidateOpenShellVersion( + repository: string, + candidateSha: string, + request: (path: string) => Promise, +): Promise { + if (repository !== "NVIDIA/NemoClaw" || !/^[0-9a-f]{40}$/u.test(candidateSha)) { + throw new Error("OpenShell selection requires an exact NVIDIA/NemoClaw candidate SHA"); + } + const sources = {} as Record; + for (const [key, sourcePath] of Object.entries(SOURCE_PATHS)) { + const value = await request(`/repos/${repository}/contents/${sourcePath}?ref=${candidateSha}`); + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error(`Missing candidate source: ${sourcePath}`); + } + const blob = value as Record; + if ( + blob.type !== "file" || + blob.path !== sourcePath || + blob.encoding !== "base64" || + typeof blob.content !== "string" || + blob.content.length > 1_500_000 || + typeof blob.size !== "number" || + blob.size < 1 || + blob.size > 1024 * 1024 || + blob.submodule_git_url !== undefined || + blob.target !== undefined + ) { + throw new Error(`Invalid candidate source: ${sourcePath}`); + } + const bytes = Buffer.from(blob.content, "base64"); + if (bytes.length !== blob.size || bytes.includes(0)) { + throw new Error(`Invalid candidate source bytes: ${sourcePath}`); + } + sources[key as keyof typeof SOURCE_PATHS] = bytes.toString("utf8"); + } + return validateInstallerSources(sources).releaseVersion; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const output = process.env.GITHUB_OUTPUT; + if (!output) throw new Error("GitHub output path is required"); + const version = await candidateOpenShellVersion( + process.env.CANDIDATE_REPOSITORY ?? "", + process.env.CANDIDATE_SHA ?? "", + (url) => githubRequest(url, process.env.GITHUB_TOKEN ?? ""), + ); + appendFileSync(output, `version=${version}\n`); + console.log(`Reviewed candidate OpenShell release: ${version}`); +} diff --git a/tools/e2e/openshell-gateway-auth-contract-workflow-boundary.mts b/tools/e2e/openshell-gateway-auth-contract-workflow-boundary.mts index 102ebb17d1a..f09dd46ec95 100644 --- a/tools/e2e/openshell-gateway-auth-contract-workflow-boundary.mts +++ b/tools/e2e/openshell-gateway-auth-contract-workflow-boundary.mts @@ -12,7 +12,7 @@ import { UPLOAD_E2E_ARTIFACTS_ACTION } from "./upload-e2e-artifacts-workflow-bou const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..", ".."); const DEFAULT_WORKFLOW_PATH = join(REPO_ROOT, ".github", "workflows", "e2e.yaml"); const JOB_NAME = "openshell-gateway-auth-contract"; -const OPENSHELL_RELEASE_VERSION = "0.0.116"; +const OPENSHELL_RELEASE_VERSION = "${{ needs.generate-matrix.outputs.openshell_version }}"; const OPENSHELL_INSTALL_RUN = "env -u DOCKER_CONFIG -u DOCKERHUB_USERNAME -u DOCKERHUB_TOKEN -u NVIDIA_API_KEY -u NVIDIA_INFERENCE_API_KEY -u GITHUB_TOKEN bash scripts/install-openshell.sh"; const FULL_SHA_ACTION = /^[^\s@]+@[0-9a-f]{40}$/u; diff --git a/tools/e2e/operations-workflow-boundary.mts b/tools/e2e/operations-workflow-boundary.mts index 1ca2494b1f7..486329c269b 100644 --- a/tools/e2e/operations-workflow-boundary.mts +++ b/tools/e2e/operations-workflow-boundary.mts @@ -748,6 +748,8 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): const errors: string[] = []; const job = workflow.jobs["base-image-publication"] ?? {}; const expectedJob = { + needs: "generate-matrix", + if: "${{ needs.generate-matrix.outputs.managed_image_required != 'false' }}", "runs-on": "ubuntu-latest", "timeout-minutes": 55, outputs: { @@ -901,10 +903,15 @@ export function validateBaseImagePublicationGate(workflow: OperationsWorkflow): ); } const matrix = workflow.jobs["generate-matrix"] ?? {}; - if (!sameMembers(needs(matrix), ["base-image-publication"])) { - errors.push("generate-matrix must wait for complete managed-image publication"); + if (needs(matrix).length !== 0) { + errors.push("generate-matrix must not wait for managed-image publication"); } const matrixOutputs = matrix.outputs ?? {}; + if ( + matrixOutputs.managed_image_required !== "${{ steps.matrix.outputs.managed_image_required }}" + ) { + errors.push("managed-image admission must use the trusted planner output"); + } if ("dcode_base_contract" in matrixOutputs || "dcode_base_ref" in matrixOutputs) { errors.push("generate-matrix must not relay Deep Agents Code base outputs"); } @@ -1246,6 +1253,8 @@ function validateRelevantE2e(errors: string[], workflow: OperationsWorkflow): vo requireResults.env?.NEEDS_JSON !== "${{ toJSON(needs) }}" || requireResults.env?.RELEASE_REQUIRED_JOBS !== "${{ needs.generate-matrix.outputs.selected_workflow_jobs }}" || + requireResults.env?.MANAGED_IMAGE_REQUIRED !== + "${{ needs.generate-matrix.outputs.managed_image_required }}" || requireResults.env?.E2E_RESULT_PATH !== "${{ inputs.checkout_sha != '' && format('{0}/review-queue-e2e-result.json', runner.temp) || '' }}" || requireResults.run !== "node --no-warnings tools/e2e/release-qualification.mts" @@ -1290,6 +1299,7 @@ function validateReleaseQualification(errors: string[], workflow: OperationsWork requireResults.env?.NEEDS_JSON !== "${{ toJSON(needs) }}" || requireResults.env?.RELEASE_REQUIRED_JOBS !== "${{ needs.generate-matrix.outputs.release_required_jobs }}" || + requireResults.env?.MANAGED_IMAGE_REQUIRED !== undefined || requireResults.run !== "node --no-warnings tools/e2e/release-qualification.mts" ) { errors.push("release-qualification must evaluate planner-selected jobs from needs"); diff --git a/tools/e2e/pre-candidate-workflow-contract.mts b/tools/e2e/pre-candidate-workflow-contract.mts index 3d40ec7bb33..6acb6db6984 100644 --- a/tools/e2e/pre-candidate-workflow-contract.mts +++ b/tools/e2e/pre-candidate-workflow-contract.mts @@ -73,6 +73,11 @@ export const PRE_CANDIDATE_STEP_ENV: Readonly> = { diff --git a/tools/e2e/release-qualification.mts b/tools/e2e/release-qualification.mts index 7e908cfe102..2596c082eb2 100644 --- a/tools/e2e/release-qualification.mts +++ b/tools/e2e/release-qualification.mts @@ -29,9 +29,16 @@ function parseJobIds(value: string, label: string, invalidLabel = label.toLowerC export function failedReleaseQualificationJobs( needs: Record, releaseRequiredJobs: readonly string[], + managedImageRequired = true, ): string[] { return [...CONTROLLER_JOBS, ...releaseRequiredJobs].filter( - (job) => needs[job]?.result !== "success", + (job) => + needs[job]?.result !== "success" && + !( + job === "base-image-publication" && + !managedImageRequired && + needs[job]?.result === "skipped" + ), ); } @@ -39,6 +46,7 @@ export function assertReleaseQualification( needsJson: string, releaseRequiredJobsJson: string, evidence?: { outputPath: string; runId: string; attempt: string }, + managedImageRequired = true, ): void { const needs = JSON.parse(needsJson) as Record; if (!needs || typeof needs !== "object" || Array.isArray(needs)) { @@ -49,7 +57,11 @@ export function assertReleaseQualification( "Release-required jobs", "release-required job IDs", ); - const failedJobs = failedReleaseQualificationJobs(needs, releaseRequiredJobs); + const failedJobs = failedReleaseQualificationJobs( + needs, + releaseRequiredJobs, + managedImageRequired, + ); if (evidence) { if (!/^[1-9][0-9]*$/.test(evidence.runId) || !/^[1-9][0-9]*$/.test(evidence.attempt)) { throw new Error("Invalid dispatch receipt reference"); @@ -72,6 +84,7 @@ export function assertReleaseQualification( kind: "nemoclaw-review-queue-e2e-result-v1", dispatchArtifact: `e2e-dispatch-${evidence.runId}-${evidence.attempt}`, selectedWorkflowJobs: releaseRequiredJobs, + ...(!managedImageRequired ? { managedImageRequired: false } : {}), results, status: failedJobs.length === 0 @@ -102,5 +115,6 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) attempt: process.env.GITHUB_RUN_ATTEMPT ?? "", } : undefined, + process.env.MANAGED_IMAGE_REQUIRED !== "false", ); } diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 3fa8673d216..6e1900c1e91 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -2695,6 +2695,7 @@ function validatePreCandidateActions( "Authorize Launchable E2E maintainer dispatch", "Install trusted E2E planner dependencies", "Generate E2E target matrix", + "Resolve reviewed candidate OpenShell version", ]); const seen = new Set(); for (const step of steps.slice(0, candidateCheckout ? steps.indexOf(candidateCheckout) : 0)) { @@ -2802,6 +2803,22 @@ function validateTrustedE2ePlannerBoundary( : -1; const generateIndex = generate ? generateSteps.indexOf(generate) : -1; const candidateCheckoutIndex = candidateCheckout ? generateSteps.indexOf(candidateCheckout) : -1; + const version = requireStep( + errors, + generateSteps, + "Resolve reviewed candidate OpenShell version", + ); + const versionIndex = version ? generateSteps.indexOf(version) : -1; + if ( + versionIndex <= generateIndex || + versionIndex >= candidateCheckoutIndex || + version?.id !== "openshell_version" || + version?.run !== "node --no-warnings tools/e2e/candidate-openshell-version.mts" + ) { + errors.push( + "candidate OpenShell selection must use the trusted verifier before candidate checkout", + ); + } if ( trustedPlannerIndex < 0 || trustedSetupIndex <= trustedPlannerIndex || @@ -2989,6 +3006,15 @@ export function validateE2eWorkflow(workflowValue: unknown): string[] { if (generateOutputs.test_matrix !== "${{ steps.matrix.outputs.test_matrix }}") { errors.push("generate-matrix job must expose test_matrix output"); } + if (generateOutputs.openshell_version !== "${{ steps.openshell_version.outputs.version }}") { + errors.push("generate-matrix must expose the reviewed candidate OpenShell version"); + } + if ( + asRecord(asRecord(jobs["external-gateway-health"]).env).NEMOCLAW_OPENSHELL_PIN_VERSION !== + "${{ needs.generate-matrix.outputs.openshell_version }}" + ) { + errors.push("external-gateway-health must use the reviewed candidate OpenShell version"); + } if (generateOutputs.hermes_selected !== "${{ steps.matrix.outputs.hermes_selected }}") { errors.push("generate-matrix job must expose hermes_selected output"); } diff --git a/tools/e2e/workflow-plan.mts b/tools/e2e/workflow-plan.mts index a6b2ce9443d..70bb41d1abe 100644 --- a/tools/e2e/workflow-plan.mts +++ b/tools/e2e/workflow-plan.mts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { appendFileSync } from "node:fs"; +import { requiresManagedImages } from "./workflow-prerequisites.mts"; import path from "node:path"; import { fileURLToPath } from "node:url"; import { isDeepStrictEqual } from "node:util"; @@ -1176,6 +1177,7 @@ export function writeE2eWorkflowPlanCiOutput( `runtime_providers_by_job=${JSON.stringify(plan.runtimeProvidersByJob)}`, `selected_jobs=${JSON.stringify(plan.selectedJobs)}`, `selected_workflow_jobs=${JSON.stringify(selectedWorkflowJobs(plan))}`, + `managed_image_required=${requiresManagedImages(selectedWorkflowJobs(plan))}`, `hermes_selected=${plan.hermesSelected}`, `explicit_only_jobs=${plan.explicitOnlyJobs.join(",")}`, `release_required_jobs=${JSON.stringify(releaseRequiredWorkflowJobs())}`, diff --git a/tools/e2e/workflow-prerequisites.mts b/tools/e2e/workflow-prerequisites.mts new file mode 100644 index 00000000000..3fee9571d82 --- /dev/null +++ b/tools/e2e/workflow-prerequisites.mts @@ -0,0 +1,26 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import YAML from "yaml"; + +// Use the trusted workflow's dependency graph, not a second list of image consumers. +export function requiresManagedImages( + selectedJobs: readonly string[], + jobs: Record = YAML.parse( + readFileSync(new URL("../../.github/workflows/e2e.yaml", import.meta.url), "utf8"), + ).jobs, +): boolean { + const visit = (job: string, ancestors: readonly string[]): boolean => { + if (!Object.hasOwn(jobs, job)) throw new Error(`Unknown E2E prerequisite: ${job}`); + if (ancestors.includes(job)) throw new Error(`Cyclic E2E prerequisite: ${job}`); + if (job === "base-image-publication") return true; + const dependencies = jobs[job]!.needs ?? []; + const needs = typeof dependencies === "string" ? [dependencies] : dependencies; + if (!Array.isArray(needs) || needs.some((value) => typeof value !== "string")) { + throw new Error(`Invalid E2E prerequisites: ${job}`); + } + return needs.map((dependency) => visit(dependency, [...ancestors, job])).some(Boolean); + }; + return selectedJobs.map((job) => visit(job, [])).some(Boolean); +} diff --git a/tools/pr-review-advisor/REVIEW-QUEUE.md b/tools/pr-review-advisor/REVIEW-QUEUE.md index 43325fd0552..838b5298f7e 100644 --- a/tools/pr-review-advisor/REVIEW-QUEUE.md +++ b/tools/pr-review-advisor/REVIEW-QUEUE.md @@ -146,7 +146,12 @@ The existing `Relevant E2E` job uploads `review-queue-e2e-result-- Date: Thu, 8 Oct 2026 11:34:16 -0700 Subject: [PATCH 2/4] fix(e2e): consolidate candidate dependency qualification controller --- .github/workflows/e2e.yaml | 52 ++-- ...managed-image-multiarch-activation-v1.json | 5 +- .../checks/build-protected-managed-images.sh | 75 ++++- .../checks/protected-dcode-base-receipt.mts | 246 ++++++++++++++++ .../protected-managed-image-contract.ts | 25 +- test/e2e/README.md | 20 ++ ...d-image-protected-runtime-workflow.test.ts | 11 + .../pr-managed-image-publication.test.ts | 62 ++++ .../protected-dcode-base-receipt.test.ts | 268 ++++++++++++++++++ .../shared-e2e-workflow-boundary.test.ts | 3 +- ...ck-managed-image-workflow-boundary.test.ts | 6 +- .../support/workflow-plan-launchable.test.ts | 105 +++++++ test/e2e/support/workflow-plan.test.ts | 44 --- ...otected-managed-image-build-script.test.ts | 190 ++++++++++++- .../protected-managed-image-contract.test.ts | 60 +++- ...aged-image-multiarch-workflow-boundary.mts | 12 +- ...ge-protected-runtime-workflow-boundary.mts | 5 + tools/e2e/pre-candidate-workflow-contract.mts | 2 + tools/e2e/workflow-plan.mts | 18 +- 19 files changed, 1123 insertions(+), 86 deletions(-) create mode 100644 scripts/checks/protected-dcode-base-receipt.mts create mode 100644 test/e2e/support/protected-dcode-base-receipt.test.ts create mode 100644 test/e2e/support/workflow-plan-launchable.test.ts diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 7dcef34c464..bd07c9db715 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -662,6 +662,7 @@ jobs: - id: matrix name: Generate E2E target matrix env: + NEMOCLAW_E2E_INCLUDE_STAGING_BREV_LAUNCHABLE: ${{ github.repository == 'NVIDIA/NemoClaw' && github.event_name == 'workflow_dispatch' && github.ref == 'refs/heads/main' && inputs.include_staging_brev_launchable && 'true' || 'false' }} INFERENCE_MODE: ${{ inputs.inference_mode || 'mock' }} NEMOCLAW_GATEWAY_RUNTIMES: ${{ inputs.jobs == 'portable-hermes-finalization' && 'podman' || inputs.gateway_runtimes || inputs.gateway_runtime || 'docker' }} JOBS: ${{ inputs.jobs }} @@ -4564,7 +4565,8 @@ jobs: - *dockerhub-auth - - name: Validate candidate activation contract + - id: candidate-contract + name: Validate candidate activation contract env: CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} shell: bash @@ -4580,8 +4582,11 @@ jobs: exit 1 } jq -e ' - (keys | sort) == ["agents", "contractVersion", "jobId", "platforms"] and - .contractVersion == 1 and + ( + ((keys | sort) == ["agents", "contractVersion", "jobId", "platforms"] and .contractVersion == 1) or + ((keys | sort) == ["agents", "contractVersion", "dcodeBaseSource", "jobId", "platforms"] and + .contractVersion == 2 and .dcodeBaseSource == "candidate") + ) and .jobId == "managed-image-multiarch-startup" and .agents == ["openclaw", "hermes", "langchain-deepagents-code"] and .platforms == ["linux/amd64", "linux/arm64"] @@ -4589,6 +4594,7 @@ jobs: echo "::error::Protected managed-image activation contract is invalid" >&2 exit 1 } + printf 'dcode_source=%s\n' "$(jq -r '.dcodeBaseSource // "published"' "$activation")" >> "$GITHUB_OUTPUT" install -d -m 0700 "$E2E_ARTIFACT_DIR" - id: hermes-base @@ -4710,7 +4716,7 @@ jobs: - name: Build exact all-agent protected managed images env: - BASE_DCODE: ${{ steps.bases.outputs.dcode }} + BASE_DCODE: ${{ steps.candidate-contract.outputs.dcode_source == 'candidate' && 'candidate' || steps.bases.outputs.dcode }} BASE_HERMES: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.hermes-base.outputs.digest }} BASE_OPENCLAW: ${{ steps.bases.outputs.openclaw }} CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} @@ -5092,7 +5098,6 @@ jobs: "$cached_revision" == "$CHECKOUT_SHA" && "$cached_platform" == "linux/amd64" && "$cached_hermes" == "$HERMES_BASE_REF" && - "$cached_dcode" == "$DCODE_BASE_REF" && "$(cat "$prepared_inputs")" == "$cached_revision $cached_platform $cached_openclaw $cached_hermes $cached_dcode" ]] || { echo "::error::protected build-cache identity does not match this run" >&2 exit 1 @@ -5108,17 +5113,32 @@ jobs: exit 1 } printf 'openclaw=%s\n' "$cached_openclaw" >> "$GITHUB_OUTPUT" - [[ "$DCODE_BASE_REF" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || { - echo "::error::dcode base publication returned an invalid exact reference" >&2 - exit 1 - } - dcode_digest="${DCODE_BASE_REF##*@}" - docker buildx imagetools inspect "$DCODE_BASE_REF" --raw > "$work_dir/dcode-exact.raw" - [[ "sha256:$(sha256sum "$work_dir/dcode-exact.raw" | awk '{print $1}')" == "$dcode_digest" ]] || { - echo "::error::dcode exact base bytes do not match the published digest" >&2 - exit 1 - } - printf 'dcode=%s\n' "$DCODE_BASE_REF" >> "$GITHUB_OUTPUT" + if [[ "$cached_dcode" =~ ^localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:[a-f0-9]{64}$ ]]; then + verified_dcode="$(node scripts/checks/protected-dcode-base-receipt.mts verify \ + "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base" \ + "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base-receipt.json")" + [[ "$verified_dcode" == "$cached_dcode" ]] || { + echo "::error::prepared DCode base does not match this run's verified OCI artifact" >&2 + exit 1 + } + printf 'dcode=%s\n' "$verified_dcode" >> "$GITHUB_OUTPUT" + else + [[ "$cached_dcode" == "$DCODE_BASE_REF" ]] || { + echo "::error::prepared published DCode base does not match the selected publication" >&2 + exit 1 + } + [[ "$DCODE_BASE_REF" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || { + echo "::error::dcode base publication returned an invalid exact reference" >&2 + exit 1 + } + dcode_digest="${DCODE_BASE_REF##*@}" + docker buildx imagetools inspect "$DCODE_BASE_REF" --raw > "$work_dir/dcode-exact.raw" + [[ "sha256:$(sha256sum "$work_dir/dcode-exact.raw" | awk '{print $1}')" == "$dcode_digest" ]] || { + echo "::error::dcode exact base bytes do not match the published digest" >&2 + exit 1 + } + printf 'dcode=%s\n' "$DCODE_BASE_REF" >> "$GITHUB_OUTPUT" + fi - name: Start isolated protected runtime registry shell: bash diff --git a/ci/protected-managed-image-multiarch-activation-v1.json b/ci/protected-managed-image-multiarch-activation-v1.json index 5960e13e340..f69c5afeaf3 100644 --- a/ci/protected-managed-image-multiarch-activation-v1.json +++ b/ci/protected-managed-image-multiarch-activation-v1.json @@ -1,6 +1,7 @@ { "agents": ["openclaw", "hermes", "langchain-deepagents-code"], - "contractVersion": 1, + "contractVersion": 2, "jobId": "managed-image-multiarch-startup", - "platforms": ["linux/amd64", "linux/arm64"] + "platforms": ["linux/amd64", "linux/arm64"], + "dcodeBaseSource": "candidate" } diff --git a/scripts/checks/build-protected-managed-images.sh b/scripts/checks/build-protected-managed-images.sh index 8c8fc805d97..cd9c56a9e09 100755 --- a/scripts/checks/build-protected-managed-images.sh +++ b/scripts/checks/build-protected-managed-images.sh @@ -105,7 +105,10 @@ npm_target_os="linux" npm_target_libc="glibc" [[ "$openclaw_base" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage [[ "$hermes_base" =~ ^ghcr[.]io/nvidia/nemoclaw/hermes-sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage -[[ "$dcode_base" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage +[[ "$dcode_base" == candidate || + "$dcode_base" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ || + (-n "$cache_from" && "$dcode_base" =~ ^localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:[a-f0-9]{64}$) ]] || usage +[[ "$dcode_base" != candidate || -z "$cache_from" ]] || usage prepared_identity="$revision $platform $openclaw_base $hermes_base $dcode_base" [[ "$source_root" == /* && "$source_root" != *$'\n'* && -d "$source_root" && ! -L "$source_root" ]] || usage source_root="$(cd -- "$source_root" && pwd -P)" @@ -240,6 +243,57 @@ trap restore_worktree EXIT trap 'exit 130' INT trap 'exit 143' TERM +# A PR dependency upgrade needs its own base; a published main base cannot +# satisfy the candidate's no-deps profile. Keep this build on the CPU runner +# and bind the exported OCI bytes to the exact source, platform and run. +dcode_base_layout="" +dcode_receipt_helper="$controller_root/scripts/checks/protected-dcode-base-receipt.mts" +if [[ "$dcode_base" == candidate ]]; then + [[ "$(git -C "$source_root" rev-parse --verify HEAD)" == "$revision" ]] || { + echo "ERROR: candidate base checkout does not match its revision" >&2 + exit 1 + } + git -C "$source_root" diff --quiet HEAD -- || { + echo "ERROR: candidate base checkout has tracked modifications" >&2 + exit 1 + } + dcode_base_layout="${cache_to:-$work_dir}/dcode-base" + dcode_base_receipt="${cache_to:-$work_dir}/dcode-base-receipt.json" + dcode_base_tag="localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code:${revision}" + docker buildx build \ + --file "$source_root/agents/langchain-deepagents-code/Dockerfile.base" \ + --platform "$platform" \ + --provenance=false --sbom=false \ + --label "org.opencontainers.image.source=https://github.com/NVIDIA/NemoClaw" \ + --label "org.opencontainers.image.revision=${revision}" \ + --label "io.nvidia.nemoclaw.agent=langchain-deepagents-code" \ + --label "io.nvidia.nemoclaw.managed-image.cohort=${cohort}" \ + --output "type=image,name=${dcode_base_tag},push=true,oci-mediatypes=true" \ + --output "type=oci,dest=${dcode_base_layout},tar=false" \ + "$source_root" + dcode_base="$(CHECKOUT_SHA="$revision" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT="$cohort" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM="$platform" \ + node "$dcode_receipt_helper" write "$dcode_base_layout" "$dcode_base_receipt")" + # Prove the pushed manifest and the offline artifact have the same identity. + docker buildx imagetools inspect "$dcode_base" --raw >"$work_dir/dcode-candidate-base.raw" + [[ "sha256:$(sha256sum "$work_dir/dcode-candidate-base.raw" | awk '{print $1}')" == "${dcode_base##*@}" ]] || { + echo "ERROR: candidate base registry and OCI artifact digests differ" >&2 + exit 1 + } + prepared_identity="$revision $platform $openclaw_base $hermes_base $dcode_base" +elif [[ "$dcode_base" == localhost:5000/* ]]; then + dcode_base_layout="$cache_from/dcode-base" + verified_dcode_base="$(CHECKOUT_SHA="$revision" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT="$cohort" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM="$platform" \ + node "$dcode_receipt_helper" verify "$dcode_base_layout" "$cache_from/dcode-base-receipt.json")" + [[ "$verified_dcode_base" == "$dcode_base" ]] || { + echo "ERROR: candidate base artifact does not match the prepared base reference" >&2 + exit 1 + } +fi + audit_receipt="" audit_raw_report="" audit_policy_result="" @@ -476,13 +530,18 @@ build_agent() { fi local base_digest="${base_reference##*@}" - docker buildx imagetools inspect "$base_reference" --raw >"$exact_base_raw" - local actual_base - actual_base="sha256:$(sha256sum "$exact_base_raw" | awk '{print $1}')" - [[ "$actual_base" == "$base_digest" ]] || { - echo "ERROR: ${agent} exact base bytes do not match its descriptor" >&2 - exit 1 - } + if [[ "$agent" == langchain-deepagents-code && -n "$dcode_base_layout" ]]; then + # The verified local OCI input survives deletion of the CPU job's registry. + cache_args+=(--build-context "$base_reference=oci-layout://${dcode_base_layout}@${base_digest}") + else + docker buildx imagetools inspect "$base_reference" --raw >"$exact_base_raw" + local actual_base + actual_base="sha256:$(sha256sum "$exact_base_raw" | awk '{print $1}')" + [[ "$actual_base" == "$base_digest" ]] || { + echo "ERROR: ${agent} exact base bytes do not match its descriptor" >&2 + exit 1 + } + fi scripts/check-production-build-args.sh \ -f "$dockerfile_path" \ diff --git a/scripts/checks/protected-dcode-base-receipt.mts b/scripts/checks/protected-dcode-base-receipt.mts new file mode 100644 index 00000000000..45baff29b8c --- /dev/null +++ b/scripts/checks/protected-dcode-base-receipt.mts @@ -0,0 +1,246 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +export const PROTECTED_DCODE_BASE_REPOSITORY = + "localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code"; +const SHA = /^[a-f0-9]{40}$/u; +const DIGEST = /^sha256:[a-f0-9]{64}$/u; +const COHORT = /^protected-[1-9][0-9]{0,19}-[1-9][0-9]{0,9}$/u; +const MANIFEST = "application/vnd.oci.image.manifest.v1+json"; +const CONFIG = "application/vnd.oci.image.config.v1+json"; +const LAYERS = new Set([ + "application/vnd.oci.image.layer.v1.tar", + "application/vnd.oci.image.layer.v1.tar+gzip", + "application/vnd.oci.image.layer.v1.tar+zstd", +]); + +export type ProtectedDcodeBaseIdentity = { + sourceRevision: string; + workflowSha: string; + cohort: string; + platform: "linux/amd64" | "linux/arm64"; +}; + +export type ProtectedDcodeBaseReceipt = ProtectedDcodeBaseIdentity & { + version: 1; + digest: string; + imageId: string; + reference: string; +}; + +function record(value: unknown): Record { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("protected DCode base metadata must be an object"); + } + return value as Record; +} + +function validateIdentity(identity: ProtectedDcodeBaseIdentity): void { + if ( + !SHA.test(identity.sourceRevision) || + !SHA.test(identity.workflowSha) || + !COHORT.test(identity.cohort) || + !["linux/amd64", "linux/arm64"].includes(identity.platform) + ) { + throw new Error("protected DCode base identity is invalid"); + } +} + +function regularFile(filename: string): number { + const fd = fs.openSync( + filename, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK, + ); + if (!fs.fstatSync(fd).isFile()) { + fs.closeSync(fd); + throw new Error("protected DCode base input must be a regular file"); + } + return fd; +} + +function readJson(filename: string): Record { + const fd = regularFile(filename); + try { + if (fs.fstatSync(fd).size > 8 * 1024 * 1024) { + throw new Error("protected DCode base metadata is too large"); + } + return record(JSON.parse(fs.readFileSync(fd, "utf8"))); + } finally { + fs.closeSync(fd); + } +} + +function descriptor(value: unknown, types: ReadonlySet) { + const entry = record(value); + if ( + typeof entry.digest !== "string" || + !DIGEST.test(entry.digest) || + !Number.isSafeInteger(entry.size) || + Number(entry.size) < 0 || + typeof entry.mediaType !== "string" || + !types.has(entry.mediaType) || + entry.urls !== undefined || + entry.data !== undefined + ) { + throw new Error("protected DCode base descriptor is invalid or requires external content"); + } + return { digest: entry.digest, size: Number(entry.size) }; +} + +function verifyBlob(layout: string, entry: { digest: string; size: number }, collect: true): Buffer; +function verifyBlob(layout: string, entry: { digest: string; size: number }, collect?: false): void; +function verifyBlob( + layout: string, + entry: { digest: string; size: number }, + collect = false, +): Buffer | void { + if (collect && entry.size > 8 * 1024 * 1024) { + throw new Error("protected DCode base metadata is too large"); + } + const filename = path.join(layout, "blobs", "sha256", entry.digest.slice(7)); + const fd = regularFile(filename); + const chunks: Buffer[] = []; + let total = 0; + try { + if (fs.fstatSync(fd).size !== entry.size) { + throw new Error("protected DCode base blob size does not match its descriptor"); + } + const hash = createHash("sha256"); + const buffer = Buffer.allocUnsafe(1024 * 1024); + let count: number; + while ((count = fs.readSync(fd, buffer)) !== 0) { + const bytes = buffer.subarray(0, count); + hash.update(bytes); + if (collect) chunks.push(Buffer.from(bytes)); + total += count; + } + if (total !== entry.size) { + throw new Error("protected DCode base blob size does not match its descriptor"); + } + if (`sha256:${hash.digest("hex")}` !== entry.digest) { + throw new Error("protected DCode base blob digest does not match its descriptor"); + } + } finally { + fs.closeSync(fd); + } + if (collect) return Buffer.concat(chunks, total); +} + +function verifiedJsonBlob(layout: string, entry: { digest: string; size: number }) { + return record(JSON.parse(verifyBlob(layout, entry, true).toString("utf8"))); +} + +/** Verify all OCI content before the protected runner accepts an offline base. */ +export function inspectProtectedDcodeBase( + layout: string, + expected: ProtectedDcodeBaseIdentity, +): ProtectedDcodeBaseReceipt { + validateIdentity(expected); + for (const directory of [layout, path.join(layout, "blobs"), path.join(layout, "blobs/sha256")]) { + if (!fs.lstatSync(directory).isDirectory()) { + throw new Error("protected DCode base layout directories must not be symlinks"); + } + } + if (readJson(path.join(layout, "oci-layout")).imageLayoutVersion !== "1.0.0") { + throw new Error("protected DCode base OCI layout version is invalid"); + } + const index = readJson(path.join(layout, "index.json")); + if ( + index.schemaVersion !== 2 || + !Array.isArray(index.manifests) || + index.manifests.length !== 1 + ) { + throw new Error("protected DCode base must contain one OCI image manifest"); + } + const manifestDescriptor = descriptor(index.manifests[0], new Set([MANIFEST])); + const manifest = verifiedJsonBlob(layout, manifestDescriptor); + if ( + manifest.schemaVersion !== 2 || + manifest.mediaType !== MANIFEST || + !Array.isArray(manifest.layers) + ) { + throw new Error("protected DCode base image manifest is invalid"); + } + const configDescriptor = descriptor(manifest.config, new Set([CONFIG])); + const config = verifiedJsonBlob(layout, configDescriptor); + for (const layer of manifest.layers) verifyBlob(layout, descriptor(layer, LAYERS)); + const labels = record(record(config.config).Labels); + if ( + `${config.os}/${config.architecture}` !== expected.platform || + labels["org.opencontainers.image.revision"] !== expected.sourceRevision || + labels["org.opencontainers.image.source"] !== "https://github.com/NVIDIA/NemoClaw" || + labels["io.nvidia.nemoclaw.managed-image.cohort"] !== expected.cohort || + labels["io.nvidia.nemoclaw.agent"] !== "langchain-deepagents-code" + ) { + throw new Error( + "protected DCode base config does not match the selected source, run or platform", + ); + } + return { + version: 1, + ...expected, + digest: manifestDescriptor.digest, + imageId: configDescriptor.digest, + reference: `${PROTECTED_DCODE_BASE_REPOSITORY}@${manifestDescriptor.digest}`, + }; +} + +export function verifyProtectedDcodeBaseReceipt( + layout: string, + receiptPath: string, + expected: ProtectedDcodeBaseIdentity, +): ProtectedDcodeBaseReceipt { + const receipt = readJson(receiptPath); + const actual = inspectProtectedDcodeBase(layout, expected); + const keys = Object.keys(actual) as (keyof ProtectedDcodeBaseReceipt)[]; + if ( + Object.keys(receipt).length !== keys.length || + keys.some((key) => receipt[key] !== actual[key]) + ) { + throw new Error( + "protected DCode base receipt does not match verified OCI content and dispatch identity", + ); + } + return actual; +} + +function main(): void { + const [command, layout, receiptPath, ...extra] = process.argv.slice(2); + if (!["write", "verify"].includes(command) || !layout || !receiptPath || extra.length) { + throw new Error( + "usage: protected-dcode-base-receipt.mts ", + ); + } + const expected: ProtectedDcodeBaseIdentity = { + sourceRevision: process.env.CHECKOUT_SHA ?? "", + workflowSha: process.env.NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA ?? "", + cohort: process.env.NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT ?? "", + platform: (process.env.NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM ?? + "") as ProtectedDcodeBaseIdentity["platform"], + }; + const receipt = + command === "write" + ? inspectProtectedDcodeBase(layout, expected) + : verifyProtectedDcodeBaseReceipt(layout, receiptPath, expected); + if (command === "write") { + fs.writeFileSync(receiptPath, `${JSON.stringify(receipt)}\n`, { + flag: "wx", + mode: 0o600, + }); + } + process.stdout.write(`${receipt.reference}\n`); +} + +if (path.resolve(process.argv[1] ?? "") === fileURLToPath(import.meta.url)) { + try { + main(); + } catch (error) { + console.error(error instanceof Error ? error.message : "invalid protected DCode base receipt"); + process.exitCode = 1; + } +} diff --git a/scripts/checks/protected-managed-image-contract.ts b/scripts/checks/protected-managed-image-contract.ts index f53df76a61f..50fc3474a5a 100644 --- a/scripts/checks/protected-managed-image-contract.ts +++ b/scripts/checks/protected-managed-image-contract.ts @@ -31,7 +31,8 @@ export type ProtectedManagedImageContract = { export type ProtectedManagedImageActivation = { readonly agents: readonly ShippedManagedImageAgent[]; - readonly contractVersion: 1; + readonly contractVersion: 1 | 2; + readonly dcodeBaseSource?: "candidate"; readonly jobId: typeof PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID; readonly platforms: readonly ProtectedManagedImagePlatform[]; }; @@ -137,8 +138,16 @@ function parseEntry( const basePrefix = `${BASE_REPOSITORIES[entry.agent as ShippedManagedImageAgent]}@`; if ( typeof entry.baseReference !== "string" || - !entry.baseReference.startsWith(basePrefix) || - !DIGEST_PATTERN.test(entry.baseReference.slice(basePrefix.length)) + (!( + entry.baseReference.startsWith(basePrefix) && + DIGEST_PATTERN.test(entry.baseReference.slice(basePrefix.length)) + ) && + !( + entry.agent === "langchain-deepagents-code" && + /^localhost:5000\/nemoclaw-managed-protected-base\/langchain-deepagents-code@sha256:[a-f0-9]{64}$/u.test( + entry.baseReference, + ) + )) ) { throw new Error("protected managed-image contract entry has an invalid base reference"); } @@ -180,11 +189,14 @@ export function parseProtectedManagedImageActivation( const activation = record(value); requireExactKeys( activation, - ["agents", "contractVersion", "jobId", "platforms"], + activation.contractVersion === 2 + ? ["agents", "contractVersion", "dcodeBaseSource", "jobId", "platforms"] + : ["agents", "contractVersion", "jobId", "platforms"], "protected managed-image activation", ); if ( - activation.contractVersion !== 1 || + (activation.contractVersion !== 1 && activation.contractVersion !== 2) || + (activation.contractVersion === 2 && activation.dcodeBaseSource !== "candidate") || activation.jobId !== PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID || JSON.stringify(activation.agents) !== JSON.stringify(PROTECTED_MANAGED_IMAGE_AGENTS) || JSON.stringify(activation.platforms) !== JSON.stringify(PROTECTED_MANAGED_IMAGE_PLATFORMS) @@ -193,7 +205,8 @@ export function parseProtectedManagedImageActivation( } return { agents: PROTECTED_MANAGED_IMAGE_AGENTS, - contractVersion: 1, + contractVersion: activation.contractVersion as 1 | 2, + ...(activation.contractVersion === 2 ? { dcodeBaseSource: "candidate" as const } : {}), jobId: PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID, platforms: PROTECTED_MANAGED_IMAGE_PLATFORMS, }; diff --git a/test/e2e/README.md b/test/e2e/README.md index 470c93d48c9..92159d4d76e 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -85,6 +85,15 @@ Each consumer runs the pinned preparation action with `build-cli: "false"` to in The `managed-image-multiarch-startup` no-build job keeps that setting and compiles only the candidate shared policy boundary on the host. It rejects preexisting output, verifies the required shared modules, and then starts the direct managed-image contracts. Its amd64 shard also exports digest-addressed npm and agent system inputs for the protected offline rebuild. +The trusted controller accepts both the original v1 multiarch activation and v2 +candidate Deep Agents base activation. Version 2 builds the candidate's +`agents/langchain-deepagents-code/Dockerfile.base` on the native CPU runner, +using the candidate checkout's pins and lockfile. It exports the base as OCI +content plus a receipt bound to the source SHA, trusted workflow SHA, platform, +run ID, and attempt. The protected runtime controller verifies the receipt and +every config, manifest, and layer digest before using that base offline. +It does not substitute the published main base when verification fails. +Version 1 retains its published-base behavior. The shared compiler uses native GitHub caching of `dist/` and `nemoclaw/dist/` for main CI, PR CI, and E2E candidate preparation. Its key includes the checkout SHA, trusted recipe revision, action content, Node version, and runner platform. @@ -170,6 +179,17 @@ It requires every shipped agent once, one candidate revision, one release, and o No matching successful run, invalid or duplicated run metadata, or incomplete, duplicated, mixed, or substituted artifact evidence stops before any stock-onboarding consumer starts. Manual PR E2E does not fall back to local Dockerfile builds. +Routine changes to existing dependency pins, lockfiles, and image digests use +this path policy; they do not need a new dependency registry or per-version +workflow edits. Regression cases exercise the real policy for OpenClaw, Hermes, +Deep Agents, Pi, OpenShell, and shared npm inputs. These are artifact-selection +tests, not live qualification. OpenShell's gateway-only jobs select the candidate +release through the existing trusted installer verifier. New release trust +records, controller protocols, permissions, and unsupported platforms still need +their own review. Historical upgrade fixtures keep their historical versions. +Pi retains its separate candidate contract and qualification receipts below; +selecting a shipped-agent catalog does not qualify Pi. + Unchanged runs pass the selected base revision and complete cohort receipt to every stock-onboarding consumer. Changed-input runs pass the authenticated candidate catalog separately to those consumers. The candidate CLI artifact cannot contain the catalog. diff --git a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts index 9ad0ea04bf0..c9ead3b0031 100644 --- a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts +++ b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts @@ -100,6 +100,17 @@ describe("protected managed-image runtime workflow", () => { expect(validateManagedImageProtectedRuntimeWorkflow(value)).toEqual([]); }); + it.each([ + "node scripts/checks/protected-dcode-base-receipt.mts verify", + '"$verified_dcode" == "$cached_dcode"', + '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base-receipt.json"', + ])("rejects a candidate OCI base handoff without %s", (fragment) => { + const value = workflow(); + const step = namedStep(value, "Resolve digest-pinned amd64 runtime base images"); + step.run = String(step.run).replace(fragment, "REMOVED"); + expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); + }); + it("requires cancellation cleanup for the derived Docker Engine 27 receipt daemon", () => { const value = workflow(); const cleanup = namedMultiarchStep(value, "Remove owned Docker Engine 27 receipt daemon"); diff --git a/test/e2e/support/pr-managed-image-publication.test.ts b/test/e2e/support/pr-managed-image-publication.test.ts index b2f054f6f2b..338393ec6d1 100644 --- a/test/e2e/support/pr-managed-image-publication.test.ts +++ b/test/e2e/support/pr-managed-image-publication.test.ts @@ -241,6 +241,68 @@ afterEach(() => { }); describe("exact PR managed-image publication", () => { + // Exercise the real trusted path policy, not a test-only dependency registry. + // Changing candidate pins/locks must select candidate artifacts without an + // accompanying workflow edit, and must never silently use main's cohort. + const dependencyInputs = [ + "Dockerfile", + "Dockerfile.base", + "agents/openclaw/openclaw-runtime/package-lock.json", + "agents/hermes/Dockerfile", + "agents/hermes/Dockerfile.base", + "agents/langchain-deepagents-code/requirements.lock", + "agents/langchain-deepagents-code/Dockerfile.base", + "agents/pi/pi-runtime/package-lock.json", + "nemoclaw/package-lock.json", + "tools/mcp-tool-discovery-runtime/package-lock.json", + "scripts/install-openshell.sh", + "nemoclaw-blueprint/blueprint.yaml", + ]; + const trustedWorkflowSource = fs.readFileSync( + new URL("../../../.github/workflows/base-image.yaml", import.meta.url), + "utf8", + ); + + it.each(dependencyInputs)( + "uses exact candidate artifacts when only %s changes", + async (changedPath) => { + const input = { ...resolverInput(), workflowSource: trustedWorkflowSource }; + const download = vi.fn(downloadContract); + await expect( + resolvePrManagedImageCatalog( + input, + candidateRequest({ changedPath, imageChanged: true }), + download, + ), + ).resolves.toBe("candidate-catalog"); + expect(download.mock.calls.map(([identity]) => identity.name)).toEqual( + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent) => `managed-pr-contract-${RUN_ID}-${agent}`), + ); + }, + ); + + it.each(dependencyInputs)( + "does not fall back to main when %s changes without successful candidate images", + async (changedPath) => { + const input = { ...resolverInput(), workflowSource: trustedWorkflowSource }; + const download = vi.fn(downloadContract); + await expect( + resolvePrManagedImageCatalog( + input, + candidateRequest({ + changedPath, + imageChanged: true, + run: workflowRun({ conclusion: "failure" }), + }), + download, + ), + ).rejects.toThrow( + `managed-image workflow for candidate ${CANDIDATE_SHA} must complete successfully`, + ); + expect(download).not.toHaveBeenCalled(); + }, + ); + it("keeps unchanged PRs on the authenticated base-history cohort", async () => { const input = resolverInput(); const download = vi.fn(downloadContract); diff --git a/test/e2e/support/protected-dcode-base-receipt.test.ts b/test/e2e/support/protected-dcode-base-receipt.test.ts new file mode 100644 index 00000000000..8c15a1c161e --- /dev/null +++ b/test/e2e/support/protected-dcode-base-receipt.test.ts @@ -0,0 +1,268 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + inspectProtectedDcodeBase, + verifyProtectedDcodeBaseReceipt, + type ProtectedDcodeBaseIdentity, +} from "../../../scripts/checks/protected-dcode-base-receipt.mts"; + +const directories: string[] = []; +afterEach(() => { + for (const directory of directories.splice(0)) + fs.rmSync(directory, { recursive: true, force: true }); +}); + +function fixture(platform: ProtectedDcodeBaseIdentity["platform"] = "linux/amd64") { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "protected-dcode-base-")); + directories.push(root); + const layout = path.join(root, "base"); + fs.mkdirSync(path.join(layout, "blobs/sha256"), { recursive: true }); + const expected: ProtectedDcodeBaseIdentity = { + sourceRevision: "a".repeat(40), + workflowSha: "b".repeat(40), + cohort: "protected-37164014229-1", + platform, + }; + function blob(body: Buffer, mediaType: string) { + const digest = `sha256:${createHash("sha256").update(body).digest("hex")}`; + fs.writeFileSync(path.join(layout, "blobs/sha256", digest.slice(7)), body); + return { digest, size: body.length, mediaType }; + } + function jsonBlob(value: unknown, mediaType: string) { + return blob(Buffer.from(JSON.stringify(value)), mediaType); + } + const config = jsonBlob( + { + os: "linux", + architecture: platform.slice(6), + config: { + Labels: { + "org.opencontainers.image.revision": expected.sourceRevision, + "org.opencontainers.image.source": "https://github.com/NVIDIA/NemoClaw", + "io.nvidia.nemoclaw.managed-image.cohort": expected.cohort, + "io.nvidia.nemoclaw.agent": "langchain-deepagents-code", + }, + }, + }, + "application/vnd.oci.image.config.v1+json", + ); + const layer = blob( + Buffer.alloc(2 * 1024 * 1024 + 7, 42), + "application/vnd.oci.image.layer.v1.tar", + ); + const manifest = { + schemaVersion: 2, + mediaType: "application/vnd.oci.image.manifest.v1+json", + config, + layers: [layer], + }; + function setManifest(value: unknown) { + const descriptor = jsonBlob(value, "application/vnd.oci.image.manifest.v1+json"); + fs.writeFileSync( + path.join(layout, "index.json"), + JSON.stringify({ schemaVersion: 2, manifests: [descriptor] }), + ); + return descriptor; + } + const descriptor = setManifest(manifest); + fs.writeFileSync( + path.join(layout, "oci-layout"), + JSON.stringify({ imageLayoutVersion: "1.0.0" }), + ); + const receiptPath = path.join(root, "receipt.json"); + const receipt = inspectProtectedDcodeBase(layout, expected); + fs.writeFileSync(receiptPath, JSON.stringify(receipt)); + return { + layout, + root, + expected, + receiptPath, + receipt, + layer, + config, + manifest, + descriptor, + setManifest, + }; +} + +describe("protected DCode base artifact handoff", () => { + it("writes receipts once and refuses to overwrite existing evidence", () => { + const f = fixture(); + const receiptPath = path.join(f.root, "cli-receipt.json"); + const args = [ + fileURLToPath( + new URL("../../../scripts/checks/protected-dcode-base-receipt.mts", import.meta.url), + ), + "write", + f.layout, + receiptPath, + ]; + const options = { + encoding: "utf8" as const, + env: { + ...process.env, + CHECKOUT_SHA: f.expected.sourceRevision, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA: f.expected.workflowSha, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT: f.expected.cohort, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM: f.expected.platform, + }, + }; + const first = spawnSync(process.execPath, args, options); + expect(first.status, first.stderr).toBe(0); + expect(first.stdout.trim()).toBe(f.receipt.reference); + const receiptFd = fs.openSync(receiptPath, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW); + try { + const opened = fs.fstatSync(receiptFd); + expect(opened.mode & 0o777).toBe(0o600); + const bytes = fs.readFileSync(receiptFd); + const second = spawnSync(process.execPath, args, options); + expect(second.status, second.stderr).toBe(1); + expect(second.stderr).toContain("EEXIST"); + const afterStat = fs.fstatSync(receiptFd); + expect(afterStat.size).toBe(bytes.length); + const after = Buffer.alloc(bytes.length); + expect(fs.readSync(receiptFd, after, 0, after.length, 0)).toBe(bytes.length); + expect(after).toEqual(bytes); + const pathStat = fs.lstatSync(receiptPath); + expect([pathStat.dev, pathStat.ino]).toEqual([opened.dev, opened.ino]); + } finally { + fs.closeSync(receiptFd); + } + }); + + it.each(["linux/amd64", "linux/arm64"] as const)( + "binds the complete OCI image on %s", + (platform) => { + const f = fixture(platform); + expect(verifyProtectedDcodeBaseReceipt(f.layout, f.receiptPath, f.expected)).toEqual( + f.receipt, + ); + expect(f.receipt.digest).toBe(f.descriptor.digest); + expect(f.receipt.imageId).toBe(f.config.digest); + expect(f.receipt.reference).toBe( + `localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@${f.descriptor.digest}`, + ); + }, + ); + + it.each([ + { sourceRevision: "c".repeat(40) }, + { workflowSha: "d".repeat(40) }, + { cohort: "protected-37164014229-2" }, + { cohort: "protected-37164014230-1" }, + { platform: "linux/arm64" as const }, + ])("rejects reuse across a different dispatch identity: %j", (change) => { + const f = fixture(); + expect(() => + verifyProtectedDcodeBaseReceipt(f.layout, f.receiptPath, { ...f.expected, ...change }), + ).toThrow(); + }); + + it.each(["digest", "imageId", "reference", "unexpected"])( + "rejects substituted receipt field %s", + (field) => { + const f = fixture(); + fs.writeFileSync(f.receiptPath, JSON.stringify({ ...f.receipt, [field]: "substituted" })); + expect(() => verifyProtectedDcodeBaseReceipt(f.layout, f.receiptPath, f.expected)).toThrow( + /receipt/, + ); + }, + ); + + it.each([ + { + kind: "corrupt", + mutate: (filename: string, _f: ReturnType) => { + const fd = fs.openSync(filename, "r+"); + fs.writeSync(fd, Buffer.from([0]), 0, 1, 1024 * 1024 + 2); + fs.closeSync(fd); + }, + }, + { + kind: "truncate", + mutate: (filename: string, f: ReturnType) => { + fs.truncateSync(filename, f.layer.size - 1); + }, + }, + { + kind: "missing", + mutate: (filename: string, f: ReturnType) => { + fs.renameSync(filename, path.join(f.root, "outside")); + }, + }, + { + kind: "symlink", + mutate: (filename: string, f: ReturnType) => { + fs.renameSync(filename, path.join(f.root, "outside")); + fs.symlinkSync(path.join(f.root, "outside"), filename); + }, + }, + ])("rejects a $kind layer before using its image", ({ mutate }) => { + const f = fixture(); + const filename = path.join(f.layout, "blobs/sha256", f.layer.digest.slice(7)); + mutate(filename, f); + expect(() => verifyProtectedDcodeBaseReceipt(f.layout, f.receiptPath, f.expected)).toThrow(); + }); + + it("rejects a remote layer even when its local bytes match", () => { + const f = fixture(); + f.setManifest({ + ...f.manifest, + layers: [{ ...f.layer, urls: ["https://example.invalid/layer"] }], + }); + expect(() => inspectProtectedDcodeBase(f.layout, f.expected)).toThrow(/external content/); + }); + + it("does not accept a manifest swapped after its bytes are verified", () => { + const f = fixture(); + const manifestPath = path.join(f.layout, "blobs/sha256", f.descriptor.digest.slice(7)); + const layerPath = path.join(f.layout, "blobs/sha256", f.layer.digest.slice(7)); + const manifestInode = fs.statSync(manifestPath).ino; + const originalClose = fs.closeSync.bind(fs); + let swapped = false; + const close = vi.spyOn(fs, "closeSync"); + close.mockImplementationOnce(originalClose).mockImplementationOnce(originalClose); + close.mockImplementationOnce((fd) => { + expect(fs.fstatSync(fd).ino).toBe(manifestInode); + originalClose(fd); + fs.renameSync(manifestPath, path.join(f.root, "original-manifest")); + fs.writeFileSync(manifestPath, JSON.stringify({ ...f.manifest, layers: [] })); + fs.truncateSync(layerPath, 1); + swapped = true; + }); + try { + expect(() => inspectProtectedDcodeBase(f.layout, f.expected)).toThrow(/blob size/); + expect(swapped).toBe(true); + } finally { + close.mockRestore(); + } + }); + + it("rejects symlinked receipt and blob directories", () => { + const f = fixture(); + fs.renameSync(f.receiptPath, path.join(f.root, "real-receipt")); + fs.symlinkSync(path.join(f.root, "real-receipt"), f.receiptPath); + expect(() => verifyProtectedDcodeBaseReceipt(f.layout, f.receiptPath, f.expected)).toThrow(); + fs.renameSync(path.join(f.layout, "blobs"), path.join(f.root, "real-blobs")); + fs.symlinkSync(path.join(f.root, "real-blobs"), path.join(f.layout, "blobs")); + expect(() => inspectProtectedDcodeBase(f.layout, f.expected)).toThrow(/symlinks/); + }); + + it("rejects ambiguous multi-image indexes", () => { + const f = fixture(); + fs.writeFileSync( + path.join(f.layout, "index.json"), + JSON.stringify({ schemaVersion: 2, manifests: [f.descriptor, f.descriptor] }), + ); + expect(() => inspectProtectedDcodeBase(f.layout, f.expected)).toThrow(/one OCI image/); + }); +}); diff --git a/test/e2e/support/shared-e2e-workflow-boundary.test.ts b/test/e2e/support/shared-e2e-workflow-boundary.test.ts index b4ec18f913d..6b288a60058 100644 --- a/test/e2e/support/shared-e2e-workflow-boundary.test.ts +++ b/test/e2e/support/shared-e2e-workflow-boundary.test.ts @@ -562,6 +562,7 @@ describe("pre-candidate execution environment identity", () => { { owner: owners[4]!, bindingName: "CANDIDATE_SHA" }, { owner: owners[6]!, bindingName: "GITHUB_TOKEN" }, { owner: owners[11]!, bindingName: "NEMOCLAW_E2E_CREDENTIALS_ALLOWED" }, + { owner: owners[11]!, bindingName: "NEMOCLAW_E2E_INCLUDE_STAGING_BREV_LAUNCHABLE" }, ]; const bindingChanges = [ { @@ -581,7 +582,7 @@ describe("pre-candidate execution environment identity", () => { boundOwners.flatMap(({ owner, bindingName }) => bindingChanges.map((change) => ({ ...owner, bindingName, ...change })), ), - )("rejects $label binding in $name", ({ name, select, bindingName, apply }) => { + )("rejects $label $bindingName binding in $name", ({ name, select, bindingName, apply }) => { const errors = validateMutatedWorkflow((workflow) => { apply(select(workflow).env as Record, bindingName); }); diff --git a/test/e2e/support/stock-managed-image-workflow-boundary.test.ts b/test/e2e/support/stock-managed-image-workflow-boundary.test.ts index 06880fe3f04..4210c6e04ac 100644 --- a/test/e2e/support/stock-managed-image-workflow-boundary.test.ts +++ b/test/e2e/support/stock-managed-image-workflow-boundary.test.ts @@ -78,12 +78,12 @@ describe("stock onboarding managed-image publication boundary", () => { }, ); - it("blocks matrix generation when any publication architecture fails", () => { + it("plans image prerequisites before waiting for publication", () => { const value = workflow(); - value.jobs["generate-matrix"].needs = []; + value.jobs["generate-matrix"].needs = ["base-image-publication"]; expect(validateBaseImagePublicationGate(value)).toContain( - "generate-matrix must wait for complete managed-image publication", + "generate-matrix must not wait for managed-image publication", ); }); }); diff --git a/test/e2e/support/workflow-plan-launchable.test.ts b/test/e2e/support/workflow-plan-launchable.test.ts new file mode 100644 index 00000000000..ccf8904ceb7 --- /dev/null +++ b/test/e2e/support/workflow-plan-launchable.test.ts @@ -0,0 +1,105 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import { + buildE2eWorkflowPlan, + releaseRequiredWorkflowJobs, + renderE2eWorkflowPlanSummary, + validateE2eWorkflowPlan, + writeE2eWorkflowPlanCiOutput, +} from "../../../tools/e2e/workflow-plan.mts"; +import { expectedWorkflowPlanCiOutput } from "./workflow-plan-test-assertions.ts"; + +vi.setConfig({ maxConcurrency: 4, testTimeout: 35_000 }); + +describe("E2E workflow plan Launchable selection", () => { + it("includes staging only when the execution plan selects it (#9167)", () => { + const stagingPlan = buildE2eWorkflowPlan( + { jobs: "staging-brev-launchable" }, + { includeStagingBrevLaunchable: false }, + ); + + expect(stagingPlan.selectedJobs).toEqual(["staging-brev-launchable"]); + expect(stagingPlan.coverageMatrix).toEqual([ + expect.objectContaining({ id: "staging-brev-launchable", source: "staging" }), + ]); + + const hermesPlan = buildE2eWorkflowPlan({ jobs: "hermes-e2e" }); + const stagingRow = buildE2eWorkflowPlan().coverageMatrix.find( + (row) => row.id === "staging-brev-launchable", + )!; + expect(() => + validateE2eWorkflowPlan({ + ...hermesPlan, + coverageMatrix: [stagingRow, ...hermesPlan.coverageMatrix], + }), + ).toThrow("execution coverage that does not match its execution plan"); + }); + + it.each(["tools/e2e/brev-launchable-e2e.sh", ".github/workflows/e2e.yaml"])( + "excludes opted-out Launchable from changed-file execution for %s without reducing the release floor", + (changedFile) => { + const options = { changedFiles: [changedFile] }; + const baseline = buildE2eWorkflowPlan({}, options); + const plan = buildE2eWorkflowPlan({}, { ...options, includeStagingBrevLaunchable: false }); + expect(baseline.selectedJobs).toContain("staging-brev-launchable"); + expect(plan.selectedJobs).toEqual( + baseline.selectedJobs.filter((job) => job !== "staging-brev-launchable"), + ); + expect(plan.runtimeProvidersByJob).not.toHaveProperty("staging-brev-launchable"); + expect(plan.coverageMatrix.some((row) => row.id === "staging-brev-launchable")).toBe(false); + expect(releaseRequiredWorkflowJobs()).toContain("staging-brev-launchable"); + expect(() => validateE2eWorkflowPlan(plan)).not.toThrow(); + }, + ); + + it.each([false, true])( + "includes every catalogue profile and respects Launchable opt-in %s for an authorized candidate", + (includeStagingBrevLaunchable) => { + const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-workflow-plan-pr-")); + const output = path.join(directory, "github-output"); + const summary = path.join(directory, "summary.md"); + const plan = buildE2eWorkflowPlan({}, { includeStagingBrevLaunchable }); + try { + writeE2eWorkflowPlanCiOutput( + {}, + { + GITHUB_OUTPUT: output, + GITHUB_STEP_SUMMARY: summary, + INFERENCE_MODE: "mock", + NEMOCLAW_E2E_CREDENTIALS_ALLOWED: "true", + NEMOCLAW_E2E_EXPECTED_SHA: "a".repeat(40), + NEMOCLAW_E2E_INCLUDE_STAGING_BREV_LAUNCHABLE: String(includeStagingBrevLaunchable), + }, + ); + + const outputs = Object.fromEntries( + readFileSync(output, "utf8") + .trim() + .split("\n") + .map((line) => { + const separator = line.indexOf("="); + return [line.slice(0, separator), line.slice(separator + 1)]; + }), + ); + expect(JSON.parse(outputs.selected_workflow_jobs).includes("staging-brev-launchable")).toBe( + includeStagingBrevLaunchable, + ); + expect(JSON.parse(outputs.release_required_jobs)).toContain("staging-brev-launchable"); + expect(plan.coverageMatrix.some((row) => row.id === "staging-brev-launchable")).toBe( + includeStagingBrevLaunchable, + ); + expect(readFileSync(output, "utf8")).toBe(expectedWorkflowPlanCiOutput(plan)); + expect(readFileSync(summary, "utf8")).toBe(renderE2eWorkflowPlanSummary(plan)); + } finally { + rmSync(directory, { force: true, recursive: true }); + } + }, + ); +}); diff --git a/test/e2e/support/workflow-plan.test.ts b/test/e2e/support/workflow-plan.test.ts index 6567b814735..29562c3139b 100644 --- a/test/e2e/support/workflow-plan.test.ts +++ b/test/e2e/support/workflow-plan.test.ts @@ -201,26 +201,6 @@ describe("E2E workflow plan", () => { ); }); - it("includes staging only when the execution plan selects it (#9167)", () => { - const stagingPlan = buildE2eWorkflowPlan({ jobs: "staging-brev-launchable" }); - - expect(stagingPlan.selectedJobs).toEqual(["staging-brev-launchable"]); - expect(stagingPlan.coverageMatrix).toEqual([ - expect.objectContaining({ id: "staging-brev-launchable", source: "staging" }), - ]); - - const hermesPlan = buildE2eWorkflowPlan({ jobs: "hermes-e2e" }); - const stagingRow = buildE2eWorkflowPlan().coverageMatrix.find( - (row) => row.id === "staging-brev-launchable", - )!; - expect(() => - validateE2eWorkflowPlan({ - ...hermesPlan, - coverageMatrix: [stagingRow, ...hermesPlan.coverageMatrix], - }), - ).toThrow("execution coverage that does not match its execution plan"); - }); - it("selects the Launchable identity smoke only when named explicitly (#9925)", () => { const plan = buildE2eWorkflowPlan({ jobs: "staging-brev-launchable-identity" }); @@ -613,30 +593,6 @@ describe("E2E workflow plan", () => { }, ); - it("includes every catalogue profile for an authorized NVIDIA-owned candidate", () => { - const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-workflow-plan-pr-")); - const output = path.join(directory, "github-output"); - const summary = path.join(directory, "summary.md"); - const plan = buildE2eWorkflowPlan(); - try { - writeE2eWorkflowPlanCiOutput( - {}, - { - GITHUB_OUTPUT: output, - GITHUB_STEP_SUMMARY: summary, - INFERENCE_MODE: "mock", - NEMOCLAW_E2E_CREDENTIALS_ALLOWED: "true", - NEMOCLAW_E2E_EXPECTED_SHA: "a".repeat(40), - }, - ); - - expect(readFileSync(output, "utf8")).toBe(expectedWorkflowPlanCiOutput(plan)); - expect(readFileSync(summary, "utf8")).toBe(renderE2eWorkflowPlanSummary(plan)); - } finally { - rmSync(directory, { force: true, recursive: true }); - } - }); - it("uses the explicit Podman planner in the CI output path", () => { const directory = mkdtempSync(path.join(tmpdir(), "nemoclaw-workflow-plan-podman-")); const output = path.join(directory, "github-output"); diff --git a/test/platform/images/protected-managed-image-build-script.test.ts b/test/platform/images/protected-managed-image-build-script.test.ts index d42949a3775..f24590baff9 100644 --- a/test/platform/images/protected-managed-image-build-script.test.ts +++ b/test/platform/images/protected-managed-image-build-script.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { chmodSync, existsSync, @@ -57,8 +58,20 @@ set -euo pipefail printf '%s\n' "$*" >>"$NEMOCLAW_TEST_DOCKER_LOG" printf '%s\n' "\${BUILDX_CONFIG:-}" >>"$NEMOCLAW_TEST_BUILDX_CONFIG_LOG" case "$*" in + "buildx imagetools inspect localhost:5000/nemoclaw-managed-protected-base/"*) + cat "$NEMOCLAW_TEST_BASE_MANIFEST" + ;; "buildx imagetools inspect "*) printf '{}\n' ;; "buildx build "*) + if [[ "$*" == *"/Dockerfile.base "* ]]; then + for argument in "$@"; do + if [[ "$argument" == type=oci,dest=*,tar=false ]]; then + destination="\${argument#type=oci,dest=}" + destination="\${destination%,tar=false}" + cp -R "$NEMOCLAW_TEST_BASE_LAYOUT" "$destination" + fi + done + fi build_count=0 if [[ -f "$NEMOCLAW_TEST_DOCKER_BUILD_COUNT" ]]; then read -r build_count <"$NEMOCLAW_TEST_DOCKER_BUILD_COUNT" @@ -112,12 +125,24 @@ case "$*" in esac `, ); - writeExecutable("sha256sum", `#!/usr/bin/env bash\nprintf '%s %s\\n' '${DIGEST}' "$1"\n`); + writeExecutable( + "sha256sum", + `#!/usr/bin/env bash +if [[ "$1" == */dcode-candidate-base.raw ]]; then + PATH="$NEMOCLAW_TEST_REAL_PATH" command sha256sum "$@" +else + printf '%s %s\\n' '${DIGEST}' "$1" +fi +`, + ); writeExecutable( "node", `#!/usr/bin/env bash set -euo pipefail printf '%s\n' "$*" >>"$NEMOCLAW_TEST_SEED_LOG" +if [[ "$1" == */scripts/checks/protected-dcode-base-receipt.mts ]]; then + exec "$NEMOCLAW_TEST_REAL_NODE" "$@" +fi if [[ "$*" == *"/scripts/lib/npm-audit-receipt.mts"* ]]; then while (($# > 0)); do if [[ "$1" == "--result" && "$NEMOCLAW_TEST_RECEIPT_VERIFY_STATUS" == 0 ]]; then @@ -205,6 +230,66 @@ function completeAuditEvidence(auditDirectory: string): void { writeFileSync(path.join(auditDirectory, "mcporter-runtime.raw.json"), '{"metadata":{}}\n'); } +// Docker is the stubbed process boundary; the production receipt CLI still +// hashes and validates every byte exported by this synthetic builder fixture. +function candidateBaseFixture(platform = "linux/amd64") { + const layout = path.join(testRoot, "base-fixture"); + mkdirSync(path.join(layout, "blobs/sha256"), { recursive: true }); + function blob(value: unknown, mediaType: string) { + const bytes = Buffer.from(JSON.stringify(value)); + const digest = `sha256:${createHash("sha256").update(bytes).digest("hex")}`; + writeFileSync(path.join(layout, "blobs/sha256", digest.slice(7)), bytes); + return { digest, size: bytes.length, mediaType }; + } + const config = blob( + { + os: "linux", + architecture: platform.slice(6), + config: { + Labels: { + "org.opencontainers.image.revision": REVISION, + "org.opencontainers.image.source": "https://github.com/NVIDIA/NemoClaw", + "io.nvidia.nemoclaw.agent": "langchain-deepagents-code", + "io.nvidia.nemoclaw.managed-image.cohort": "protected-1-1", + }, + }, + }, + "application/vnd.oci.image.config.v1+json", + ); + const manifest = blob( + { + schemaVersion: 2, + mediaType: "application/vnd.oci.image.manifest.v1+json", + config, + layers: [blob("synthetic layer", "application/vnd.oci.image.layer.v1.tar")], + }, + "application/vnd.oci.image.manifest.v1+json", + ); + writeFileSync( + path.join(layout, "index.json"), + JSON.stringify({ schemaVersion: 2, manifests: [manifest] }), + ); + writeFileSync(path.join(layout, "oci-layout"), JSON.stringify({ imageLayoutVersion: "1.0.0" })); + writeExecutable( + "git", + `#!/usr/bin/env bash +case "$*" in + *"rev-parse --verify HEAD") printf '%s\\n' "\${NEMOCLAW_TEST_GIT_HEAD:-${REVISION}}" ;; + *"diff --quiet HEAD --") exit "\${NEMOCLAW_TEST_GIT_DIRTY:-0}" ;; + *) exit 97 ;; +esac +`, + ); + return { + reference: `localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@${manifest.digest}`, + environment: { + NEMOCLAW_TEST_BASE_LAYOUT: layout, + NEMOCLAW_TEST_BASE_MANIFEST: path.join(layout, "blobs/sha256", manifest.digest.slice(7)), + NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA: "c".repeat(40), + }, + }; +} + function completeSourceBoundary(sourceRoot: string): void { mkdirSync(path.join(sourceRoot, "nemoclaw"), { recursive: true }); mkdirSync(path.join(sourceRoot, "scripts", "checks"), { recursive: true }); @@ -313,6 +398,7 @@ function runBuild( NEMOCLAW_TEST_REGISTRY_LOG: registryLog, NEMOCLAW_TEST_REGISTRY_STATUS: registryStatus, NEMOCLAW_TEST_REAL_PATH: process.env.PATH ?? "", + NEMOCLAW_TEST_REAL_NODE: process.execPath, NEMOCLAW_TEST_RECEIPT_VERIFY_STATUS: receiptVerifyStatus, NEMOCLAW_TEST_SEED_LOG: seedLog, NEMOCLAW_TEST_TEE_FAILURE_MODE: teeFailureMode, @@ -351,6 +437,108 @@ afterEach(() => { rmSync(testRoot, { force: true, recursive: true }); }); +describe("protected candidate DCode base handoff", () => { + it.each(["linux/amd64", "linux/arm64"])( + "exports a verified base and consumes it offline on %s", + (platform) => { + stubBuildInvocation(); + const fixture = candidateBaseFixture(platform); + const cache = path.join(testRoot, "candidate-cache"); + const source = path.join(testRoot, "candidate-source"); + completeSourceBoundary(source); + const produced = runBuild( + source, + ["--dcode-base", "candidate", "--cache-to", cache], + platform, + fixture.environment, + ); + expect(produced.status, produced.stderr).toBe(0); + const realCache = realpathSync(cache); + expect(readFileSync(path.join(cache, "prepared-inputs"), "utf8")).toBe( + `${REVISION} ${platform} ${OPENCLAW_BASE} ${HERMES_BASE} ${fixture.reference}\n`, + ); + const receipt = JSON.parse(readFileSync(path.join(cache, "dcode-base-receipt.json"), "utf8")); + expect(receipt).toMatchObject({ + reference: fixture.reference, + platform, + sourceRevision: REVISION, + workflowSha: "c".repeat(40), + cohort: "protected-1-1", + }); + const baseBuild = recordedBuildInvocations()[0]; + expect(baseBuild).toContain(`/Dockerfile.base --platform ${platform}`); + expect(baseBuild).toContain(`--output type=oci,dest=${realCache}/dcode-base,tar=false`); + expect(baseBuild).toContain( + `--output type=image,name=localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code:${REVISION},push=true,oci-mediatypes=true`, + ); + expect(baseBuild).not.toContain("ghcr.io"); + + completeImportedAgentCaches(cache); + const audit = path.join(testRoot, "audit"); + completeAuditEvidence(audit); + writeFileSync(dockerLog, ""); + const consumed = runBuild( + source, + ["--dcode-base", fixture.reference, "--cache-from", cache, "--audit-evidence-from", audit], + platform, + fixture.environment, + ); + expect(consumed.status, consumed.stderr).toBe(0); + const builds = recordedBuildInvocations(); + expect(builds).toHaveLength(3); + expect(builds.every((line) => line.includes("--network none"))).toBe(true); + expect(recordedBuildInvocation("langchain-deepagents-code")).toContain( + `--build-context ${fixture.reference}=oci-layout://${realCache}/dcode-base@${receipt.digest}`, + ); + const calls = readFileSync(dockerLog, "utf8"); + expect(calls).not.toContain("/Dockerfile.base"); + expect(calls).not.toContain(`buildx imagetools inspect ${fixture.reference}`); + + // A receipt from another controller revision must fail before Docker, + // rather than silently selecting the published main base. + writeFileSync(dockerLog, ""); + const rejected = runBuild( + source, + ["--dcode-base", fixture.reference, "--cache-from", cache, "--audit-evidence-from", audit], + platform, + { ...fixture.environment, NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA: "d".repeat(40) }, + ); + expect(rejected.status, rejected.stderr).toBe(1); + expect(rejected.stderr).toContain("receipt does not match"); + expect(readFileSync(dockerLog, "utf8")).toBe(""); + }, + ); + + it.each([ + [{ NEMOCLAW_TEST_GIT_HEAD: "d".repeat(40) }, "does not match its revision"], + [{ NEMOCLAW_TEST_GIT_DIRTY: "1" }, "tracked modifications"], + ] as const)("rejects an unbound candidate checkout %j", (change, diagnostic) => { + stubBuildInvocation(); + const fixture = candidateBaseFixture(); + const result = runBuild(REPO_ROOT, ["--dcode-base", "candidate"], "linux/amd64", { + ...fixture.environment, + ...change, + }); + expect(result.status, result.stderr).toBe(1); + expect(result.stderr).toContain(diagnostic); + expect(existsSync(dockerLog)).toBe(false); + }); + + it("rejects different registry and OCI manifests before building managed images", () => { + stubBuildInvocation(); + const fixture = candidateBaseFixture(); + const mismatch = path.join(testRoot, "different-manifest"); + writeFileSync(mismatch, "{}"); + const result = runBuild(REPO_ROOT, ["--dcode-base", "candidate"], "linux/amd64", { + ...fixture.environment, + NEMOCLAW_TEST_BASE_MANIFEST: mismatch, + }); + expect(result.status, result.stderr).toBe(1); + expect(result.stderr).toContain("registry and OCI artifact digests differ"); + expect(recordedBuildInvocations()).toHaveLength(1); + }); +}); + describe("protected managed-image source-root boundary", () => { it("accepts one absolute non-symlink source root before invoking Docker", () => { const sourceRoot = path.join(testRoot, "candidate"); diff --git a/test/platform/images/protected-managed-image-contract.test.ts b/test/platform/images/protected-managed-image-contract.test.ts index 96f4c1c5bef..b6e05236574 100644 --- a/test/platform/images/protected-managed-image-contract.test.ts +++ b/test/platform/images/protected-managed-image-contract.test.ts @@ -223,6 +223,63 @@ describe("protected managed-image build contract", () => { ).toThrow("activation contract is invalid"); }); + it("accepts an immutable isolated candidate base for DCode", () => { + const localBase = `localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:${"d".repeat(64)}`; + const valid = contracts("linux/amd64").map((entry) => + entry.agent === "langchain-deepagents-code" ? { ...entry, baseReference: localBase } : entry, + ); + expect(parseProtectedManagedImageContracts(valid, "linux/amd64")).toEqual(valid); + }); + + it.each(["openclaw", "hermes"])("rejects a candidate DCode base for %s", (agent) => { + const localBase = `localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:${"d".repeat(64)}`; + const wrongAgent = contracts("linux/amd64").map((entry) => + entry.agent === agent ? { ...entry, baseReference: localBase } : entry, + ); + expect(() => parseProtectedManagedImageContracts(wrongAgent, "linux/amd64")).toThrow( + /base reference/, + ); + }); + + it.each([ + `example.com/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:${"d".repeat(64)}`, + "localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code:latest", + ])("rejects an untrusted or mutable candidate base %s", (invalid) => { + const wrongReference = contracts("linux/amd64").map((entry) => + entry.agent === "langchain-deepagents-code" ? { ...entry, baseReference: invalid } : entry, + ); + expect(() => parseProtectedManagedImageContracts(wrongReference, "linux/amd64")).toThrow( + /base reference/, + ); + }); + + it("accepts candidate-base activation with the explicit version 2 contract", () => { + const activation = { + agents: PROTECTED_MANAGED_IMAGE_AGENTS, + contractVersion: 2, + dcodeBaseSource: "candidate", + jobId: PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID, + platforms: PROTECTED_MANAGED_IMAGE_PLATFORMS, + }; + expect(parseProtectedManagedImageActivation(activation)).toEqual(activation); + }); + + it.each([ + { contractVersion: "2", dcodeBaseSource: "candidate" }, + { contractVersion: 1, dcodeBaseSource: "candidate" }, + { contractVersion: 2, dcodeBaseSource: "latest" }, + { contractVersion: 2, dcodeBaseSource: undefined }, + ])("rejects invalid candidate-base activation %j", (invalid) => { + expect(() => + parseProtectedManagedImageActivation({ + agents: PROTECTED_MANAGED_IMAGE_AGENTS, + jobId: PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID, + platforms: PROTECTED_MANAGED_IMAGE_PLATFORMS, + ...invalid, + }), + ).toThrow(); + }); + it("ships the exact activation contract consumed by the trusted lane (#7744)", () => { const activation = JSON.parse( readFileSync(PROTECTED_MANAGED_IMAGE_ACTIVATION_PATH, "utf8"), @@ -230,7 +287,8 @@ describe("protected managed-image build contract", () => { expect(parseProtectedManagedImageActivation(activation)).toEqual({ agents: PROTECTED_MANAGED_IMAGE_AGENTS, - contractVersion: 1, + contractVersion: 2, + dcodeBaseSource: "candidate", jobId: PROTECTED_MANAGED_IMAGE_MULTIARCH_JOB_ID, platforms: PROTECTED_MANAGED_IMAGE_PLATFORMS, }); diff --git a/tools/e2e/managed-image-multiarch-workflow-boundary.mts b/tools/e2e/managed-image-multiarch-workflow-boundary.mts index aefff43ea73..fcfbceba55c 100644 --- a/tools/e2e/managed-image-multiarch-workflow-boundary.mts +++ b/tools/e2e/managed-image-multiarch-workflow-boundary.mts @@ -62,7 +62,7 @@ const REVIEWED_EXECUTION_STEP_NAMES = [ "Run every exact managed-image contract directly", ] as const; const REVIEWED_EXECUTION_SURFACE_SHA256 = - "3838afa4f7e9fd98e182a5dc320a122751981a26c606732f240b5edb65ffcf16"; + "8a44ba348ebc4a839b91006a3b385506706b8c072b0d634251fd9a6670ff8458"; const SHARED_POLICY_BOUNDARY_RUN = [ "set -euo pipefail", "[[ ! -e nemoclaw/dist && ! -L nemoclaw/dist ]] || {", @@ -357,6 +357,8 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): } const activation = requireStep(errors, steps, "Validate candidate activation contract"); + if (activation?.id !== "candidate-contract") + errors.push(`${JOB_ID} activation must bind the DCode base source`); requireFragments(errors, activation, [ `activation="${ACTIVATION_PATH}"`, '[[ "$(git rev-parse --verify HEAD)" == "$CHECKOUT_SHA" ]]', @@ -364,6 +366,10 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): '(keys | sort) == ["agents", "contractVersion", "jobId", "platforms"]', '.agents == ["openclaw", "hermes", "langchain-deepagents-code"]', '.platforms == ["linux/amd64", "linux/arm64"]', + ".contractVersion == 1", + '.contractVersion == 2 and .dcodeBaseSource == "candidate"', + '(keys | sort) == ["agents", "contractVersion", "dcodeBaseSource", "jobId", "platforms"]', + "dcode_source=%s", ]); const hermesBase = requireStep(errors, steps, "Resolve reviewed Hermes platform base image"); @@ -428,6 +434,10 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): ]); const build = requireStep(errors, steps, "Build exact all-agent protected managed images"); + requireValues(errors, `${JOB_ID} candidate base selection`, record(build?.env), { + BASE_DCODE: + "${{ steps.candidate-contract.outputs.dcode_source == 'candidate' && 'candidate' || steps.bases.outputs.dcode }}", + }); requireFragments(errors, build, [ "scripts/checks/build-protected-managed-images.sh", '--revision "$CHECKOUT_SHA"', diff --git a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts index a93a2795cdb..857b68ba756 100644 --- a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts +++ b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts @@ -315,6 +315,11 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR '"$cached_platform" == "linux/amd64"', '"$cached_hermes" == "$HERMES_BASE_REF"', '"$cached_dcode" == "$DCODE_BASE_REF"', + "node scripts/checks/protected-dcode-base-receipt.mts verify", + '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base"', + '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base-receipt.json"', + '"$verified_dcode" == "$cached_dcode"', + 'printf \'dcode=%s\\n\' "$verified_dcode" >> "$GITHUB_OUTPUT"', '"$(cat "$prepared_inputs")" == "$cached_revision $cached_platform $cached_openclaw $cached_hermes $cached_dcode"', '[[ "$cached_openclaw" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]]', 'openclaw_digest="${cached_openclaw##*@}"', diff --git a/tools/e2e/pre-candidate-workflow-contract.mts b/tools/e2e/pre-candidate-workflow-contract.mts index 6acb6db6984..574d2614292 100644 --- a/tools/e2e/pre-candidate-workflow-contract.mts +++ b/tools/e2e/pre-candidate-workflow-contract.mts @@ -61,6 +61,8 @@ export const PRE_CANDIDATE_STEP_ENV: Readonly FULL_SUITE_OWNING_PATHS.some((owner) => pathMatches(file, owner))) ) { - const plan = buildE2eWorkflowPlan(selectors, { gatewayRuntimes }); + const plan = buildE2eWorkflowPlan(selectors, { + gatewayRuntimes, + includeStagingBrevLaunchable: options.includeStagingBrevLaunchable, + }); const { coverageMatrix: _coverageMatrix, ...planWithoutCoverage } = plan; const selectedJobs = [...new Set([...plan.selectedJobs, JETSON_DISPATCH_TARGET])]; return withCoverageMatrix( @@ -814,7 +818,9 @@ export function buildE2eWorkflowPlan( selectedJobSet.add(JETSON_DISPATCH_TARGET); const selectedJobs = [...selectedJobSet]; const runtimeSelectedJobs = selectedJobs.filter( - (job) => workflowJobRuntimeProviders(inventory, job, gatewayRuntimes).length > 0, + (job) => + (job !== "staging-brev-launchable" || options.includeStagingBrevLaunchable !== false) && + workflowJobRuntimeProviders(inventory, job, gatewayRuntimes).length > 0, ); const selectedTests = credentialFreeTestMatrix( credentialFreeTests.filter((row) => changedFiles.includes(row.file)), @@ -869,6 +875,7 @@ export function buildE2eWorkflowPlan( const selectedJobs = inventory.workflowJobs.filter( (job) => !inventory.explicitOnlyJobs.includes(job) && + (job !== "staging-brev-launchable" || options.includeStagingBrevLaunchable !== false) && (job !== SHARED_E2E_JOB_ID || testMatrix.length > 0) && workflowJobRuntimeProviders(inventory, job, gatewayRuntimes).length > 0, ); @@ -1155,7 +1162,12 @@ export function writeE2eWorkflowPlanCiOutput( ); const hasPlannerSelectors = Boolean(selectors.jobs || selectors.targets); const changedFiles = hasPlannerSelectors ? undefined : changedFilesFromEnvironment(environment); - const planned = buildE2eWorkflowPlan(selectors, { changedFiles, gatewayRuntimes }); + const planned = buildE2eWorkflowPlan(selectors, { + changedFiles, + gatewayRuntimes, + includeStagingBrevLaunchable: + environment.NEMOCLAW_E2E_INCLUDE_STAGING_BREV_LAUNCHABLE === "true", + }); const plan = validateE2eWorkflowPlan(planned); const expectedHermes = expectedHermesSelection(selectors); if (!changedFiles && plan.hermesSelected !== expectedHermes) { From 4399849c2ea10efec202d64fad354c520d05e216 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 8 Oct 2026 13:57:53 -0700 Subject: [PATCH 3/4] fix(e2e): qualify candidate dependencies across protected runtimes --- .github/workflows/e2e.yaml | 136 ++++++--- .../checks/build-protected-managed-images.sh | 129 ++++---- scripts/checks/extract-installer-pins.mts | 54 ++++ .../pi-qualification-receipt-refresh.mts | 47 +-- .../checks/protected-dcode-base-receipt.mts | 30 +- .../protected-managed-image-contract.ts | 7 +- scripts/checks/resolve-managed-pr-base.sh | 51 ++-- scripts/checks/run.mts | 2 +- scripts/lib/reviewed-npm-archive.mts | 8 + test/e2e/README.md | 45 ++- .../candidate-openshell-version.test.ts | 42 ++- ...d-image-protected-runtime-workflow.test.ts | 104 ++++++- .../e2e/support/openshell-sdk-install.test.ts | 31 +- .../protected-dcode-base-receipt.test.ts | 40 ++- .../protected-openshell-projection.test.ts | 283 ++++++++++++++++++ .../protected-openshell-workspace.test.ts | 225 ++++++++++++++ .../support/workflow-prerequisites.test.ts | 58 ++++ .../managed-image-pr-base-resolution.test.ts | 41 ++- ...otected-managed-image-build-script.test.ts | 60 ++-- .../protected-managed-image-contract.test.ts | 199 +++++++++++- test/repository/checks-runner.test.ts | 1 + .../pi-qualification-receipt-refresh.test.ts | 61 +++- ...aged-image-multiarch-workflow-boundary.mts | 14 +- ...ge-protected-runtime-workflow-boundary.mts | 130 ++++++-- tools/e2e/pre-candidate-workflow-contract.mts | 2 + tools/e2e/protected-openshell-projection.mts | 168 +++++++++++ tools/e2e/protected-openshell-workspace.mts | 223 ++++++++++++++ tools/e2e/workflow-boundary-policy.mts | 4 +- tools/e2e/workflow-boundary.mts | 7 +- 29 files changed, 1955 insertions(+), 247 deletions(-) create mode 100644 test/e2e/support/protected-openshell-projection.test.ts create mode 100644 test/e2e/support/protected-openshell-workspace.test.ts create mode 100644 tools/e2e/protected-openshell-projection.mts create mode 100644 tools/e2e/protected-openshell-workspace.mts diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index bd07c9db715..fafdc8c9053 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -688,6 +688,7 @@ jobs: echo 'hermes_selected=false' echo 'explicit_only_jobs=native-runtime-qualification-producer' echo 'release_required_jobs=[]' + echo 'managed_image_required=false' } >>"$GITHUB_OUTPUT" exit 0 fi @@ -703,6 +704,7 @@ jobs: - id: openshell_version name: Resolve reviewed candidate OpenShell version + if: ${{ contains(fromJSON(steps.matrix.outputs.selected_jobs), 'openshell-gateway-auth-contract') || contains(fromJSON(steps.matrix.outputs.selected_jobs), 'external-gateway-health') }} env: CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository || github.repository }} CANDIDATE_SHA: ${{ inputs.checkout_sha || github.sha }} @@ -4599,6 +4601,7 @@ jobs: - id: hermes-base name: Resolve reviewed Hermes platform base image + if: ${{ inputs.checkout_sha == '' }} uses: ./.trusted-hermes-resolver/.github/actions/resolve-reviewed-hermes-platform with: dockerfile-path: agents/hermes/Dockerfile @@ -4625,11 +4628,21 @@ jobs: - id: bases name: Resolve digest-pinned platform base images env: + CANDIDATE_BASES: ${{ inputs.checkout_sha != '' }} DCODE_BASE_CONTRACT: ${{ needs.base-image-publication.outputs.dcode_base_contract }} + HERMES_BASE_REF: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.hermes-base.outputs.digest }} PLATFORM: ${{ matrix.platform }} shell: bash run: | set -euo pipefail + case "$CANDIDATE_BASES" in + true) + printf 'openclaw=candidate\nhermes=candidate\ndcode=candidate\n' >> "$GITHUB_OUTPUT" + exit 0 + ;; + false) ;; + *) echo "::error::Invalid candidate base selection" >&2; exit 1 ;; + esac arch="${PLATFORM#linux/}" work_dir="$(mktemp -d "${RUNNER_TEMP}/nemoclaw-protected-bases.XXXXXX")" trap 'rm -rf -- "$work_dir"' EXIT @@ -4686,6 +4699,8 @@ jobs: exit 1 } printf 'dcode=%s\n' "$dcode_reference" >> "$GITHUB_OUTPUT" + [[ "$HERMES_BASE_REF" =~ ^ghcr[.]io/nvidia/nemoclaw/hermes-sandbox-base@sha256:[a-f0-9]{64}$ ]] + printf 'hermes=%s\n' "$HERMES_BASE_REF" >> "$GITHUB_OUTPUT" - name: Start isolated protected managed-image registry shell: bash @@ -4717,7 +4732,7 @@ jobs: - name: Build exact all-agent protected managed images env: BASE_DCODE: ${{ steps.candidate-contract.outputs.dcode_source == 'candidate' && 'candidate' || steps.bases.outputs.dcode }} - BASE_HERMES: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.hermes-base.outputs.digest }} + BASE_HERMES: ${{ steps.bases.outputs.hermes }} BASE_OPENCLAW: ${{ steps.bases.outputs.openclaw }} CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} shell: bash @@ -4919,13 +4934,20 @@ jobs: # assertions without the hosted cache. managed-image-protected-runtime: name: Protected managed-image GPU and local inference - needs: [base-image-publication, generate-matrix, managed-image-multiarch-startup] - if: ${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }} + needs: + [ + base-image-publication, + generate-matrix, + managed-image-multiarch-startup, + package-openshell-sdk, + ] + if: ${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && needs['package-openshell-sdk'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }} runs-on: linux-amd64-gpu-rtxpro6000-latest-1 timeout-minutes: 75 permissions: contents: read env: + CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} E2E_ARTIFACT_DIR: ${{ github.workspace }}/e2e-artifacts/live/managed-image-protected-runtime E2E_JOB: "1" E2E_GATEWAY_RUNTIMES: docker @@ -5022,6 +5044,8 @@ jobs: - name: Prepare E2E workspace uses: NVIDIA/NemoClaw/.github/actions/prepare-e2e@afffe9cdedd168bfd7116c53846ddffe32eadd4c + with: + build-cli: "false" - id: runtime-contract name: Validate protected runtime activation contract @@ -5067,8 +5091,29 @@ jobs: printf 'runtime_user=%s\n' "$runtime_user" >> "$GITHUB_OUTPUT" install -d -m 0700 "$E2E_ARTIFACT_DIR" + - id: openshell-projection + name: Bind reviewed candidate OpenShell runtime + shell: bash + run: | + set -euo pipefail + node tools/e2e/protected-openshell-workspace.mts prepare > "$E2E_ARTIFACT_DIR/openshell-projection.json" + + - name: Download reviewed OpenShell SDK archive + uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 + with: + name: ${{ needs.package-openshell-sdk.outputs.artifact_name }} + path: ${{ runner.temp }}/openshell-sdk + + - name: Install reviewed OpenShell SDK from trusted controller + uses: ./.github/actions/install-reviewed-openshell-sdk + + - name: Build trusted CLI with reviewed OpenShell runtime + shell: bash + run: npm run build:cli + - id: runtime-hermes-base name: Resolve reviewed Hermes runtime base image + if: ${{ inputs.checkout_sha == '' }} uses: ./.github/actions/resolve-reviewed-hermes-platform with: dockerfile-path: .candidate-runtime/agents/hermes/Dockerfile @@ -5077,6 +5122,7 @@ jobs: - id: runtime-bases name: Resolve digest-pinned amd64 runtime base images env: + CANDIDATE_BASES: ${{ inputs.checkout_sha != '' }} CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} DCODE_BASE_REF: ${{ needs.base-image-publication.outputs.dcode_base_ref }} HERMES_BASE_REF: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }} @@ -5086,8 +5132,8 @@ jobs: work_dir="$(mktemp -d "${RUNNER_TEMP}/nemoclaw-runtime-bases.XXXXXX")" trap 'rm -rf -- "$work_dir"' EXIT - # The mutable base alias can move after the startup job prepared this cache. - # Reuse that job's exact OpenClaw base and preserve the other identity checks. + [[ "$CANDIDATE_BASES" == true || "$CANDIDATE_BASES" == false ]] || exit 1 + # Consume the CPU job's immutable bases, not aliases resolved again on the GPU host. prepared_inputs="$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/prepared-inputs" [[ -f "$prepared_inputs" && ! -L "$prepared_inputs" ]] || { echo "::error::protected build cache has no safe prepared-input identity" >&2 @@ -5097,48 +5143,41 @@ jobs: [[ -z "$extra" && "$cached_revision" == "$CHECKOUT_SHA" && "$cached_platform" == "linux/amd64" && - "$cached_hermes" == "$HERMES_BASE_REF" && "$(cat "$prepared_inputs")" == "$cached_revision $cached_platform $cached_openclaw $cached_hermes $cached_dcode" ]] || { echo "::error::protected build-cache identity does not match this run" >&2 exit 1 } - [[ "$cached_openclaw" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]] || { - echo "::error::prepared OpenClaw base is not an exact approved image reference" >&2 - exit 1 - } - openclaw_digest="${cached_openclaw##*@}" - docker buildx imagetools inspect "$cached_openclaw" --raw > "$work_dir/openclaw-exact.raw" - [[ "sha256:$(sha256sum "$work_dir/openclaw-exact.raw" | awk '{print $1}')" == "$openclaw_digest" ]] || { - echo "::error::OpenClaw exact base bytes do not match the prepared digest" >&2 - exit 1 + resolve_cached_base() { + local name="$1" agent="$2" reference="$3" repository="$4" expected_published="$5" + local candidate_prefix="localhost:5000/nemoclaw-managed-protected-base/${agent}@" + local digest="${reference##*@}" + [[ "$digest" =~ ^sha256:[a-f0-9]{64}$ ]] || exit 1 + if [[ "$reference" == "${candidate_prefix}${digest}" ]]; then + local verified + verified="$(node scripts/checks/protected-dcode-base-receipt.mts verify \ + "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/${name}-base" \ + "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/${name}-base-receipt.json" "$agent")" + [[ "$verified" == "$reference" ]] || { + echo "::error::prepared ${agent} base does not match this run's verified OCI artifact" >&2 + exit 1 + } + else + [[ "$CANDIDATE_BASES" == false && "$reference" == "${repository}@${digest}" && + ( -z "$expected_published" || "$reference" == "$expected_published" ) ]] || { + echo "::error::prepared ${agent} base does not match the selected source" >&2 + exit 1 + } + docker buildx imagetools inspect "$reference" --raw > "$work_dir/${name}-exact.raw" + [[ "sha256:$(sha256sum "$work_dir/${name}-exact.raw" | awk '{print $1}')" == "$digest" ]] || { + echo "::error::${agent} exact base bytes do not match the prepared digest" >&2 + exit 1 + } + fi + printf '%s=%s\n' "$name" "$reference" >> "$GITHUB_OUTPUT" } - printf 'openclaw=%s\n' "$cached_openclaw" >> "$GITHUB_OUTPUT" - if [[ "$cached_dcode" =~ ^localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:[a-f0-9]{64}$ ]]; then - verified_dcode="$(node scripts/checks/protected-dcode-base-receipt.mts verify \ - "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base" \ - "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base-receipt.json")" - [[ "$verified_dcode" == "$cached_dcode" ]] || { - echo "::error::prepared DCode base does not match this run's verified OCI artifact" >&2 - exit 1 - } - printf 'dcode=%s\n' "$verified_dcode" >> "$GITHUB_OUTPUT" - else - [[ "$cached_dcode" == "$DCODE_BASE_REF" ]] || { - echo "::error::prepared published DCode base does not match the selected publication" >&2 - exit 1 - } - [[ "$DCODE_BASE_REF" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ ]] || { - echo "::error::dcode base publication returned an invalid exact reference" >&2 - exit 1 - } - dcode_digest="${DCODE_BASE_REF##*@}" - docker buildx imagetools inspect "$DCODE_BASE_REF" --raw > "$work_dir/dcode-exact.raw" - [[ "sha256:$(sha256sum "$work_dir/dcode-exact.raw" | awk '{print $1}')" == "$dcode_digest" ]] || { - echo "::error::dcode exact base bytes do not match the published digest" >&2 - exit 1 - } - printf 'dcode=%s\n' "$DCODE_BASE_REF" >> "$GITHUB_OUTPUT" - fi + resolve_cached_base openclaw openclaw "$cached_openclaw" ghcr.io/nvidia/nemoclaw/sandbox-base '' + resolve_cached_base hermes hermes "$cached_hermes" ghcr.io/nvidia/nemoclaw/hermes-sandbox-base "$HERMES_BASE_REF" + resolve_cached_base dcode langchain-deepagents-code "$cached_dcode" ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base "$DCODE_BASE_REF" - name: Start isolated protected runtime registry shell: bash @@ -5170,7 +5209,7 @@ jobs: - name: Build exact all-agent protected runtime images env: BASE_DCODE: ${{ steps.runtime-bases.outputs.dcode }} - BASE_HERMES: ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }} + BASE_HERMES: ${{ steps.runtime-bases.outputs.hermes }} BASE_OPENCLAW: ${{ steps.runtime-bases.outputs.openclaw }} CHECKOUT_SHA: ${{ inputs.checkout_sha || github.sha }} RUNTIME_USER: ${{ steps.runtime-contract.outputs.runtime_user }} @@ -5204,8 +5243,10 @@ jobs: echo "::error::Protected NIM qualification must execute trusted workflow code" >&2 exit 1 } + node tools/e2e/protected-openshell-workspace.mts verify > "$E2E_ARTIFACT_DIR/openshell-projection-verified.json" export PATH="$HOME/.local/bin:$HOME/.npm-global/bin:$PATH" - export OPENSHELL_BIN="$(command -v openshell)" + OPENSHELL_BIN="$(command -v openshell)" + export OPENSHELL_BIN "$OPENSHELL_BIN" --version npx tsx tools/e2e/live-vitest-invocation.mts run --test-path test/e2e/live/managed-image-protected-runtime.test.ts @@ -5235,6 +5276,13 @@ jobs: exit 1 fi + - name: Restore trusted OpenShell sources + if: ${{ always() && steps.openshell-projection.outcome == 'success' }} + shell: bash + run: | + set -euo pipefail + node tools/e2e/protected-openshell-workspace.mts restore > "$E2E_ARTIFACT_DIR/openshell-projection-restored.json" + - name: Upload protected managed-image runtime artifacts if: always() uses: NVIDIA/NemoClaw/.github/actions/upload-e2e-artifacts@7768e15eb90d3ee2d33432f481dfe8747e4f6d57 diff --git a/scripts/checks/build-protected-managed-images.sh b/scripts/checks/build-protected-managed-images.sh index cd9c56a9e09..dcf9aa8ccba 100755 --- a/scripts/checks/build-protected-managed-images.sh +++ b/scripts/checks/build-protected-managed-images.sh @@ -103,12 +103,18 @@ esac target_arch="${platform#linux/}" npm_target_os="linux" npm_target_libc="glibc" -[[ "$openclaw_base" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage -[[ "$hermes_base" =~ ^ghcr[.]io/nvidia/nemoclaw/hermes-sandbox-base@sha256:[a-f0-9]{64}$ ]] || usage +[[ "$openclaw_base" == candidate || + "$openclaw_base" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ || + (-n "$cache_from" && "$openclaw_base" =~ ^localhost:5000/nemoclaw-managed-protected-base/openclaw@sha256:[a-f0-9]{64}$) ]] || usage +[[ "$hermes_base" == candidate || + "$hermes_base" =~ ^ghcr[.]io/nvidia/nemoclaw/hermes-sandbox-base@sha256:[a-f0-9]{64}$ || + (-n "$cache_from" && "$hermes_base" =~ ^localhost:5000/nemoclaw-managed-protected-base/hermes@sha256:[a-f0-9]{64}$) ]] || usage [[ "$dcode_base" == candidate || "$dcode_base" =~ ^ghcr[.]io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@sha256:[a-f0-9]{64}$ || (-n "$cache_from" && "$dcode_base" =~ ^localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:[a-f0-9]{64}$) ]] || usage [[ "$dcode_base" != candidate || -z "$cache_from" ]] || usage +[[ "$openclaw_base" != candidate || -z "$cache_from" ]] || usage +[[ "$hermes_base" != candidate || -z "$cache_from" ]] || usage prepared_identity="$revision $platform $openclaw_base $hermes_base $dcode_base" [[ "$source_root" == /* && "$source_root" != *$'\n'* && -d "$source_root" && ! -L "$source_root" ]] || usage source_root="$(cd -- "$source_root" && pwd -P)" @@ -246,53 +252,68 @@ trap 'exit 143' TERM # A PR dependency upgrade needs its own base; a published main base cannot # satisfy the candidate's no-deps profile. Keep this build on the CPU runner # and bind the exported OCI bytes to the exact source, platform and run. -dcode_base_layout="" -dcode_receipt_helper="$controller_root/scripts/checks/protected-dcode-base-receipt.mts" -if [[ "$dcode_base" == candidate ]]; then - [[ "$(git -C "$source_root" rev-parse --verify HEAD)" == "$revision" ]] || { - echo "ERROR: candidate base checkout does not match its revision" >&2 - exit 1 - } - git -C "$source_root" diff --quiet HEAD -- || { - echo "ERROR: candidate base checkout has tracked modifications" >&2 - exit 1 - } - dcode_base_layout="${cache_to:-$work_dir}/dcode-base" - dcode_base_receipt="${cache_to:-$work_dir}/dcode-base-receipt.json" - dcode_base_tag="localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code:${revision}" - docker buildx build \ - --file "$source_root/agents/langchain-deepagents-code/Dockerfile.base" \ - --platform "$platform" \ - --provenance=false --sbom=false \ - --label "org.opencontainers.image.source=https://github.com/NVIDIA/NemoClaw" \ - --label "org.opencontainers.image.revision=${revision}" \ - --label "io.nvidia.nemoclaw.agent=langchain-deepagents-code" \ - --label "io.nvidia.nemoclaw.managed-image.cohort=${cohort}" \ - --output "type=image,name=${dcode_base_tag},push=true,oci-mediatypes=true" \ - --output "type=oci,dest=${dcode_base_layout},tar=false" \ - "$source_root" - dcode_base="$(CHECKOUT_SHA="$revision" \ - NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT="$cohort" \ - NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM="$platform" \ - node "$dcode_receipt_helper" write "$dcode_base_layout" "$dcode_base_receipt")" - # Prove the pushed manifest and the offline artifact have the same identity. - docker buildx imagetools inspect "$dcode_base" --raw >"$work_dir/dcode-candidate-base.raw" - [[ "sha256:$(sha256sum "$work_dir/dcode-candidate-base.raw" | awk '{print $1}')" == "${dcode_base##*@}" ]] || { - echo "ERROR: candidate base registry and OCI artifact digests differ" >&2 - exit 1 - } - prepared_identity="$revision $platform $openclaw_base $hermes_base $dcode_base" -elif [[ "$dcode_base" == localhost:5000/* ]]; then - dcode_base_layout="$cache_from/dcode-base" - verified_dcode_base="$(CHECKOUT_SHA="$revision" \ - NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT="$cohort" \ - NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM="$platform" \ - node "$dcode_receipt_helper" verify "$dcode_base_layout" "$cache_from/dcode-base-receipt.json")" - [[ "$verified_dcode_base" == "$dcode_base" ]] || { - echo "ERROR: candidate base artifact does not match the prepared base reference" >&2 - exit 1 - } -fi +prepare_candidate_base() { + local agent="$1" dockerfile="$2" cache_name="$3" + prepared_base="$4" + prepared_base_layout="" + local receipt_helper="$controller_root/scripts/checks/protected-dcode-base-receipt.mts" + if [[ "$prepared_base" == candidate ]]; then + [[ "$(git -C "$source_root" rev-parse --verify HEAD)" == "$revision" ]] || { + echo "ERROR: candidate base checkout does not match its revision" >&2 + exit 1 + } + git -C "$source_root" diff --quiet HEAD -- || { + echo "ERROR: candidate base checkout has tracked modifications" >&2 + exit 1 + } + prepared_base_layout="${cache_to:-$work_dir}/${cache_name}-base" + local base_receipt="${cache_to:-$work_dir}/${cache_name}-base-receipt.json" + local base_tag="localhost:5000/nemoclaw-managed-protected-base/${agent}:${revision}" + docker buildx build \ + --file "$source_root/$dockerfile" \ + --platform "$platform" \ + --provenance=false --sbom=false \ + --label "org.opencontainers.image.source=https://github.com/NVIDIA/NemoClaw" \ + --label "org.opencontainers.image.revision=${revision}" \ + --label "io.nvidia.nemoclaw.agent=${agent}" \ + --label "io.nvidia.nemoclaw.managed-image.cohort=${cohort}" \ + --output "type=image,name=${base_tag},push=true,oci-mediatypes=true" \ + --output "type=oci,dest=${prepared_base_layout},tar=false" \ + "$source_root" + prepared_base="$(CHECKOUT_SHA="$revision" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT="$cohort" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM="$platform" \ + node "$receipt_helper" write "$prepared_base_layout" "$base_receipt" "$agent")" + # Prove the pushed manifest and the offline artifact have the same identity. + docker buildx imagetools inspect "$prepared_base" --raw >"$work_dir/${cache_name}-candidate-base.raw" + [[ "sha256:$(sha256sum "$work_dir/${cache_name}-candidate-base.raw" | awk '{print $1}')" == "${prepared_base##*@}" ]] || { + echo "ERROR: candidate base registry and OCI artifact digests differ" >&2 + exit 1 + } + elif [[ "$prepared_base" == localhost:5000/* ]]; then + prepared_base_layout="$cache_from/${cache_name}-base" + local verified_base + verified_base="$(CHECKOUT_SHA="$revision" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT="$cohort" \ + NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM="$platform" \ + node "$receipt_helper" verify "$prepared_base_layout" "$cache_from/${cache_name}-base-receipt.json" "$agent")" + [[ "$verified_base" == "$prepared_base" ]] || { + echo "ERROR: candidate base artifact does not match the prepared base reference" >&2 + exit 1 + } + fi +} + +prepare_candidate_base openclaw Dockerfile.base openclaw "$openclaw_base" +openclaw_base="$prepared_base" +openclaw_base_layout="$prepared_base_layout" +prepare_candidate_base hermes agents/hermes/Dockerfile.base hermes "$hermes_base" +hermes_base="$prepared_base" +hermes_base_layout="$prepared_base_layout" +prepare_candidate_base langchain-deepagents-code agents/langchain-deepagents-code/Dockerfile.base dcode "$dcode_base" +dcode_base="$prepared_base" +dcode_base_layout="$prepared_base_layout" +prepared_identity="$revision $platform $openclaw_base $hermes_base $dcode_base" audit_receipt="" audit_raw_report="" @@ -530,9 +551,15 @@ build_agent() { fi local base_digest="${base_reference##*@}" - if [[ "$agent" == langchain-deepagents-code && -n "$dcode_base_layout" ]]; then + local base_layout="" + case "$agent" in + openclaw) base_layout="$openclaw_base_layout" ;; + hermes) base_layout="$hermes_base_layout" ;; + langchain-deepagents-code) base_layout="$dcode_base_layout" ;; + esac + if [[ -n "$base_layout" ]]; then # The verified local OCI input survives deletion of the CPU job's registry. - cache_args+=(--build-context "$base_reference=oci-layout://${dcode_base_layout}@${base_digest}") + cache_args+=(--build-context "$base_reference=oci-layout://${base_layout}@${base_digest}") else docker buildx imagetools inspect "$base_reference" --raw >"$exact_base_raw" local actual_base diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index 72795e208b5..474c0de5d64 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -60,6 +60,7 @@ type OpenShellPinLayout = { type OpenShellReleaseTrust = { brevTemplateSha256: readonly string[]; + featureGateTemplateSha256?: readonly string[]; formula: { asset: "openshell.rb"; sha256: string; @@ -592,6 +593,7 @@ const TRUSTED_OPENSHELL_RELEASES: readonly OpenShellReleaseTrust[] = [ ], }, pinLayout: V00116_OPENSHELL_PIN_LAYOUT, + featureGateTemplateSha256: ["3404b35030ce0adef3998dcdedf27245610534ddefaa741e125539b3d2e1a735"], version: "0.0.116", }, { @@ -646,6 +648,8 @@ const TRUSTED_OPENSHELL_RELEASES: readonly OpenShellReleaseTrust[] = [ ], }, pinLayout: V00116_OPENSHELL_PIN_LAYOUT, + // #12603's reviewed split-supervisor check accepts only the selected sandbox hashes. + featureGateTemplateSha256: ["3a402736ff8a2e02b5b26382521b4a4b9774046856c42f5be093b56480d6711e"], version: "0.1.2", }, ] as const; @@ -696,6 +700,9 @@ function validateTrustedRelease(release: OpenShellReleaseTrust): void { release.installerTemplateSha256.some((sha256) => !SHA256_PATTERN.test(sha256)) || release.brevTemplateSha256.length === 0 || release.brevTemplateSha256.some((sha256) => !SHA256_PATTERN.test(sha256)) || + (release.featureGateTemplateSha256 !== undefined && + (release.featureGateTemplateSha256.length === 0 || + release.featureGateTemplateSha256.some((sha256) => !SHA256_PATTERN.test(sha256)))) || release.sandboxBuilds.some((pin) => !SHA256_PATTERN.test(pin.sha256)) ) { fail(`trusted OpenShell v${release.version} template or sandbox record is invalid`); @@ -1853,6 +1860,53 @@ export function validateInstallerSources(sources: { return { releaseVersion, pins, installerReleases, installerTemplateSha256, brevTemplateSha256 }; } +/** Validate the host feature-check module before protected E2E adopts its template. */ +export function validateOpenShellFeatureGateSource(source: string, releaseVersion: string): void { + const release = trustedRelease(releaseVersion); + if (Buffer.byteLength(source) > MAX_INSTALLER_INPUT_BYTES || source.includes("\0")) { + fail("feature gate source is invalid or too large"); + } + const header = "const PINNED_SANDBOX_BUILD_VERSIONS = new Map([\n"; + const start = source.indexOf(header); + if (start < 0 || source.indexOf(header, start + header.length) !== -1) { + fail("feature gate must contain one literal sandbox build map"); + } + const bodyStart = start + header.length; + const end = source.indexOf("\n]);", bodyStart); + if (end < 0) fail("feature gate sandbox build map is unterminated"); + const pins = source + .slice(bodyStart, end) + .split("\n") + .flatMap((line) => { + if (/^ \/\/[^\r\n]*$/u.test(line)) return []; + const match = /^ \["([a-f0-9]{64})", "([0-9]+\.[0-9]+\.[0-9]+)"\],$/u.exec(line); + if (!match) fail("feature gate sandbox build map must contain only literal pins"); + return [{ sha256: match[1]!, version: match[2]! }]; + }); + const allowed = new Set( + TRUSTED_OPENSHELL_RELEASES.flatMap((record) => + record.sandboxBuilds.map((pin) => `${record.version}:${pin.sha256}`), + ), + ); + const actual = new Set(pins.map((pin) => `${pin.version}:${pin.sha256}`)); + if ( + new Set(pins.map((pin) => pin.sha256)).size !== pins.length || + pins.some((pin) => !allowed.has(`${pin.version}:${pin.sha256}`)) || + release.sandboxBuilds.length === 0 || + release.sandboxBuilds.some((pin) => !actual.has(`${releaseVersion}:${pin.sha256}`)) + ) { + fail( + "feature gate sandbox identities must be unique, base-trusted and include the selected release", + ); + } + const normalized = + source.slice(0, bodyStart) + "" + source.slice(end); + const digest = createHash("sha256").update(normalized).digest("hex"); + if (!release.featureGateTemplateSha256?.includes(digest)) { + fail(`feature gate operational template is not base-trusted; actual_sha256=${digest}`); + } +} + function runCli(): void { const options = parseCliOptions(process.argv.slice(2)); const { pins, installerReleases, installerTemplateSha256, brevTemplateSha256 } = diff --git a/scripts/checks/pi-qualification-receipt-refresh.mts b/scripts/checks/pi-qualification-receipt-refresh.mts index 640a5bb7302..e93f774da55 100644 --- a/scripts/checks/pi-qualification-receipt-refresh.mts +++ b/scripts/checks/pi-qualification-receipt-refresh.mts @@ -209,13 +209,10 @@ function receiptComparisonRevision(git: GitRunner, explicit?: string): string | } function validateReceiptPair( - git: GitRunner, rootDir: string, - imageSourcePaths: readonly string[], receipts: readonly { path: string; platform: ManagedImagePlatform }[], acceptedDigests: ReadonlySet, - comparisonRevision: string | null, -): void { +): string { const validated = receipts.map((receipt) => parseReceipt(rootDir, receipt, acceptedDigests)); const contracts = validated.map(({ contract }) => contract); const revisions = new Set(contracts.map(({ source }) => source.revision)); @@ -231,15 +228,11 @@ function validateReceiptPair( ) { throw new Error("Pi candidate receipt authority must exactly match both published receipts"); } - requireReceiptSourceParity( - git, - contracts[0]!.source.revision, - comparisonRevision, - imageSourcePaths, - ); + return contracts[0]!.source.revision; } type PiReceiptRefreshCheckOptions = { + allowPendingPublication?: boolean; acceptedDigests?: ReadonlySet; baseBranch?: string; git?: GitRunner; @@ -250,7 +243,7 @@ type PiReceiptRefreshCheckOptions = { export function checkPiQualificationReceiptRefresh( options: PiReceiptRefreshCheckOptions = {}, -): void { +): "pending-publication" | undefined { const git = options.git ?? runGit; const rootDir = options.rootDir ?? REPO_ROOT; const baseBranch = options.baseBranch ?? process.env.GITHUB_BASE_REF?.trim(); @@ -275,8 +268,15 @@ export function checkPiQualificationReceiptRefresh( ); if (!imageInputsChanged && !receiptAuthorityChanged) return; + // A source commit must reach image CI before its receipts can exist. Only local + // source-only publication can defer freshness; CI and receipt edits stay strict. + const pendingPublication = + options.allowPendingPublication === true && + process.env.GITHUB_ACTIONS !== "true" && + imageInputsChanged && + !receiptAuthorityChanged; const missingReceipts = receiptPaths.filter((receipt) => !changedPaths.includes(receipt)); - if (imageInputsChanged && missingReceipts.length > 0) { + if (imageInputsChanged && missingReceipts.length > 0 && !pendingPublication) { throw new Error( [ "Pi image inputs changed without refreshing both qualification receipts.", @@ -287,17 +287,28 @@ export function checkPiQualificationReceiptRefresh( ].join("\n"), ); } - validateReceiptPair( + const sourceRevision = validateReceiptPair(rootDir, receipts, acceptedDigests); + if (pendingPublication) return "pending-publication"; + requireReceiptSourceParity( git, - rootDir, - imageSourcePaths, - receipts, - acceptedDigests, + sourceRevision, receiptComparisonRevision(git, options.headRevision), + imageSourcePaths, ); } const currentModule = fileURLToPath(import.meta.url); if (process.argv[1] && path.resolve(process.argv[1]) === currentModule) { - checkPiQualificationReceiptRefresh(); + const args = process.argv.slice(2); + if (args.length > 1 || (args.length === 1 && args[0] !== "--local-publication")) { + throw new Error("Expected no arguments or --local-publication"); + } + const result = checkPiQualificationReceiptRefresh({ + allowPendingPublication: args[0] === "--local-publication", + }); + if (result === "pending-publication") { + console.warn( + "Pi source publication only; qualification is pending. CI requires both newly published receipts and matching authority before merge.", + ); + } } diff --git a/scripts/checks/protected-dcode-base-receipt.mts b/scripts/checks/protected-dcode-base-receipt.mts index 45baff29b8c..f0842359d34 100644 --- a/scripts/checks/protected-dcode-base-receipt.mts +++ b/scripts/checks/protected-dcode-base-receipt.mts @@ -5,6 +5,7 @@ import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { PROTECTED_MANAGED_IMAGE_AGENTS } from "./protected-managed-image-contract.ts"; export const PROTECTED_DCODE_BASE_REPOSITORY = "localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code"; @@ -139,8 +140,12 @@ function verifiedJsonBlob(layout: string, entry: { digest: string; size: number export function inspectProtectedDcodeBase( layout: string, expected: ProtectedDcodeBaseIdentity, + agent: (typeof PROTECTED_MANAGED_IMAGE_AGENTS)[number] = "langchain-deepagents-code", ): ProtectedDcodeBaseReceipt { validateIdentity(expected); + if (!PROTECTED_MANAGED_IMAGE_AGENTS.includes(agent)) { + throw new Error("protected base agent is not supported"); + } for (const directory of [layout, path.join(layout, "blobs"), path.join(layout, "blobs/sha256")]) { if (!fs.lstatSync(directory).isDirectory()) { throw new Error("protected DCode base layout directories must not be symlinks"); @@ -175,7 +180,7 @@ export function inspectProtectedDcodeBase( labels["org.opencontainers.image.revision"] !== expected.sourceRevision || labels["org.opencontainers.image.source"] !== "https://github.com/NVIDIA/NemoClaw" || labels["io.nvidia.nemoclaw.managed-image.cohort"] !== expected.cohort || - labels["io.nvidia.nemoclaw.agent"] !== "langchain-deepagents-code" + labels["io.nvidia.nemoclaw.agent"] !== agent ) { throw new Error( "protected DCode base config does not match the selected source, run or platform", @@ -186,7 +191,7 @@ export function inspectProtectedDcodeBase( ...expected, digest: manifestDescriptor.digest, imageId: configDescriptor.digest, - reference: `${PROTECTED_DCODE_BASE_REPOSITORY}@${manifestDescriptor.digest}`, + reference: `localhost:5000/nemoclaw-managed-protected-base/${agent}@${manifestDescriptor.digest}`, }; } @@ -194,9 +199,10 @@ export function verifyProtectedDcodeBaseReceipt( layout: string, receiptPath: string, expected: ProtectedDcodeBaseIdentity, + agent: (typeof PROTECTED_MANAGED_IMAGE_AGENTS)[number] = "langchain-deepagents-code", ): ProtectedDcodeBaseReceipt { const receipt = readJson(receiptPath); - const actual = inspectProtectedDcodeBase(layout, expected); + const actual = inspectProtectedDcodeBase(layout, expected, agent); const keys = Object.keys(actual) as (keyof ProtectedDcodeBaseReceipt)[]; if ( Object.keys(receipt).length !== keys.length || @@ -210,10 +216,11 @@ export function verifyProtectedDcodeBaseReceipt( } function main(): void { - const [command, layout, receiptPath, ...extra] = process.argv.slice(2); + const [command, layout, receiptPath, agent = "langchain-deepagents-code", ...extra] = + process.argv.slice(2); if (!["write", "verify"].includes(command) || !layout || !receiptPath || extra.length) { throw new Error( - "usage: protected-dcode-base-receipt.mts ", + "usage: protected-dcode-base-receipt.mts [agent]", ); } const expected: ProtectedDcodeBaseIdentity = { @@ -225,8 +232,17 @@ function main(): void { }; const receipt = command === "write" - ? inspectProtectedDcodeBase(layout, expected) - : verifyProtectedDcodeBaseReceipt(layout, receiptPath, expected); + ? inspectProtectedDcodeBase( + layout, + expected, + agent as (typeof PROTECTED_MANAGED_IMAGE_AGENTS)[number], + ) + : verifyProtectedDcodeBaseReceipt( + layout, + receiptPath, + expected, + agent as (typeof PROTECTED_MANAGED_IMAGE_AGENTS)[number], + ); if (command === "write") { fs.writeFileSync(receiptPath, `${JSON.stringify(receipt)}\n`, { flag: "wx", diff --git a/scripts/checks/protected-managed-image-contract.ts b/scripts/checks/protected-managed-image-contract.ts index 50fc3474a5a..35c2ec2a7ec 100644 --- a/scripts/checks/protected-managed-image-contract.ts +++ b/scripts/checks/protected-managed-image-contract.ts @@ -136,6 +136,7 @@ function parseEntry( throw new Error("protected managed-image contract entry is not the exact agent digest"); } const basePrefix = `${BASE_REPOSITORIES[entry.agent as ShippedManagedImageAgent]}@`; + const candidateBasePrefix = `localhost:5000/nemoclaw-managed-protected-base/${entry.agent}@`; if ( typeof entry.baseReference !== "string" || (!( @@ -143,10 +144,8 @@ function parseEntry( DIGEST_PATTERN.test(entry.baseReference.slice(basePrefix.length)) ) && !( - entry.agent === "langchain-deepagents-code" && - /^localhost:5000\/nemoclaw-managed-protected-base\/langchain-deepagents-code@sha256:[a-f0-9]{64}$/u.test( - entry.baseReference, - ) + entry.baseReference.startsWith(candidateBasePrefix) && + DIGEST_PATTERN.test(entry.baseReference.slice(candidateBasePrefix.length)) )) ) { throw new Error("protected managed-image contract entry has an invalid base reference"); diff --git a/scripts/checks/resolve-managed-pr-base.sh b/scripts/checks/resolve-managed-pr-base.sh index 2f22b03ce62..f7132395f88 100755 --- a/scripts/checks/resolve-managed-pr-base.sh +++ b/scripts/checks/resolve-managed-pr-base.sh @@ -55,17 +55,13 @@ build_local_base() { local local_base_archive="$RUNNER_TEMP/pr-base.docker.tar" local local_base_oci_archive="$RUNNER_TEMP/pr-base.oci.tar" local local_base_oci="$RUNNER_TEMP/pr-base.oci" - local base_labels=() - if [ "$AGENT" = "langchain-deepagents-code" ]; then - base_labels+=(--label "org.opencontainers.image.revision=${CANDIDATE_SHA}") - fi docker buildx build \ --platform linux/amd64 \ --provenance=false \ --sbom=false \ --file "$BASE_DOCKERFILE" \ --tag "$LOCAL_BASE_REFERENCE" \ - "${base_labels[@]}" \ + --label "org.opencontainers.image.revision=${CANDIDATE_SHA}" \ --output "type=docker,dest=${local_base_archive}" \ --output "type=oci,dest=${local_base_oci_archive}" \ . @@ -97,8 +93,8 @@ build_local_base() { "$DISPLAY_NAME" "$BASE_DOCKERFILE" "$CANDIDATE_SHA" "$reason" \ >>"$GITHUB_STEP_SUMMARY" } -DCODE_COPY_PARSER_INPUT="scripts/lib/dockerfile-copy-sources.mts" -dcode_changed_inputs() { +COPY_PARSER_INPUT="scripts/lib/dockerfile-copy-sources.mts" +changed_base_inputs() { local source_revision="$1" candidate_revision="$2" input local literal_inputs=() shift 2 @@ -108,10 +104,10 @@ dcode_changed_inputs() { git diff --name-only "$source_revision" "$candidate_revision" -- \ "${literal_inputs[@]}" } -read_dcode_base_inputs() { +read_base_inputs() { local dockerfile="$1" parser parsed_inputs source parser="${BASH_SOURCE[0]%/*}/../lib/dockerfile-copy-sources.mts" - DCODE_BASE_INPUTS=("$dockerfile" .dockerignore "$DCODE_COPY_PARSER_INPUT") + BASE_INPUTS=("$dockerfile" .dockerignore "$COPY_PARSER_INPUT") parsed_inputs="$( node --experimental-strip-types --input-type=module -e ' import { pathToFileURL } from "node:url"; @@ -124,14 +120,13 @@ read_dcode_base_inputs() { while IFS= read -r source; do [ -n "$source" ] || continue git cat-file -e "${CANDIDATE_SHA}:${source}" 2>/dev/null || return 1 - DCODE_BASE_INPUTS+=("$source") + BASE_INPUTS+=("$source") done <<<"$parsed_inputs" - [ "${#DCODE_BASE_INPUTS[@]}" -gt 1 ] + [ "${#BASE_INPUTS[@]}" -gt 1 ] } -published_dcode_base_matches_candidate_contract() { - [ "$AGENT" = "langchain-deepagents-code" ] || return 0 +published_base_matches_candidate_contract() { local reference="$1" image_json source_revision changed_inputs - local bootstrap_inputs=("$BASE_DOCKERFILE" .dockerignore "$DCODE_COPY_PARSER_INPUT") + local bootstrap_inputs=("$BASE_DOCKERFILE" .dockerignore "$COPY_PARSER_INPUT") docker pull --platform "$PLATFORM" "$reference" >/dev/null || return 1 image_json="$(docker image inspect "$reference")" || return 1 source_revision="$( @@ -143,24 +138,24 @@ published_dcode_base_matches_candidate_contract() { ' <<<"$image_json" )" || return 1 [[ "$source_revision" =~ ^[0-9a-f]{40}$ ]] || return 1 - PUBLISHED_DCODE_SOURCE_REVISION="$source_revision" + PUBLISHED_BASE_SOURCE_REVISION="$source_revision" if ! git cat-file -e "${source_revision}^{commit}" 2>/dev/null; then git fetch --no-tags --depth=1 origin "$source_revision" || return 1 fi changed_inputs="$( - dcode_changed_inputs "$source_revision" "$CANDIDATE_SHA" \ + changed_base_inputs "$source_revision" "$CANDIDATE_SHA" \ "${bootstrap_inputs[@]}" )" || return 1 if [ -n "$changed_inputs" ]; then - PUBLISHED_DCODE_CHANGED_INPUTS="${changed_inputs//$'\n'/, }" + PUBLISHED_BASE_CHANGED_INPUTS="${changed_inputs//$'\n'/, }" return 1 fi - read_dcode_base_inputs "$BASE_DOCKERFILE" || return 1 + read_base_inputs "$BASE_DOCKERFILE" || return 1 changed_inputs="$( - dcode_changed_inputs "$source_revision" "$CANDIDATE_SHA" \ - "${DCODE_BASE_INPUTS[@]}" + changed_base_inputs "$source_revision" "$CANDIDATE_SHA" \ + "${BASE_INPUTS[@]}" )" || return 1 - PUBLISHED_DCODE_CHANGED_INPUTS="${changed_inputs//$'\n'/, }" + PUBLISHED_BASE_CHANGED_INPUTS="${changed_inputs//$'\n'/, }" [ -z "$changed_inputs" ] } if [[ ! "$BASE_SHA" =~ ^[0-9a-f]{40}$ || ! "$CANDIDATE_SHA" =~ ^[0-9a-f]{40}$ ]]; then @@ -216,14 +211,14 @@ if [ "$actual" != "$digest" ]; then echo "ERROR: exact PR base bytes do not match the selected descriptor digest." >&2 exit 1 fi -PUBLISHED_DCODE_SOURCE_REVISION="" -PUBLISHED_DCODE_CHANGED_INPUTS="" -if ! published_dcode_base_matches_candidate_contract "$reference"; then +PUBLISHED_BASE_SOURCE_REVISION="" +PUBLISHED_BASE_CHANGED_INPUTS="" +if ! published_base_matches_candidate_contract "$reference"; then reason="published base ${reference} could not be proven compatible with candidate ${CANDIDATE_SHA}" - if [ -n "$PUBLISHED_DCODE_SOURCE_REVISION" ] && [ -n "$PUBLISHED_DCODE_CHANGED_INPUTS" ]; then - reason="published base ${reference} from ${PUBLISHED_DCODE_SOURCE_REVISION} differs from candidate ${CANDIDATE_SHA} at ${PUBLISHED_DCODE_CHANGED_INPUTS}" - elif [ -n "$PUBLISHED_DCODE_SOURCE_REVISION" ]; then - reason="published base ${reference} from ${PUBLISHED_DCODE_SOURCE_REVISION} could not be proven compatible with candidate ${CANDIDATE_SHA}" + if [ -n "$PUBLISHED_BASE_SOURCE_REVISION" ] && [ -n "$PUBLISHED_BASE_CHANGED_INPUTS" ]; then + reason="published base ${reference} from ${PUBLISHED_BASE_SOURCE_REVISION} differs from candidate ${CANDIDATE_SHA} at ${PUBLISHED_BASE_CHANGED_INPUTS}" + elif [ -n "$PUBLISHED_BASE_SOURCE_REVISION" ]; then + reason="published base ${reference} from ${PUBLISHED_BASE_SOURCE_REVISION} could not be proven compatible with candidate ${CANDIDATE_SHA}" fi build_local_base "$reason" exit 0 diff --git a/scripts/checks/run.mts b/scripts/checks/run.mts index e5203f13239..76c728c2e00 100644 --- a/scripts/checks/run.mts +++ b/scripts/checks/run.mts @@ -107,7 +107,7 @@ export const CHECKS: readonly CheckCommand[] = [ }, { name: "pi-qualification-receipt-refresh", - args: ["scripts/checks/pi-qualification-receipt-refresh.mts"], + args: ["scripts/checks/pi-qualification-receipt-refresh.mts", "--local-publication"], }, { name: "test-registration-boundary", diff --git a/scripts/lib/reviewed-npm-archive.mts b/scripts/lib/reviewed-npm-archive.mts index 2f211119450..35079b51b0c 100755 --- a/scripts/lib/reviewed-npm-archive.mts +++ b/scripts/lib/reviewed-npm-archive.mts @@ -539,6 +539,14 @@ function productionLockLocations( return reachable; } +/** Resolve one package's locked dependency graph with the shared npm resolution rules. */ +export function reviewedNpmDependencyLocations( + packages: Readonly>>, + packageName: string, +): ReadonlySet { + return productionLockLocations({ ...packages, "": { dependencies: { [packageName]: "*" } } }); +} + function verifyReviewedLockDigest( lockfilePath: string, expectedLockSha256: string, diff --git a/test/e2e/README.md b/test/e2e/README.md index 92159d4d76e..383c8e2efc4 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -85,15 +85,17 @@ Each consumer runs the pinned preparation action with `build-cli: "false"` to in The `managed-image-multiarch-startup` no-build job keeps that setting and compiles only the candidate shared policy boundary on the host. It rejects preexisting output, verifies the required shared modules, and then starts the direct managed-image contracts. Its amd64 shard also exports digest-addressed npm and agent system inputs for the protected offline rebuild. -The trusted controller accepts both the original v1 multiarch activation and v2 -candidate Deep Agents base activation. Version 2 builds the candidate's -`agents/langchain-deepagents-code/Dockerfile.base` on the native CPU runner, -using the candidate checkout's pins and lockfile. It exports the base as OCI -content plus a receipt bound to the source SHA, trusted workflow SHA, platform, -run ID, and attempt. The protected runtime controller verifies the receipt and -every config, manifest, and layer digest before using that base offline. -It does not substitute the published main base when verification fails. -Version 1 retains its published-base behavior. +The trusted controller accepts both v1 multiarch activation and v2 Deep Agents +base activation. PR runs build all three managed-agent bases from the selected +checkout's Dockerfiles, pins and lockfiles on native CPU runners. Each base has +a separate OCI layout and receipt bound to its agent, source SHA, trusted +workflow SHA, platform, run ID and attempt. The protected GPU controller verifies +these identities and every config, manifest and layer digest before using the +bases offline. PR runs reject published-base substitution and failed verification. +Runs without a PR source retain published OpenClaw and Hermes bases; Deep Agents +uses a published base with v1 activation and a candidate base with v2 activation. +The receipt command retains its Deep Agents default for existing callers; an +explicit agent selects the OpenClaw or Hermes contract. The shared compiler uses native GitHub caching of `dist/` and `nemoclaw/dist/` for main CI, PR CI, and E2E candidate preparation. Its key includes the checkout SHA, trusted recipe revision, action content, Node version, and runner platform. @@ -287,6 +289,16 @@ local image, removes registry credentials, validates the anonymously pullable di qualification receipts may consume these candidate contracts only when the recorded image-source paths are unchanged through the receipt commit. +Keep a Pi upgrade in one PR with two publication steps: + +1. Commit and push the image inputs, leaving both existing receipts and their authority unchanged. + Local hooks permit this source-only step and report qualification as pending. +2. After both candidate images publish, add their receipts and matching authority in the same PR. + Keep image inputs unchanged between the source and receipt commits. + +CI does not permit the source-only exception. It requires refreshed receipts before the PR can pass. +A partial receipt or authority change remains an error in local hooks and CI. + Pi full lifecycle qualification runs on Linux AMD64. Linux ARM64 remains release-gated by its native managed-image build, startup, publication, and checked-in receipt. The receipt refresh check requires the Linux AMD64 and Linux ARM64 receipts to identify one source revision, release, and publication @@ -1859,7 +1871,7 @@ Main and manual PR runs use the same typed planner from the trusted workflow rev The planner derives managed-image prerequisites from the selected jobs' dependency graph. Gateway auth and external gateway health can run without managed-agent image publication; selecting an image consumer alongside them retains that consumer's publication gate. -Before candidate execution, the trusted installer verifier reads the exact candidate's blueprint, +When either gateway job is selected, the trusted installer verifier reads the exact candidate's blueprint, installer, Brev installer, and supervisor pins as data and selects its reviewed OpenShell release. Gateway auth and external gateway health use that version, not the version pinned on `main`. Unreviewed releases, inconsistent pins, and modified installer templates fail admission. @@ -1881,7 +1893,8 @@ PR runs select the nearest fully successful publication on the trusted workflow The publication must cover the PR base's latest reviewed image input. For that publication, the job binds the run ID, attempt, revision, cohort artifact ID, and artifact digest before it emits `managed_image_revision`. It validates the complete three-agent, two-architecture cohort artifact and the immutable Deep Agents Code base artifact from that workflow attempt. -`generate-matrix` and every stock-onboarding job depend on this publication job, so incomplete publication creates no onboarding fanout. +`generate-matrix` runs first and selects whether publication is required. +Stock-onboarding jobs still depend on publication, so incomplete publication creates no onboarding fanout. Direct `main` runs use the same publication workflow and artifact contract. The Deep Agents Code managed-image target uses the shared receipt check to verify its image digest, source revision, and cohort. @@ -1975,6 +1988,16 @@ To select the protected managed-image runtime qualification, set `jobs=managed-i Leave `targets` empty. Keep `include_staging_brev_launchable=false`. The candidate must contain `ci/protected-managed-image-multiarch-activation-v1.json` and `ci/protected-managed-image-runtime-activation-v1.json`. +The GPU job reads OpenShell sources from the candidate commit as data, then validates their pins and operational templates. +It projects only the reviewed installer, supervisor and feature-check modules, plus version literals, into the trusted controller checkout. +It builds that controller after projection and verifies the projected sources before qualification. +The job restores the trusted sources after qualification and retains source-digest records with its artifacts. +Those records identify tested inputs; they do not prove live E2E success. +The job also selects the candidate OpenShell SDK from the controller's reviewed current or replacement archives. +It projects the SDK identity into the trusted manifest and lockfile, then installs the verified archive before building the CLI. +The SDK version must match the candidate runtime version. +Changed SDK dependency metadata or transitive dependencies require a trust/bootstrap review; unrelated candidate npm changes never enter the controller. +Live qualification must still pass for the selected candidate; source projection and archive-install tests do not establish that result. To select native runtime qualification evidence production, set `jobs=native-runtime-qualification-producer`. Leave `targets` empty and keep `include_staging_brev_launchable=false`. For this producer run, the executing workflow SHA, `workflow_sha` input, and PR base SHA must match. diff --git a/test/e2e/support/candidate-openshell-version.test.ts b/test/e2e/support/candidate-openshell-version.test.ts index d922e87780f..5c486e78a69 100644 --- a/test/e2e/support/candidate-openshell-version.test.ts +++ b/test/e2e/support/candidate-openshell-version.test.ts @@ -2,11 +2,20 @@ // SPDX-License-Identifier: Apache-2.0 import { readFileSync } from "node:fs"; +import assert from "node:assert/strict"; import { describe, expect, it, vi } from "vitest"; +import * as installerPins from "../../../scripts/checks/extract-installer-pins.mts"; import { candidateOpenShellVersion } from "../../../tools/e2e/candidate-openshell-version.mts"; const sha = "a".repeat(40); const repository = "NVIDIA/NemoClaw"; +const blueprint = readFileSync( + new URL("../../../nemoclaw-blueprint/blueprint.yaml", import.meta.url), + "utf8", +); +const blueprintVersions = [...blueprint.matchAll(/^max_openshell_version: "(\d+\.\d+\.\d+)"$/gm)]; +assert.equal(blueprintVersions.length, 1, "Expected one blueprint OpenShell pin"); +const pinnedVersion = blueprintVersions[0]![1]!; function sourceResponse(url: string) { const parsed = new URL(url, "https://api.github.com"); expect(parsed.searchParams.get("ref")).toBe(sha); @@ -24,10 +33,39 @@ function sourceResponse(url: string) { describe("candidate OpenShell selection", () => { it("reads only immutable candidate data and selects the reviewed runtime", async () => { const request = vi.fn(async (url: string) => sourceResponse(url)); - await expect(candidateOpenShellVersion(repository, sha, request)).resolves.toBe("0.0.116"); + await expect(candidateOpenShellVersion(repository, sha, request)).resolves.toMatch( + /^\d+\.\d+\.\d+$/, + ); expect(request).toHaveBeenCalledTimes(4); }); + it("returns the trusted verifier's selection without substituting a workflow pin", async () => { + const verifier = vi.spyOn(installerPins, "validateInstallerSources").mockReturnValueOnce({ + releaseVersion: "9.8.7", + pins: [], + installerReleases: [], + installerTemplateSha256: "", + brevTemplateSha256: "", + }); + try { + await expect( + candidateOpenShellVersion(repository, sha, async (url) => { + const blob = sourceResponse(url); + const source = `fixture ${blob.path}`; + return { ...blob, content: Buffer.from(source).toString("base64"), size: source.length }; + }), + ).resolves.toBe("9.8.7"); + expect(verifier).toHaveBeenCalledExactlyOnceWith({ + blueprintSource: "fixture nemoclaw-blueprint/blueprint.yaml", + installerSource: "fixture scripts/install-openshell.sh", + brevInstallerSource: "fixture scripts/brev-launchable-ci-cpu.sh", + supervisorRuntimeSource: "fixture src/lib/onboard/docker-driver-gateway-runtime.ts", + }); + } finally { + verifier.mockRestore(); + } + }); + it.each(["main", "a".repeat(39), `${sha}\nversion=9.9.9`])( "rejects mutable or malformed revision %s", async (revision) => { @@ -75,7 +113,7 @@ describe("candidate OpenShell selection", () => { { name: "unknown release", target: /.*/, - rewrite: (source: string) => source.replaceAll("0.0.116", "9.9.9"), + rewrite: (source: string) => source.replaceAll(pinnedVersion, "9.9.9"), }, { name: "mismatched blueprint", diff --git a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts index c9ead3b0031..53266342f9c 100644 --- a/test/e2e/support/managed-image-protected-runtime-workflow.test.ts +++ b/test/e2e/support/managed-image-protected-runtime-workflow.test.ts @@ -56,6 +56,92 @@ describe("protected managed-image runtime workflow", () => { expect(validateManagedImageProtectedRuntimeWorkflow(workflow())).toEqual([]); }); + it.each([ + ["Bind reviewed candidate OpenShell runtime", "if", "false"], + ["Bind reviewed candidate OpenShell runtime", "continue-on-error", true], + ["Bind reviewed candidate OpenShell runtime", "env", { CHECKOUT_SHA: "other" }], + ["Bind reviewed candidate OpenShell runtime", "run", "echo bypass"], + ["Restore trusted OpenShell sources", "if", "success()"], + ["Restore trusted OpenShell sources", "run", "echo bypass"], + ["Build trusted CLI with reviewed OpenShell runtime", "if", "false"], + ["Build trusted CLI with reviewed OpenShell runtime", "run", "echo bypass"], + ["Prepare E2E workspace", "with", {}], + ])("rejects OpenShell step %s with altered %s", (name, field, replacement) => { + const value = workflow(); + namedStep(value, String(name))[String(field)] = replacement; + expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); + }); + + it("rejects building the CLI before projecting candidate OpenShell", () => { + const value = workflow(); + const job = runtimeJob(value); + const steps = job.steps as Array>; + const build = namedStep(value, "Build trusted CLI with reviewed OpenShell runtime"); + const projection = namedStep(value, "Bind reviewed candidate OpenShell runtime"); + const index = steps.indexOf(projection); + job.steps = [ + ...steps.slice(0, index), + build, + ...steps.slice(index).filter((step) => step !== build), + ]; + expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); + }); + + it.each([ + ["Download reviewed OpenShell SDK archive", "with", { name: "other-run" }], + ["Download reviewed OpenShell SDK archive", "if", "false"], + [ + "Install reviewed OpenShell SDK from trusted controller", + "uses", + "./.candidate-runtime/.github/actions/install-reviewed-openshell-sdk", + ], + ["Install reviewed OpenShell SDK from trusted controller", "if", "false"], + ["Install reviewed OpenShell SDK from trusted controller", "continue-on-error", true], + ])("rejects SDK step %s with altered %s", (name, field, replacement) => { + const value = workflow(); + namedStep(value, String(name))[String(field)] = replacement; + expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); + }); + + it("rejects building the CLI before installing the projected SDK", () => { + const value = workflow(); + const job = runtimeJob(value); + const steps = job.steps as Array>; + const build = namedStep(value, "Build trusted CLI with reviewed OpenShell runtime"); + const install = namedStep(value, "Install reviewed OpenShell SDK from trusted controller"); + const index = steps.indexOf(install); + job.steps = [ + ...steps.slice(0, index), + build, + ...steps.slice(index).filter((step) => step !== build), + ]; + expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); + }); + + it("rejects missing source verification", () => { + const value = workflow(); + const step = namedStep( + value, + "Run all-agent GPU, local inference, rollback, and cleanup qualification", + ); + const command = + 'node tools/e2e/protected-openshell-workspace.mts verify > "$E2E_ARTIFACT_DIR/openshell-projection-verified.json"'; + step.run = String(step.run).replace(command, ""); + expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); + }); + + it("rejects source verification after qualification", () => { + const value = workflow(); + const step = namedStep( + value, + "Run all-agent GPU, local inference, rollback, and cleanup qualification", + ); + const command = + 'node tools/e2e/protected-openshell-workspace.mts verify > "$E2E_ARTIFACT_DIR/openshell-projection-verified.json"'; + step.run = `${String(step.run).replace(command, "")}\n${command}\n`; + expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); + }); + it("rejects a runtime job that exceeds the 75 minute budget", () => { const value = workflow(); runtimeJob(value)["timeout-minutes"] = 300; @@ -102,8 +188,10 @@ describe("protected managed-image runtime workflow", () => { it.each([ "node scripts/checks/protected-dcode-base-receipt.mts verify", - '"$verified_dcode" == "$cached_dcode"', - '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base-receipt.json"', + '"$verified" == "$reference"', + '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/${name}-base-receipt.json" "$agent"', + '"$CANDIDATE_BASES" == false', + '[[ "$CANDIDATE_BASES" == false &&', ])("rejects a candidate OCI base handoff without %s", (fragment) => { const value = workflow(); const step = namedStep(value, "Resolve digest-pinned amd64 runtime base images"); @@ -111,6 +199,16 @@ describe("protected managed-image runtime workflow", () => { expect(validateManagedImageProtectedRuntimeWorkflow(value)).not.toEqual([]); }); + it.each([ + ["managed-image-multiarch-startup", "Resolve digest-pinned platform base images"], + ["managed-image-protected-runtime", "Resolve digest-pinned amd64 runtime base images"], + ])("rejects a disabled candidate base selector in %s", (jobId, name) => { + const value = workflow(); + const step = namedJobStep(value, jobId, name); + (step.env as Record).CANDIDATE_BASES = "false"; + expect(validateE2eWorkflow(value)).not.toEqual([]); + }); + it("requires cancellation cleanup for the derived Docker Engine 27 receipt daemon", () => { const value = workflow(); const cleanup = namedMultiarchStep(value, "Remove owned Docker Engine 27 receipt daemon"); @@ -655,7 +753,7 @@ describe("protected managed-image runtime workflow", () => { runtimeJob(value).needs = ["generate-matrix"]; expect(validateManagedImageProtectedRuntimeWorkflow(value)).toContain( - "managed-image-protected-runtime must depend on base-image-publication, generate-matrix, and managed-image-multiarch-startup", + "managed-image-protected-runtime must depend on base-image-publication, generate-matrix, managed-image-multiarch-startup, and package-openshell-sdk", ); }); diff --git a/test/e2e/support/openshell-sdk-install.test.ts b/test/e2e/support/openshell-sdk-install.test.ts index f9affcb66d2..ac9c3296d3c 100644 --- a/test/e2e/support/openshell-sdk-install.test.ts +++ b/test/e2e/support/openshell-sdk-install.test.ts @@ -14,6 +14,7 @@ import { validateReviewedOpenShellSdkInstallAction, } from "../../../tools/e2e/reviewed-openshell-sdk-install-workflow-boundary.mts"; import { parseNpmPackArchives } from "./openshell-sdk-pack-archives.ts"; +import { projectProtectedOpenShellSdk } from "../../../tools/e2e/protected-openshell-projection.mts"; describe("reviewed OpenShell SDK E2E boundary", () => { it.for([ @@ -52,7 +53,7 @@ describe("reviewed OpenShell SDK E2E boundary", () => { }); it.each(["0.0.106", "0.0.116"] as const)( - "installs and imports SDK %s without credentials or scripts", + "projects, installs and imports SDK %s without credentials or scripts", (selectedVersion) => { const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-sdk-action-execution-")); const trustedRoot = path.join(directory, "trusted"); @@ -232,6 +233,34 @@ export class OpenShellClient { static connect() { return transport; } } version: "1.0.0", }), ); + const packageSource = fs.readFileSync(path.join(targetRoot, "package.json"), "utf8"); + const lockSource = fs.readFileSync(path.join(targetRoot, "package-lock.json"), "utf8"); + const baselinePackage = JSON.parse(packageSource); + const baselineLock = JSON.parse(lockSource); + baselinePackage.optionalDependencies["@nvidia/openshell-sdk"] = "0.0.106"; + baselineLock.packages[""].optionalDependencies["@nvidia/openshell-sdk"] = "0.0.106"; + Object.assign(baselineLock.packages["node_modules/@nvidia/openshell-sdk"], { + version: "0.0.106", + resolved: tarballUrl, + integrity, + }); + const projected = projectProtectedOpenShellSdk( + { packageSource, lockSource }, + { + packageSource: JSON.stringify(baselinePackage), + lockSource: JSON.stringify(baselineLock), + auditSource: fs.readFileSync( + path.join(trustedRoot, "ci/reviewed-npm-audit.json"), + "utf8", + ), + }, + selectedVersion, + ); + fs.writeFileSync(path.join(targetRoot, "package.json"), projected.files["package.json"]!); + fs.writeFileSync( + path.join(targetRoot, "package-lock.json"), + projected.files["package-lock.json"]!, + ); fs.mkdirSync(path.join(targetRoot, "nemoclaw")); fs.writeFileSync( path.join(targetRoot, "nemoclaw", "package-lock.json"), diff --git a/test/e2e/support/protected-dcode-base-receipt.test.ts b/test/e2e/support/protected-dcode-base-receipt.test.ts index 8c15a1c161e..ffb53d6ad26 100644 --- a/test/e2e/support/protected-dcode-base-receipt.test.ts +++ b/test/e2e/support/protected-dcode-base-receipt.test.ts @@ -20,7 +20,10 @@ afterEach(() => { fs.rmSync(directory, { recursive: true, force: true }); }); -function fixture(platform: ProtectedDcodeBaseIdentity["platform"] = "linux/amd64") { +function fixture( + platform: ProtectedDcodeBaseIdentity["platform"] = "linux/amd64", + agent: "openclaw" | "hermes" | "langchain-deepagents-code" = "langchain-deepagents-code", +) { const root = fs.mkdtempSync(path.join(os.tmpdir(), "protected-dcode-base-")); directories.push(root); const layout = path.join(root, "base"); @@ -48,7 +51,7 @@ function fixture(platform: ProtectedDcodeBaseIdentity["platform"] = "linux/amd64 "org.opencontainers.image.revision": expected.sourceRevision, "org.opencontainers.image.source": "https://github.com/NVIDIA/NemoClaw", "io.nvidia.nemoclaw.managed-image.cohort": expected.cohort, - "io.nvidia.nemoclaw.agent": "langchain-deepagents-code", + "io.nvidia.nemoclaw.agent": agent, }, }, }, @@ -78,7 +81,7 @@ function fixture(platform: ProtectedDcodeBaseIdentity["platform"] = "linux/amd64 JSON.stringify({ imageLayoutVersion: "1.0.0" }), ); const receiptPath = path.join(root, "receipt.json"); - const receipt = inspectProtectedDcodeBase(layout, expected); + const receipt = inspectProtectedDcodeBase(layout, expected, agent); fs.writeFileSync(receiptPath, JSON.stringify(receipt)); return { layout, @@ -95,6 +98,37 @@ function fixture(platform: ProtectedDcodeBaseIdentity["platform"] = "linux/amd64 } describe("protected DCode base artifact handoff", () => { + it.each(["openclaw", "hermes", "langchain-deepagents-code"] as const)( + "binds %s to its OCI artifact", + (agent) => { + const f = fixture("linux/amd64", agent); + expect(verifyProtectedDcodeBaseReceipt(f.layout, f.receiptPath, f.expected, agent)).toEqual( + f.receipt, + ); + }, + ); + + it.each([ + ["openclaw", "hermes"], + ["openclaw", "langchain-deepagents-code"], + ["hermes", "openclaw"], + ["hermes", "langchain-deepagents-code"], + ["langchain-deepagents-code", "openclaw"], + ["langchain-deepagents-code", "hermes"], + ] as const)("rejects %s OCI bytes when %s is required", (agent, other) => { + const f = fixture("linux/amd64", agent); + expect(() => + verifyProtectedDcodeBaseReceipt(f.layout, f.receiptPath, f.expected, other), + ).toThrow(/config/); + }); + + it("rejects an unsupported agent before reading the layout", () => { + const f = fixture(); + expect(() => + inspectProtectedDcodeBase("/missing", f.expected, "../other" as "openclaw"), + ).toThrow(/not supported/); + }); + it("writes receipts once and refuses to overwrite existing evidence", () => { const f = fixture(); const receiptPath = path.join(f.root, "cli-receipt.json"); diff --git a/test/e2e/support/protected-openshell-projection.test.ts b/test/e2e/support/protected-openshell-projection.test.ts new file mode 100644 index 00000000000..dea6bfd9b2c --- /dev/null +++ b/test/e2e/support/protected-openshell-projection.test.ts @@ -0,0 +1,283 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { readFileSync } from "node:fs"; +import { describe, expect, it } from "vitest"; +import { validateOpenShellFeatureGateSource } from "../../../scripts/checks/extract-installer-pins.mts"; +import { + projectProtectedOpenShellSources, + projectProtectedOpenShellSdk, +} from "../../../tools/e2e/protected-openshell-projection.mts"; + +function read(source: string) { + return readFileSync(new URL(`../../../${source}`, import.meta.url), "utf8"); +} +function fixture() { + return { + candidate: { + blueprintSource: read("nemoclaw-blueprint/blueprint.yaml"), + installerSource: read("scripts/install-openshell.sh"), + brevInstallerSource: read("scripts/brev-launchable-ci-cpu.sh"), + supervisorRuntimeSource: read("src/lib/onboard/docker-driver-gateway-runtime.ts"), + featureGateSource: read("src/lib/onboard/openshell-feature-gate.ts"), + }, + trusted: { + blueprintSource: + 'name: trusted-controller\nmin_openshell_version: "0.0.1"\nmax_openshell_version: "0.0.1"\n', + versionSource: + 'export const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "0.0.1";\nexport const otherSetting = "unchanged";\n', + }, + }; +} + +describe("protected OpenShell source projection", () => { + it("binds the controller to reviewed release data without adopting the candidate blueprint", () => { + const { candidate, trusted } = fixture(); + candidate.blueprintSource += '\nunrelated_candidate_field: "never copy"\n'; + const projected = projectProtectedOpenShellSources(candidate, trusted); + expect(projected.releaseVersion).toMatch(/^\d+\.\d+\.\d+$/); + expect(Object.keys(projected.files).sort()).toEqual([ + "nemoclaw-blueprint/blueprint.yaml", + "scripts/install-openshell.sh", + "src/lib/onboard/docker-driver-gateway-runtime.ts", + "src/lib/onboard/openshell-feature-gate.ts", + "src/lib/onboard/openshell-version.ts", + ]); + expect(projected.files["nemoclaw-blueprint/blueprint.yaml"]).toBe( + `name: trusted-controller\nmin_openshell_version: "${projected.releaseVersion}"\nmax_openshell_version: "${projected.releaseVersion}"\n`, + ); + expect(projected.files["src/lib/onboard/openshell-version.ts"]).toBe( + `export const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "${projected.releaseVersion}";\nexport const otherSetting = "unchanged";\n`, + ); + }); + + it.each([ + "installerSource", + "brevInstallerSource", + "supervisorRuntimeSource", + "featureGateSource", + ] as const)("rejects unreviewed operations in %s", (field) => { + const { candidate, trusted } = fixture(); + candidate[field] += "\nunreviewed_operation();\n"; + expect(() => projectProtectedOpenShellSources(candidate, trusted)).toThrow(/template/); + }); + + it.each(["blueprintSource", "versionSource"] as const)( + "rejects ambiguous trusted %s pins", + (field) => { + const { candidate, trusted } = fixture(); + trusted[field] += trusted[field]; + expect(() => projectProtectedOpenShellSources(candidate, trusted)).toThrow(/requires one/); + }, + ); + + it("rejects a reviewed supervisor template that selects a different release", () => { + const { candidate, trusted } = fixture(); + candidate.supervisorRuntimeSource = candidate.supervisorRuntimeSource.replace( + /^const QUALIFIED_STABLE_OPENSHELL_VERSION = ".*";$/m, + 'const QUALIFIED_STABLE_OPENSHELL_VERSION = "9.9.9";', + ); + expect(() => projectProtectedOpenShellSources(candidate, trusted)).toThrow(); + }); + + it.each([ + { name: "unknown binary", map: ` ["${"a".repeat(64)}", "0.0.116"],\n` }, + { name: "executable entry", map: ' [process.env.BINARY, "0.0.116"],\n' }, + { name: "unterminated comment", map: " /* ignore remaining map\n" }, + ])("rejects a feature map with $name", ({ map }) => { + const { candidate, trusted } = fixture(); + candidate.featureGateSource = candidate.featureGateSource.replace( + "const PINNED_SANDBOX_BUILD_VERSIONS = new Map([\n", + `const PINNED_SANDBOX_BUILD_VERSIONS = new Map([\n${map}`, + ); + expect(() => projectProtectedOpenShellSources(candidate, trusted)).toThrow(/feature gate/); + }); + + it("rejects duplicate binary identities before using the map", () => { + const { candidate, trusted } = fixture(); + candidate.featureGateSource = candidate.featureGateSource.replace( + /^( \["[a-f0-9]{64}", "[0-9.]+"\],)$/m, + "$1\n$1", + ); + expect(() => projectProtectedOpenShellSources(candidate, trusted)).toThrow(/unique/); + }); + + it("rejects an unknown release and oversized feature source", () => { + const { candidate } = fixture(); + expect(() => validateOpenShellFeatureGateSource(candidate.featureGateSource, "9.9.9")).toThrow( + /base-trusted/, + ); + expect(() => + validateOpenShellFeatureGateSource("x".repeat(1024 * 1024 + 1), "0.0.116"), + ).toThrow(/too large/); + }); +}); + +const sdkName = "@nvidia/openshell-sdk"; +const sdkLocation = `node_modules/${sdkName}`; +function sdkFixture() { + const auditSource = read("ci/reviewed-npm-audit.json"); + const config = JSON.parse(auditSource); + const baseline = config.sourceRegistryPackage; + const replacement = config.sourceRegistryPackageReplacement; + const baseVersion = baseline.packageSpec.split("@").at(-1); + const version = replacement.packageSpec.split("@").at(-1); + const packageRecord = { + name: "trusted", + scripts: { build: "trusted-build" }, + optionalDependencies: { [sdkName]: baseVersion }, + dependencies: { unrelated: "1.0.0" }, + }; + const lock = { + lockfileVersion: 3, + packages: { + "": { ...packageRecord }, + [sdkLocation]: { + version: baseVersion, + resolved: baseline.tarballUrl, + integrity: baseline.integrity, + optional: true, + dependencies: { helper: "1.0.0" }, + }, + "node_modules/helper": { + version: "1.0.0", + resolved: "https://registry.npmjs.org/helper/-/helper-1.0.0.tgz", + integrity: baseline.integrity, + }, + "node_modules/unrelated": { version: "1.0.0" }, + }, + }; + const candidatePackage = structuredClone(packageRecord); + candidatePackage.optionalDependencies[sdkName] = version; + candidatePackage.scripts.build = "unreviewed-build"; + candidatePackage.dependencies.unrelated = "9.0.0"; + const candidateLock = structuredClone(lock); + candidateLock.packages[""] = candidatePackage; + Object.assign(candidateLock.packages[sdkLocation], { + version, + resolved: replacement.tarballUrl, + integrity: replacement.integrity, + }); + candidateLock.packages["node_modules/unrelated"].version = "9.0.0"; + return { + version, + candidate: { + packageSource: JSON.stringify(candidatePackage), + lockSource: JSON.stringify(candidateLock), + }, + trusted: { + packageSource: JSON.stringify(packageRecord), + lockSource: JSON.stringify(lock), + auditSource, + }, + }; +} + +describe("protected OpenShell SDK projection", () => { + it("selects the candidate archive and preserves unrelated trusted dependencies and scripts", () => { + const { candidate, trusted, version } = sdkFixture(); + const result = projectProtectedOpenShellSdk(candidate, trusted, version); + const manifest = JSON.parse(result.files["package.json"]!); + const lock = JSON.parse(result.files["package-lock.json"]!); + expect(result.sdkVersion).toBe(version); + expect(manifest).toEqual({ + ...JSON.parse(trusted.packageSource), + optionalDependencies: { [sdkName]: version }, + }); + expect(lock.packages[sdkLocation]).toEqual( + JSON.parse(candidate.lockSource).packages[sdkLocation], + ); + expect(lock.packages["node_modules/unrelated"]).toEqual({ version: "1.0.0" }); + }); + + it("rejects a runtime and SDK version mismatch", () => { + const { candidate, trusted } = sdkFixture(); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, "9.9.9")).toThrow( + /match the selected/, + ); + }); + + it.each(["resolved", "integrity"])("rejects substituted candidate SDK %s", (field) => { + const { candidate, trusted, version } = sdkFixture(); + const lock = JSON.parse(candidate.lockSource); + lock.packages[sdkLocation][field] = "unreviewed"; + candidate.lockSource = JSON.stringify(lock); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow(/not trusted/); + }); + + it("rejects an SDK absent from trusted archive records", () => { + const { candidate, trusted, version } = sdkFixture(); + const config = JSON.parse(trusted.auditSource); + delete config.sourceRegistryPackageReplacement; + trusted.auditSource = JSON.stringify(config); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow(/not trusted/); + }); + + it.each(["version", "integrity"])("rejects candidate changes to SDK transitive %s", (field) => { + const { candidate, trusted, version } = sdkFixture(); + const lock = JSON.parse(candidate.lockSource); + lock.packages["node_modules/helper"][field] = "substituted"; + candidate.lockSource = JSON.stringify(lock); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow( + /transitive dependencies/, + ); + }); + + it("rejects a nested dependency that shadows the trusted dependency", () => { + const { candidate, trusted, version } = sdkFixture(); + const lock = JSON.parse(candidate.lockSource); + lock.packages[`${sdkLocation}/node_modules/helper`] = lock.packages["node_modules/helper"]; + candidate.lockSource = JSON.stringify(lock); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow( + /transitive dependencies/, + ); + }); + + it("rejects new SDK dependency metadata", () => { + const { candidate, trusted, version } = sdkFixture(); + const lock = JSON.parse(candidate.lockSource); + lock.packages[sdkLocation].dependencies.injected = "1.0.0"; + candidate.lockSource = JSON.stringify(lock); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow( + /dependency metadata/, + ); + }); + + it("rejects a mismatched SDK lock identity", () => { + const { candidate, trusted, version } = sdkFixture(); + const lock = JSON.parse(candidate.lockSource); + lock.packages[sdkLocation].version = "9.9.9"; + candidate.lockSource = JSON.stringify(lock); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow( + /identities disagree/, + ); + }); + + it("rejects a mismatched root lock identity", () => { + const { candidate, trusted, version } = sdkFixture(); + const lock = JSON.parse(candidate.lockSource); + lock.packages[""].optionalDependencies[sdkName] = "9.9.9"; + candidate.lockSource = JSON.stringify(lock); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow( + /identities disagree/, + ); + }); + + it("rejects an unsupported lockfile version", () => { + const { candidate, trusted, version } = sdkFixture(); + const lock = JSON.parse(candidate.lockSource); + lock.lockfileVersion = 2; + candidate.lockSource = JSON.stringify(lock); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow( + /lockfileVersion/, + ); + }); + + it("rejects ambiguous manifest declarations", () => { + const { candidate, trusted, version } = sdkFixture(); + const manifest = JSON.parse(candidate.packageSource); + manifest.dependencies[sdkName] = version; + candidate.packageSource = JSON.stringify(manifest); + expect(() => projectProtectedOpenShellSdk(candidate, trusted, version)).toThrow(/ambiguous/); + }); +}); diff --git a/test/e2e/support/protected-openshell-workspace.test.ts b/test/e2e/support/protected-openshell-workspace.test.ts new file mode 100644 index 00000000000..727b5a0006e --- /dev/null +++ b/test/e2e/support/protected-openshell-workspace.test.ts @@ -0,0 +1,225 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import * as fs from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { manageProtectedOpenShellWorkspace } from "../../../tools/e2e/protected-openshell-workspace.mts"; + +vi.mock("node:fs", async (importOriginal) => { + const original = await importOriginal(); + return { ...original, renameSync: vi.fn(original.renameSync) }; +}); + +const sources = [ + "nemoclaw-blueprint/blueprint.yaml", + "scripts/install-openshell.sh", + "scripts/brev-launchable-ci-cpu.sh", + "src/lib/onboard/docker-driver-gateway-runtime.ts", + "src/lib/onboard/openshell-feature-gate.ts", + "src/lib/onboard/openshell-version.ts", + "package.json", + "package-lock.json", + "ci/reviewed-npm-audit.json", +]; +const roots: string[] = []; +afterEach(() => { + vi.restoreAllMocks(); + for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); +}); + +function git(root: string, ...args: string[]) { + return execFileSync( + "git", + [ + "-c", + "core.hooksPath=/dev/null", + "-c", + "commit.gpgsign=false", + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "-C", + root, + ...args, + ], + { encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }, + ).trim(); +} +function fixture() { + const root = fs.mkdtempSync(join(tmpdir(), "protected-openshell-workspace-")); + roots.push(root); + const trustedRoot = join(root, "trusted"); + const candidateRoot = join(root, "candidate"); + for (const target of [trustedRoot, candidateRoot]) { + fs.mkdirSync(target); + git(target, "init", "--quiet"); + for (const path of sources) { + const file = join(target, path); + fs.mkdirSync(dirname(file), { recursive: true }); + fs.copyFileSync(new URL(`../../../${path}`, import.meta.url), file); + fs.chmodSync(file, path.endsWith(".sh") ? 0o755 : 0o644); + } + fs.writeFileSync(join(target, "controller.txt"), "trusted fixture\n"); + } + fs.writeFileSync( + join(trustedRoot, "nemoclaw-blueprint/blueprint.yaml"), + 'name: fixture\nmin_openshell_version: "0.0.1"\nmax_openshell_version: "0.0.1"\n', + ); + fs.writeFileSync( + join(trustedRoot, "src/lib/onboard/openshell-version.ts"), + 'export const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "0.0.1";\n', + ); + git(trustedRoot, "add", "."); + git(trustedRoot, "commit", "--quiet", "-m", "fixture"); + git(candidateRoot, "add", "."); + git(candidateRoot, "commit", "--quiet", "-m", "fixture"); + return { + trustedRoot, + candidateRoot, + workflowSha: git(trustedRoot, "rev-parse", "HEAD"), + candidateSha: git(candidateRoot, "rev-parse", "HEAD"), + }; +} + +describe("protected OpenShell workspace", () => { + it("binds the workflow CLI to dispatch commits and emits records for each phase", () => { + const input = fixture(); + const command = fileURLToPath( + new URL("../../../tools/e2e/protected-openshell-workspace.mts", import.meta.url), + ); + const options = { + encoding: "utf8", + env: { + ...process.env, + GITHUB_WORKSPACE: input.trustedRoot, + NEMOCLAW_E2E_TESTED_ROOT: input.candidateRoot, + CHECKOUT_SHA: input.candidateSha, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA: input.workflowSha, + }, + } as const; + const expected = { + workflowSha: input.workflowSha, + candidateSha: input.candidateSha, + }; + const prepared = execFileSync(process.execPath, [command, "prepare"], options); + expect(JSON.parse(prepared)).toMatchObject({ ...expected, operation: "prepare" }); + const verified = execFileSync(process.execPath, [command, "verify"], options); + expect(JSON.parse(verified)).toMatchObject({ ...expected, operation: "verify" }); + const restored = execFileSync(process.execPath, [command, "restore"], options); + expect(JSON.parse(restored)).toMatchObject({ ...expected, operation: "restore" }); + expect(git(input.trustedRoot, "status", "--porcelain")).toBe(""); + }); + + it("prepares candidate pins, verifies their bytes, and restores the trusted checkout", () => { + const input = fixture(); + const prepared = manageProtectedOpenShellWorkspace("prepare", input); + expect(prepared).toMatchObject({ + workflowSha: input.workflowSha, + candidateSha: input.candidateSha, + operation: "prepare", + }); + expect(prepared.files).toHaveLength(7); + expect(manageProtectedOpenShellWorkspace("verify", input)).toEqual({ + ...prepared, + operation: "verify", + }); + const actualDigests = prepared.files.map((file) => ({ + path: file.path, + sha256: createHash("sha256") + .update(fs.readFileSync(join(input.trustedRoot, file.path))) + .digest("hex"), + })); + expect(actualDigests).toEqual(prepared.files); + manageProtectedOpenShellWorkspace("restore", input); + expect(git(input.trustedRoot, "status", "--porcelain")).toBe(""); + expect(() => manageProtectedOpenShellWorkspace("restore", input)).not.toThrow(); + }); + + it.each(["workflowSha", "candidateSha"] as const)( + "rejects a mismatched %s before changing files", + (key) => { + const input = fixture(); + input[key] = "a".repeat(40); + expect(() => manageProtectedOpenShellWorkspace("prepare", input)).toThrow(/dispatch commit/); + expect(git(input.trustedRoot, "status", "--porcelain")).toBe(""); + }, + ); + + it("uses committed candidate blobs instead of mutable worktree content", () => { + const input = fixture(); + fs.appendFileSync( + join(input.candidateRoot, "scripts/install-openshell.sh"), + "\nunreviewed_operation\n", + ); + const result = manageProtectedOpenShellWorkspace("prepare", input); + expect(result.releaseVersion).toMatch(/^\d+\.\d+\.\d+$/); + expect(() => manageProtectedOpenShellWorkspace("verify", input)).not.toThrow(); + }); + + it("rejects committed unreviewed candidate operations", () => { + const input = fixture(); + fs.appendFileSync( + join(input.candidateRoot, "scripts/install-openshell.sh"), + "\nunreviewed_operation\n", + ); + git(input.candidateRoot, "add", "."); + git(input.candidateRoot, "commit", "--quiet", "-m", "unreviewed"); + input.candidateSha = git(input.candidateRoot, "rev-parse", "HEAD"); + expect(() => manageProtectedOpenShellWorkspace("prepare", input)).toThrow(/template/); + expect(git(input.trustedRoot, "status", "--porcelain")).toBe(""); + }); + + it.each(["prepare", "verify", "restore"] as const)( + "rejects unrelated controller edits during %s", + (operation) => { + const input = fixture(); + fs.writeFileSync(join(input.trustedRoot, "controller.txt"), "modified"); + expect(() => manageProtectedOpenShellWorkspace(operation, input)).toThrow(/Unrelated/); + expect(fs.readFileSync(join(input.trustedRoot, "controller.txt"), "utf8")).toBe("modified"); + }, + ); + + it.each(["file", "parent"])("rejects a symlinked destination %s without following it", (kind) => { + const input = fixture(); + const path = join( + input.trustedRoot, + kind === "file" ? "scripts/install-openshell.sh" : "scripts", + ); + const moved = `${path}.retained`; + fs.renameSync(path, moved); + fs.symlinkSync(moved, path); + expect(() => manageProtectedOpenShellWorkspace("prepare", input)).toThrow(/Unsafe/); + expect(fs.readlinkSync(path)).toBe(moved); + }); + + it("rejects tampering before verification or restoration", () => { + const input = fixture(); + manageProtectedOpenShellWorkspace("prepare", input); + const path = join(input.trustedRoot, "src/lib/onboard/openshell-version.ts"); + fs.appendFileSync(path, "\nunreviewed_operation();\n"); + const before = git(input.trustedRoot, "diff", "--no-ext-diff"); + expect(() => manageProtectedOpenShellWorkspace("verify", input)).toThrow(/Unexpected verify/); + expect(() => manageProtectedOpenShellWorkspace("restore", input)).toThrow(/Unexpected restore/); + expect(git(input.trustedRoot, "diff", "--no-ext-diff")).toBe(before); + }); + + it("rolls back an incomplete prepare when a later replacement fails", async () => { + const input = fixture(); + const { renameSync: original } = await vi.importActual("node:fs"); + vi.mocked(fs.renameSync) + .mockImplementationOnce(original) + .mockImplementationOnce(() => { + throw new Error("fixture replacement failure"); + }); + expect(() => manageProtectedOpenShellWorkspace("prepare", input)).toThrow( + /fixture replacement failure/, + ); + expect(git(input.trustedRoot, "status", "--porcelain")).toBe(""); + }); +}); diff --git a/test/e2e/support/workflow-prerequisites.test.ts b/test/e2e/support/workflow-prerequisites.test.ts index c4810553565..19d20122445 100644 --- a/test/e2e/support/workflow-prerequisites.test.ts +++ b/test/e2e/support/workflow-prerequisites.test.ts @@ -1,6 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; import { describe, expect, it } from "vitest"; import { requiresManagedImages } from "../../../tools/e2e/workflow-prerequisites.mts"; import { validateE2eWorkflow } from "../../../tools/e2e/workflow-boundary.mts"; @@ -9,6 +13,22 @@ import { buildE2eWorkflowPlan, selectedWorkflowJobs } from "../../../tools/e2e/w describe("selected E2E prerequisites", () => { it.each([ + { + name: "unconditional version resolution", + mutate: (workflow: Workflow) => { + delete workflow.jobs["generate-matrix"]!.steps!.find( + (step) => step.id === "openshell_version", + )!.if; + }, + }, + { + name: "skipped version resolution", + mutate: (workflow: Workflow) => { + workflow.jobs["generate-matrix"]!.steps!.find( + (step) => step.id === "openshell_version", + )!.if = "false"; + }, + }, { name: "version output", mutate: (workflow: Workflow) => { @@ -79,6 +99,44 @@ describe("selected E2E prerequisites", () => { expect(requiresManagedImages([], jobs)).toBe(false); }); + it("emits the native producer selection without a managed image prerequisite", () => { + const workflow = readWorkflow() as unknown as Workflow; + const script = workflow.jobs["generate-matrix"]!.steps!.find( + (step) => step.id === "matrix", + )!.run!; + const directory = mkdtempSync(join(tmpdir(), "native-producer-plan-")); + const output = join(directory, "output"); + try { + const result = spawnSync("bash", ["-c", script], { + encoding: "utf8", + env: { + PATH: process.env.PATH, + JOBS: "native-runtime-qualification-producer", + TARGETS: "", + GITHUB_OUTPUT: output, + }, + timeout: 10_000, + }); + expect(result.status, result.stderr).toBe(0); + const values = Object.fromEntries( + readFileSync(output, "utf8") + .trim() + .split("\n") + .map((line) => { + const separator = line.indexOf("="); + return [line.slice(0, separator), line.slice(separator + 1)]; + }), + ); + expect(values.managed_image_required).toBe("false"); + expect(JSON.parse(values.selected_workflow_jobs!)).toEqual([ + "native-runtime-qualification-producer", + ]); + expect(JSON.parse(values.matrix!)).toEqual([]); + } finally { + rmSync(directory, { recursive: true, force: true }); + } + }); + it("rejects cycles and malformed dependencies", () => { expect(() => requiresManagedImages(["a"], { a: { needs: "b" }, b: { needs: "a" } })).toThrow( "Cyclic", diff --git a/test/inference/managed/managed-image-pr-base-resolution.test.ts b/test/inference/managed/managed-image-pr-base-resolution.test.ts index ad155bcb8ef..991dde3b1b0 100644 --- a/test/inference/managed/managed-image-pr-base-resolution.test.ts +++ b/test/inference/managed/managed-image-pr-base-resolution.test.ts @@ -115,14 +115,14 @@ exit 90 } }); -it.each([ +const publishedBaseCases = [ { candidateContents: "unrelated candidate change\n", candidatePath: "README.md", expectedLocal: false, failPublishedPull: false, rejectCopyParsing: false, - title: "reuses a published DCode base built from the same runtime contract inputs", + title: "reuses a published base built from the same inputs", }, { candidateContents: "print('new contract')\n", @@ -130,7 +130,7 @@ it.each([ expectedLocal: true, failPublishedPull: false, rejectCopyParsing: false, - title: "builds the DCode base locally when its published source predates the runtime contract", + title: "builds locally when the published source predates a copied runtime contract", }, { candidateContents: "security patch v2\n", @@ -138,7 +138,23 @@ it.each([ expectedLocal: true, failPublishedPull: false, rejectCopyParsing: false, - title: "builds the DCode base locally when a copied security input changed", + title: "builds locally when a copied security input changed", + }, + { + candidateContents: "deepagents==0.8.0\n", + candidatePath: "agents/langchain-deepagents-code/requirements.lock", + expectedLocal: true, + failPublishedPull: false, + rejectCopyParsing: false, + title: "builds locally when a copied dependency lock changed without a Dockerfile edit", + }, + { + candidateContents: ".git\nREADME.md\n", + candidatePath: ".dockerignore", + expectedLocal: true, + failPublishedPull: false, + rejectCopyParsing: false, + title: "builds locally when the Docker context exclusions changed", }, { candidateContents: @@ -147,7 +163,7 @@ it.each([ expectedLocal: true, failPublishedPull: false, rejectCopyParsing: false, - title: "builds the DCode base locally when its COPY parser changed", + title: "builds locally without executing a changed COPY parser", }, { candidateContents: "adversarial contract v2\n", @@ -163,7 +179,7 @@ it.each([ expectedLocal: true, failPublishedPull: true, rejectCopyParsing: false, - title: "builds the DCode base locally when the published base cannot be verified", + title: "builds locally when the published base cannot be verified", }, { candidateContents: "candidate documentation\n", @@ -171,9 +187,16 @@ it.each([ expectedLocal: true, failPublishedPull: false, rejectCopyParsing: true, - title: "builds the DCode base locally when direct COPY parsing rejects the Dockerfile", + title: "builds locally when direct COPY parsing rejects the Dockerfile", }, -])("$title", (testCase) => { +] as const; + +it.each( + // One synthetic COPY contract exercises every agent routed through this resolver. + publishedBaseCases.flatMap((testCase) => + ["openclaw", "hermes", "langchain-deepagents-code"].map((agent) => ({ ...testCase, agent })), + ), +)("$agent: $title", (testCase) => { const { candidateContents, candidatePath, expectedLocal, failPublishedPull, rejectCopyParsing } = testCase; const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-pr-base-")); @@ -293,7 +316,7 @@ exit 90 ); const environment = { ...process.env, - AGENT: "langchain-deepagents-code", + AGENT: testCase.agent, ALIAS_RAW: aliasRaw, BASE_ALIAS: `${baseRepository}:latest`, BASE_DOCKERFILE: "agents/langchain-deepagents-code/Dockerfile.base", diff --git a/test/platform/images/protected-managed-image-build-script.test.ts b/test/platform/images/protected-managed-image-build-script.test.ts index f24590baff9..380ca9779b0 100644 --- a/test/platform/images/protected-managed-image-build-script.test.ts +++ b/test/platform/images/protected-managed-image-build-script.test.ts @@ -128,7 +128,7 @@ esac writeExecutable( "sha256sum", `#!/usr/bin/env bash -if [[ "$1" == */dcode-candidate-base.raw ]]; then +if [[ "$1" == */*-candidate-base.raw ]]; then PATH="$NEMOCLAW_TEST_REAL_PATH" command sha256sum "$@" else printf '%s %s\\n' '${DIGEST}' "$1" @@ -232,7 +232,7 @@ function completeAuditEvidence(auditDirectory: string): void { // Docker is the stubbed process boundary; the production receipt CLI still // hashes and validates every byte exported by this synthetic builder fixture. -function candidateBaseFixture(platform = "linux/amd64") { +function candidateBaseFixture(platform = "linux/amd64", agent = "langchain-deepagents-code") { const layout = path.join(testRoot, "base-fixture"); mkdirSync(path.join(layout, "blobs/sha256"), { recursive: true }); function blob(value: unknown, mediaType: string) { @@ -249,7 +249,7 @@ function candidateBaseFixture(platform = "linux/amd64") { Labels: { "org.opencontainers.image.revision": REVISION, "org.opencontainers.image.source": "https://github.com/NVIDIA/NemoClaw", - "io.nvidia.nemoclaw.agent": "langchain-deepagents-code", + "io.nvidia.nemoclaw.agent": agent, "io.nvidia.nemoclaw.managed-image.cohort": "protected-1-1", }, }, @@ -281,7 +281,7 @@ esac `, ); return { - reference: `localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@${manifest.digest}`, + reference: `localhost:5000/nemoclaw-managed-protected-base/${agent}@${manifest.digest}`, environment: { NEMOCLAW_TEST_BASE_LAYOUT: layout, NEMOCLAW_TEST_BASE_MANIFEST: path.join(layout, "blobs/sha256", manifest.digest.slice(7)), @@ -437,27 +437,33 @@ afterEach(() => { rmSync(testRoot, { force: true, recursive: true }); }); -describe("protected candidate DCode base handoff", () => { +describe.each([ + ["openclaw", "openclaw", OPENCLAW_BASE], + ["hermes", "hermes", HERMES_BASE], + ["langchain-deepagents-code", "dcode", DCODE_BASE], +])("protected candidate %s base handoff", (agent, cacheName, publishedBase) => { it.each(["linux/amd64", "linux/arm64"])( "exports a verified base and consumes it offline on %s", (platform) => { stubBuildInvocation(); - const fixture = candidateBaseFixture(platform); + const fixture = candidateBaseFixture(platform, agent); const cache = path.join(testRoot, "candidate-cache"); const source = path.join(testRoot, "candidate-source"); completeSourceBoundary(source); const produced = runBuild( source, - ["--dcode-base", "candidate", "--cache-to", cache], + [`--${cacheName}-base`, "candidate", "--cache-to", cache], platform, fixture.environment, ); expect(produced.status, produced.stderr).toBe(0); const realCache = realpathSync(cache); expect(readFileSync(path.join(cache, "prepared-inputs"), "utf8")).toBe( - `${REVISION} ${platform} ${OPENCLAW_BASE} ${HERMES_BASE} ${fixture.reference}\n`, + `${REVISION} ${platform} ${[OPENCLAW_BASE, HERMES_BASE, DCODE_BASE].map((base) => (base === publishedBase ? fixture.reference : base)).join(" ")}\n`, + ); + const receipt = JSON.parse( + readFileSync(path.join(cache, `${cacheName}-base-receipt.json`), "utf8"), ); - const receipt = JSON.parse(readFileSync(path.join(cache, "dcode-base-receipt.json"), "utf8")); expect(receipt).toMatchObject({ reference: fixture.reference, platform, @@ -467,9 +473,11 @@ describe("protected candidate DCode base handoff", () => { }); const baseBuild = recordedBuildInvocations()[0]; expect(baseBuild).toContain(`/Dockerfile.base --platform ${platform}`); - expect(baseBuild).toContain(`--output type=oci,dest=${realCache}/dcode-base,tar=false`); expect(baseBuild).toContain( - `--output type=image,name=localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code:${REVISION},push=true,oci-mediatypes=true`, + `--output type=oci,dest=${realCache}/${cacheName}-base,tar=false`, + ); + expect(baseBuild).toContain( + `--output type=image,name=localhost:5000/nemoclaw-managed-protected-base/${agent}:${REVISION},push=true,oci-mediatypes=true`, ); expect(baseBuild).not.toContain("ghcr.io"); @@ -479,7 +487,14 @@ describe("protected candidate DCode base handoff", () => { writeFileSync(dockerLog, ""); const consumed = runBuild( source, - ["--dcode-base", fixture.reference, "--cache-from", cache, "--audit-evidence-from", audit], + [ + `--${cacheName}-base`, + fixture.reference, + "--cache-from", + cache, + "--audit-evidence-from", + audit, + ], platform, fixture.environment, ); @@ -487,8 +502,8 @@ describe("protected candidate DCode base handoff", () => { const builds = recordedBuildInvocations(); expect(builds).toHaveLength(3); expect(builds.every((line) => line.includes("--network none"))).toBe(true); - expect(recordedBuildInvocation("langchain-deepagents-code")).toContain( - `--build-context ${fixture.reference}=oci-layout://${realCache}/dcode-base@${receipt.digest}`, + expect(recordedBuildInvocation(agent)).toContain( + `--build-context ${fixture.reference}=oci-layout://${realCache}/${cacheName}-base@${receipt.digest}`, ); const calls = readFileSync(dockerLog, "utf8"); expect(calls).not.toContain("/Dockerfile.base"); @@ -499,7 +514,14 @@ describe("protected candidate DCode base handoff", () => { writeFileSync(dockerLog, ""); const rejected = runBuild( source, - ["--dcode-base", fixture.reference, "--cache-from", cache, "--audit-evidence-from", audit], + [ + `--${cacheName}-base`, + fixture.reference, + "--cache-from", + cache, + "--audit-evidence-from", + audit, + ], platform, { ...fixture.environment, NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA: "d".repeat(40) }, ); @@ -514,8 +536,8 @@ describe("protected candidate DCode base handoff", () => { [{ NEMOCLAW_TEST_GIT_DIRTY: "1" }, "tracked modifications"], ] as const)("rejects an unbound candidate checkout %j", (change, diagnostic) => { stubBuildInvocation(); - const fixture = candidateBaseFixture(); - const result = runBuild(REPO_ROOT, ["--dcode-base", "candidate"], "linux/amd64", { + const fixture = candidateBaseFixture("linux/amd64", agent); + const result = runBuild(REPO_ROOT, [`--${cacheName}-base`, "candidate"], "linux/amd64", { ...fixture.environment, ...change, }); @@ -526,10 +548,10 @@ describe("protected candidate DCode base handoff", () => { it("rejects different registry and OCI manifests before building managed images", () => { stubBuildInvocation(); - const fixture = candidateBaseFixture(); + const fixture = candidateBaseFixture("linux/amd64", agent); const mismatch = path.join(testRoot, "different-manifest"); writeFileSync(mismatch, "{}"); - const result = runBuild(REPO_ROOT, ["--dcode-base", "candidate"], "linux/amd64", { + const result = runBuild(REPO_ROOT, [`--${cacheName}-base`, "candidate"], "linux/amd64", { ...fixture.environment, NEMOCLAW_TEST_BASE_MANIFEST: mismatch, }); diff --git a/test/platform/images/protected-managed-image-contract.test.ts b/test/platform/images/protected-managed-image-contract.test.ts index b6e05236574..2d0748f783b 100644 --- a/test/platform/images/protected-managed-image-contract.test.ts +++ b/test/platform/images/protected-managed-image-contract.test.ts @@ -2,12 +2,14 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import path from "node:path"; import { describe, expect, it } from "vitest"; import YAML from "yaml"; +import { inspectProtectedDcodeBase } from "../../../scripts/checks/protected-dcode-base-receipt.mts"; import { CANDIDATE_MANAGED_IMAGE_AGENTS, @@ -71,7 +73,68 @@ function workflowStep(jobId: string, stepName: string): string { return run ?? ""; } -function runBaseResolution(jobId: string, stepName: string) { +type BaseResolutionOptions = { + candidate?: string; + localBases?: boolean; + env?: Record; + publishedAgent?: (typeof PROTECTED_MANAGED_IMAGE_AGENTS)[number]; + mutate?: (cache: string) => void; +}; + +function candidateBase(cache: string, agent: (typeof PROTECTED_MANAGED_IMAGE_AGENTS)[number]) { + const name = agent === "langchain-deepagents-code" ? "dcode" : agent; + const layout = path.join(cache, `${name}-base`); + mkdirSync(path.join(layout, "blobs/sha256"), { recursive: true }); + function blob(value: unknown, mediaType: string) { + const bytes = Buffer.from(JSON.stringify(value)); + const digest = `sha256:${createHash("sha256").update(bytes).digest("hex")}`; + writeFileSync(path.join(layout, "blobs/sha256", digest.slice(7)), bytes); + return { digest, size: bytes.length, mediaType }; + } + const config = blob( + { + os: "linux", + architecture: "amd64", + config: { + Labels: { + "org.opencontainers.image.revision": HEAD_SHA, + "org.opencontainers.image.source": "https://github.com/NVIDIA/NemoClaw", + "io.nvidia.nemoclaw.managed-image.cohort": COHORT, + "io.nvidia.nemoclaw.agent": agent, + }, + }, + }, + "application/vnd.oci.image.config.v1+json", + ); + const manifest = blob( + { + schemaVersion: 2, + mediaType: "application/vnd.oci.image.manifest.v1+json", + config, + layers: [], + }, + "application/vnd.oci.image.manifest.v1+json", + ); + writeFileSync( + path.join(layout, "index.json"), + JSON.stringify({ schemaVersion: 2, manifests: [manifest] }), + ); + writeFileSync(path.join(layout, "oci-layout"), JSON.stringify({ imageLayoutVersion: "1.0.0" })); + const receipt = inspectProtectedDcodeBase( + layout, + { + sourceRevision: HEAD_SHA, + workflowSha: WORKFLOW_SHA, + cohort: COHORT, + platform: "linux/amd64", + }, + agent, + ); + writeFileSync(path.join(cache, `${name}-base-receipt.json`), JSON.stringify(receipt)); + return receipt.reference; +} + +function runBaseResolution(jobId: string, stepName: string, options: BaseResolutionOptions = {}) { const fixture = mkdtempSync(path.join(tmpdir(), "nemoclaw-protected-bases-")); const fakeBin = path.join(fixture, "bin"); const outputPath = path.join(fixture, "github-output"); @@ -80,15 +143,16 @@ function runBaseResolution(jobId: string, stepName: string) { mkdirSync(fakeBin); mkdirSync(runnerTemp); writeFileSync(outputPath, ""); + const dockerLog = path.join(fixture, "docker-log"); + writeFileSync(dockerLog, ""); + const references = PROTECTED_MANAGED_IMAGE_AGENTS.map((agent, index) => { + return options.localBases && options.publishedAgent !== agent + ? candidateBase(fixture, agent) + : `ghcr.io/nvidia/nemoclaw/${BASE_REPOSITORIES[agent]}@${Object.values(PLATFORM_DIGESTS)[index]}`; + }); writeFileSync( path.join(fixture, "prepared-inputs"), - [ - HEAD_SHA, - "linux/amd64", - `ghcr.io/nvidia/nemoclaw/sandbox-base@${PLATFORM_DIGESTS.openclaw}`, - `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${PLATFORM_DIGESTS.hermes}`, - DCODE_BASE_REF, - ].join(" ") + "\n", + [HEAD_SHA, "linux/amd64", ...references].join(" ") + "\n", ); writeFileSync( path.join(fixture, "agents", "hermes", "Dockerfile"), @@ -99,6 +163,7 @@ function runBaseResolution(jobId: string, stepName: string) { dockerPath, `#!/bin/sh set -eu +printf '%s\\n' "$*" >> "$DOCKER_LOG" ref="$4" case "$ref" in ghcr.io/nvidia/nemoclaw/hermes-sandbox-base:latest) exit 97 ;; @@ -129,12 +194,15 @@ printf '%s %s\n' "$digest" "$1" chmodSync(sha256sumPath, 0o700); try { + options.mutate?.(fixture); const result = spawnSync("bash", ["-c", workflowStep(jobId, stepName)], { - cwd: fixture, + cwd: ROOT, encoding: "utf8", env: { ...process.env, + CANDIDATE_BASES: options.candidate ?? "false", CHECKOUT_SHA: HEAD_SHA, + DOCKER_LOG: dockerLog, DCODE_BASE_CONTRACT: JSON.stringify({ platformReferences: { "linux/amd64": DCODE_BASE_REF }, }), @@ -142,14 +210,20 @@ printf '%s %s\n' "$digest" "$1" GITHUB_OUTPUT: outputPath, HERMES_BASE_REF: `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${PLATFORM_DIGESTS.hermes}`, NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE: fixture, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA: WORKFLOW_SHA, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT: COHORT, + NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM: "linux/amd64", PATH: `${fakeBin}:${process.env.PATH ?? ""}`, PLATFORM: "linux/amd64", RUNNER_TEMP: runnerTemp, + ...options.env, }, }); return { result, output: readFileSync(outputPath, "utf8"), + dockerCalls: readFileSync(dockerLog, "utf8"), + references, }; } finally { rmSync(fixture, { recursive: true, force: true }); @@ -206,9 +280,99 @@ describe("protected managed-image build contract", () => { ).toEqual({ dcode: `ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base@${PLATFORM_DIGESTS.dcode}`, openclaw: `ghcr.io/nvidia/nemoclaw/sandbox-base@${PLATFORM_DIGESTS.openclaw}`, + hermes: `ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${PLATFORM_DIGESTS.hermes}`, }); }); + it("selects all candidate bases on CPU without resolving published images", () => { + const { result, output, dockerCalls } = runBaseResolution( + "managed-image-multiarch-startup", + "Resolve digest-pinned platform base images", + { candidate: "true" }, + ); + expect(result.status, result.stderr).toBe(0); + expect(output).toBe("openclaw=candidate\nhermes=candidate\ndcode=candidate\n"); + expect(dockerCalls).toBe(""); + }); + + it.each(["managed-image-multiarch-startup", "managed-image-protected-runtime"])( + "rejects an invalid candidate selection in %s", + (jobId) => { + const stepName = + jobId === "managed-image-multiarch-startup" + ? "Resolve digest-pinned platform base images" + : "Resolve digest-pinned amd64 runtime base images"; + const { result, output, dockerCalls } = runBaseResolution(jobId, stepName, { + candidate: "yes", + }); + expect(result.status).not.toBe(0); + expect(output).toBe(""); + expect(dockerCalls).toBe(""); + }, + ); + + it("verifies all candidate OCI bases on GPU without registry access", () => { + const { result, output, dockerCalls, references } = runBaseResolution( + "managed-image-protected-runtime", + "Resolve digest-pinned amd64 runtime base images", + { candidate: "true", localBases: true }, + ); + expect(result.status, result.stderr).toBe(0); + expect(output).toBe( + `openclaw=${references[0]}\nhermes=${references[1]}\ndcode=${references[2]}\n`, + ); + expect(dockerCalls).toBe(""); + }); + + it.each(PROTECTED_MANAGED_IMAGE_AGENTS)( + "rejects a published %s base in a PR cache", + (publishedAgent) => { + const { result, dockerCalls } = runBaseResolution( + "managed-image-protected-runtime", + "Resolve digest-pinned amd64 runtime base images", + { candidate: "true", localBases: true, publishedAgent }, + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("does not match the selected source"); + expect(dockerCalls).toBe(""); + }, + ); + + it.each>([ + { CHECKOUT_SHA: "d".repeat(40) }, + { NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA: "d".repeat(40) }, + { NEMOCLAW_PROTECTED_MANAGED_IMAGE_COHORT: "protected-42-2" }, + { NEMOCLAW_PROTECTED_MANAGED_IMAGE_PLATFORM: "linux/arm64" }, + ])("rejects a GPU handoff for another dispatch: %j", (env) => { + const { result, output, dockerCalls } = runBaseResolution( + "managed-image-protected-runtime", + "Resolve digest-pinned amd64 runtime base images", + { candidate: "true", localBases: true, env }, + ); + expect(result.status).not.toBe(0); + expect(output).toBe(""); + expect(dockerCalls).toBe(""); + }); + + it.each(["openclaw", "hermes", "dcode"])("rejects a substituted %s receipt on GPU", (name) => { + const { result, dockerCalls } = runBaseResolution( + "managed-image-protected-runtime", + "Resolve digest-pinned amd64 runtime base images", + { + candidate: "true", + localBases: true, + mutate(cache) { + const receipt = path.join(cache, `${name}-base-receipt.json`); + const original = JSON.parse(readFileSync(receipt, "utf8")); + writeFileSync(receipt, JSON.stringify({ ...original, workflowSha: "d".repeat(40) })); + }, + }, + ); + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("receipt does not match"); + expect(dockerCalls).toBe(""); + }); + it("accepts only the all-agent multiarch activation contract (#7744)", () => { const activation = { agents: PROTECTED_MANAGED_IMAGE_AGENTS, @@ -223,13 +387,16 @@ describe("protected managed-image build contract", () => { ).toThrow("activation contract is invalid"); }); - it("accepts an immutable isolated candidate base for DCode", () => { - const localBase = `localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:${"d".repeat(64)}`; - const valid = contracts("linux/amd64").map((entry) => - entry.agent === "langchain-deepagents-code" ? { ...entry, baseReference: localBase } : entry, - ); - expect(parseProtectedManagedImageContracts(valid, "linux/amd64")).toEqual(valid); - }); + it.each(PROTECTED_MANAGED_IMAGE_AGENTS)( + "accepts an immutable isolated candidate base for %s", + (agent) => { + const localBase = `localhost:5000/nemoclaw-managed-protected-base/${agent}@sha256:${"d".repeat(64)}`; + const valid = contracts("linux/amd64").map((entry) => + entry.agent === agent ? { ...entry, baseReference: localBase } : entry, + ); + expect(parseProtectedManagedImageContracts(valid, "linux/amd64")).toEqual(valid); + }, + ); it.each(["openclaw", "hermes"])("rejects a candidate DCode base for %s", (agent) => { const localBase = `localhost:5000/nemoclaw-managed-protected-base/langchain-deepagents-code@sha256:${"d".repeat(64)}`; diff --git a/test/repository/checks-runner.test.ts b/test/repository/checks-runner.test.ts index 3a9c98af264..f638b1bac5c 100644 --- a/test/repository/checks-runner.test.ts +++ b/test/repository/checks-runner.test.ts @@ -101,6 +101,7 @@ describe("checks runner", () => { [ fileURLToPath(import.meta.resolve("tsx/cli")), "scripts/checks/pi-qualification-receipt-refresh.mts", + "--local-publication", ], expect.objectContaining({ stdio: "inherit" }), ); diff --git a/test/repository/pi-qualification-receipt-refresh.test.ts b/test/repository/pi-qualification-receipt-refresh.test.ts index b15125eb154..9020371e1cd 100644 --- a/test/repository/pi-qualification-receipt-refresh.test.ts +++ b/test/repository/pi-qualification-receipt-refresh.test.ts @@ -77,6 +77,7 @@ describe("Pi qualification receipt refresh", () => { function run( changedPaths: readonly string[], options: { + allowPendingPublication?: boolean; accepted?: ReadonlySet; headRevision?: string | null; mergeInProgress?: boolean; @@ -84,8 +85,9 @@ describe("Pi qualification receipt refresh", () => { sourceParity?: boolean; stagedPaths?: readonly string[]; } = {}, - ): void { - checkPiQualificationReceiptRefresh({ + ): "pending-publication" | undefined { + return checkPiQualificationReceiptRefresh({ + allowPendingPublication: options.allowPendingPublication, acceptedDigests: options.accepted ?? acceptedDigests, baseBranch: "main", git: (args) => @@ -140,6 +142,61 @@ describe("Pi qualification receipt refresh", () => { expect(() => run(["protected/base/config.json", RECEIPTS[0].path])).toThrow(RECEIPTS[1].path); }); + it("allows a local source commit before image publication without treating it as qualification", () => { + expect( + run(["protected/app/config.json"], { + allowPendingPublication: true, + sourceParity: false, + }), + ).toBe("pending-publication"); + }); + + it("keeps CI strict even when the local-publication option is supplied", () => { + vi.stubEnv("GITHUB_ACTIONS", "true"); + expect(() => + run(["protected/app/config.json"], { + allowPendingPublication: true, + }), + ).toThrow("Pi image inputs changed without refreshing both qualification receipts"); + }); + + it.each([RECEIPTS[0].path, "src/lib/agent/candidate-authority.ts"])( + "does not defer a local refresh that changes %s", + (changedPath) => { + expect(() => + run(["protected/app/config.json"], { + allowPendingPublication: true, + stagedPaths: [changedPath], + }), + ).toThrow("Pi image inputs changed without refreshing both qualification receipts"); + }, + ); + + it("does not accept broken receipt authority during source-only publication", () => { + expect(() => + run(["protected/app/config.json"], { + allowPendingPublication: true, + accepted: new Set(), + }), + ).toThrow("is not present in the Pi candidate receipt authority"); + }); + + it("requires source parity once both receipts are added to the same local PR", () => { + expect(() => + run(["protected/app/config.json"], { + allowPendingPublication: true, + stagedPaths: RECEIPTS.map(({ path: receiptPath }) => receiptPath), + sourceParity: false, + }), + ).toThrow(`Pi image inputs changed after receipt source revision ${SOURCE_REVISION}`); + expect( + run(["protected/app/config.json"], { + allowPendingPublication: true, + stagedPaths: RECEIPTS.map(({ path: receiptPath }) => receiptPath), + }), + ).toBeUndefined(); + }); + it.each(RECEIPTS)("rejects deletion of the $platform qualification receipt", (candidate) => { fs.unlinkSync(path.join(rootDir, candidate.path)); diff --git a/tools/e2e/managed-image-multiarch-workflow-boundary.mts b/tools/e2e/managed-image-multiarch-workflow-boundary.mts index fcfbceba55c..e416b46b8aa 100644 --- a/tools/e2e/managed-image-multiarch-workflow-boundary.mts +++ b/tools/e2e/managed-image-multiarch-workflow-boundary.mts @@ -62,7 +62,7 @@ const REVIEWED_EXECUTION_STEP_NAMES = [ "Run every exact managed-image contract directly", ] as const; const REVIEWED_EXECUTION_SURFACE_SHA256 = - "8a44ba348ebc4a839b91006a3b385506706b8c072b0d634251fd9a6670ff8458"; + "10a73edea771fdd015b543a8dec7ed55be5d6c28dc1a43bed8dccd07be497ba7"; const SHARED_POLICY_BOUNDARY_RUN = [ "set -euo pipefail", "[[ ! -e nemoclaw/dist && ! -L nemoclaw/dist ]] || {", @@ -376,6 +376,9 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): if (hermesBase?.uses !== REVIEWED_HERMES_PLATFORM_ACTION) { errors.push(`${JOB_ID} must use the shared reviewed Hermes platform resolver`); } + if (hermesBase?.if !== "${{ inputs.checkout_sha == '' }}") { + errors.push(`${JOB_ID} must resolve a published Hermes base only without a PR candidate`); + } requireValues(errors, `${JOB_ID} Hermes platform resolver`, record(hermesBase?.with), { "dockerfile-path": "agents/hermes/Dockerfile", platform: "${{ matrix.platform }}", @@ -398,10 +401,15 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): const bases = requireStep(errors, steps, "Resolve digest-pinned platform base images"); requireValues(errors, `${JOB_ID} exact base resolution`, record(bases?.env), { + CANDIDATE_BASES: "${{ inputs.checkout_sha != '' }}", DCODE_BASE_CONTRACT: "${{ needs.base-image-publication.outputs.dcode_base_contract }}", + HERMES_BASE_REF: + "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.hermes-base.outputs.digest }}", PLATFORM: "${{ matrix.platform }}", }); requireFragments(errors, bases, [ + 'case "$CANDIDATE_BASES" in', + "printf 'openclaw=candidate\\nhermes=candidate\\ndcode=candidate\\n'", 'arch="${PLATFORM#linux/}"', 'docker buildx imagetools inspect "$alias" --raw', '.platform.os == "linux" and .platform.architecture == $arch', @@ -437,6 +445,7 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): requireValues(errors, `${JOB_ID} candidate base selection`, record(build?.env), { BASE_DCODE: "${{ steps.candidate-contract.outputs.dcode_source == 'candidate' && 'candidate' || steps.bases.outputs.dcode }}", + BASE_OPENCLAW: "${{ steps.bases.outputs.openclaw }}", }); requireFragments(errors, build, [ "scripts/checks/build-protected-managed-images.sh", @@ -450,8 +459,7 @@ export function validateManagedImageMultiarchWorkflow(workflow: WorkflowRecord): '--dcode-base "$BASE_DCODE"', ]); requireValues(errors, `${JOB_ID} protected build bases`, record(build?.env), { - BASE_HERMES: - "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.hermes-base.outputs.digest }}", + BASE_HERMES: "${{ steps.bases.outputs.hermes }}", }); const direct = requireStep(errors, steps, "Run every exact managed-image contract directly"); diff --git a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts index 857b68ba756..76916c7fdf5 100644 --- a/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts +++ b/tools/e2e/managed-image-protected-runtime-workflow-boundary.mts @@ -14,7 +14,7 @@ type WorkflowStep = WorkflowRecord & { const JOB_ID = "managed-image-protected-runtime"; const SELECTOR = - "${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }}"; + "${{ always() && github.repository == 'NVIDIA/NemoClaw' && (github.event_name == 'workflow_dispatch' || (github.event_name == 'push' && github.ref == 'refs/heads/main')) && needs['base-image-publication'].result == 'success' && needs['generate-matrix'].result == 'success' && needs['managed-image-multiarch-startup'].result == 'success' && needs['package-openshell-sdk'].result == 'success' && contains(fromJSON(needs.generate-matrix.outputs.selected_jobs), 'managed-image-protected-runtime') }}"; const ACTIVATION_PATH = "ci/protected-managed-image-runtime-activation-v1.json"; const LIVE_TEST_PATH = "test/e2e/live/managed-image-protected-runtime.test.ts"; const REGISTRY_IMAGE = @@ -100,10 +100,11 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR "base-image-publication", "generate-matrix", "managed-image-multiarch-startup", + "package-openshell-sdk", ]) ) { errors.push( - `${JOB_ID} must depend on base-image-publication, generate-matrix, and managed-image-multiarch-startup`, + `${JOB_ID} must depend on base-image-publication, generate-matrix, managed-image-multiarch-startup, and package-openshell-sdk`, ); } if (job.if !== SELECTOR) errors.push(`${JOB_ID} must use the trusted execution plan`); @@ -120,6 +121,7 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR const jobEnv = record(job.env); requireValues(errors, `${JOB_ID} env`, jobEnv, { + CHECKOUT_SHA: "${{ inputs.checkout_sha || github.sha }}", E2E_ARTIFACT_DIR: "${{ github.workspace }}/e2e-artifacts/live/managed-image-protected-runtime", E2E_JOB: "1", E2E_TARGET_ID: JOB_ID, @@ -252,8 +254,75 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR ) { errors.push(`${JOB_ID} must pin the trusted E2E preparation action`); } - if (prepare?.with !== undefined) { - errors.push(`${JOB_ID} must use the default CLI build`); + if (!isDeepStrictEqual(prepare?.with, { "build-cli": "false" })) { + errors.push(`${JOB_ID} must defer the CLI build until OpenShell projection`); + } + + const projection = requireStep( + errors, + workflowSteps, + "Bind reviewed candidate OpenShell runtime", + ); + if (projection?.id !== "openshell-projection") + errors.push(`${JOB_ID} must identify the OpenShell projection`); + const restore = requireStep(errors, workflowSteps, "Restore trusted OpenShell sources"); + if (restore?.if !== "${{ always() && steps.openshell-projection.outcome == 'success' }}") { + errors.push(`${JOB_ID} must restore sources after a successful OpenShell projection`); + } + for (const [step, operation, output] of [ + [projection, "prepare", "openshell-projection.json"], + [restore, "restore", "openshell-projection-restored.json"], + ] as const) { + const expected = `set -euo pipefail\nnode tools/e2e/protected-openshell-workspace.mts ${operation} > "$E2E_ARTIFACT_DIR/${output}"\n`; + if ( + step?.run !== expected || + step?.shell !== "bash" || + step?.env !== undefined || + step?.["continue-on-error"] !== undefined + ) { + errors.push(`${JOB_ID} must use the reviewed OpenShell ${operation} operation`); + } + } + if (projection?.if !== undefined) errors.push(`${JOB_ID} must not skip OpenShell projection`); + const sdkDownload = requireStep(errors, workflowSteps, "Download reviewed OpenShell SDK archive"); + if ( + !isDeepStrictEqual(sdkDownload, { + name: "Download reviewed OpenShell SDK archive", + uses: "actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c", + with: { + name: "${{ needs.package-openshell-sdk.outputs.artifact_name }}", + path: "${{ runner.temp }}/openshell-sdk", + }, + }) + ) + errors.push(`${JOB_ID} must download this run's reviewed SDK archives`); + const sdkInstall = requireStep( + errors, + workflowSteps, + "Install reviewed OpenShell SDK from trusted controller", + ); + if ( + !isDeepStrictEqual(sdkInstall, { + name: "Install reviewed OpenShell SDK from trusted controller", + uses: "./.github/actions/install-reviewed-openshell-sdk", + }) + ) + errors.push( + `${JOB_ID} must install the projected SDK with the trusted controller's archive verifier`, + ); + const cliBuild = requireStep( + errors, + workflowSteps, + "Build trusted CLI with reviewed OpenShell runtime", + ); + if ( + !isDeepStrictEqual(cliBuild, { + name: "Build trusted CLI with reviewed OpenShell runtime", + shell: "bash", + run: "npm run build:cli", + }) + ) { + errors.push(`${JOB_ID} must build the trusted CLI after OpenShell projection`); } const activation = requireStep( @@ -290,6 +359,9 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR if (hermesBase?.uses !== REVIEWED_HERMES_PLATFORM_ACTION) { errors.push(`${JOB_ID} must use the shared reviewed Hermes platform resolver`); } + if (hermesBase?.if !== "${{ inputs.checkout_sha == '' }}") { + errors.push(`${JOB_ID} must resolve a published Hermes base only without a PR candidate`); + } requireValues(errors, `${JOB_ID} Hermes platform resolver`, record(hermesBase?.with), { "dockerfile-path": ".candidate-runtime/agents/hermes/Dockerfile", platform: "linux/amd64", @@ -301,34 +373,36 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR "Resolve digest-pinned amd64 runtime base images", ); requireValues(errors, `${JOB_ID} runtime base env`, record(bases?.env), { + CANDIDATE_BASES: "${{ inputs.checkout_sha != '' }}", CHECKOUT_SHA: "${{ inputs.checkout_sha || github.sha }}", DCODE_BASE_REF: "${{ needs.base-image-publication.outputs.dcode_base_ref }}", HERMES_BASE_REF: "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }}", }); requireFragments(errors, bases, [ + '[[ "$CANDIDATE_BASES" == true || "$CANDIDATE_BASES" == false ]] || exit 1', 'prepared_inputs="$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/prepared-inputs"', '[[ -f "$prepared_inputs" && ! -L "$prepared_inputs" ]]', 'read -r cached_revision cached_platform cached_openclaw cached_hermes cached_dcode extra < "$prepared_inputs"', '[[ -z "$extra" &&', '"$cached_revision" == "$CHECKOUT_SHA"', '"$cached_platform" == "linux/amd64"', - '"$cached_hermes" == "$HERMES_BASE_REF"', - '"$cached_dcode" == "$DCODE_BASE_REF"', "node scripts/checks/protected-dcode-base-receipt.mts verify", - '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base"', - '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/dcode-base-receipt.json"', - '"$verified_dcode" == "$cached_dcode"', - 'printf \'dcode=%s\\n\' "$verified_dcode" >> "$GITHUB_OUTPUT"', + '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/${name}-base"', + '"$NEMOCLAW_PROTECTED_MANAGED_IMAGE_BUILD_CACHE/${name}-base-receipt.json" "$agent"', + '"$verified" == "$reference"', + 'local candidate_prefix="localhost:5000/nemoclaw-managed-protected-base/${agent}@"', + '[[ "$reference" == "${candidate_prefix}${digest}" ]]', + '[[ "$digest" =~ ^sha256:[a-f0-9]{64}$ ]]', + '[[ "$CANDIDATE_BASES" == false && "$reference" == "${repository}@${digest}" &&', + '( -z "$expected_published" || "$reference" == "$expected_published" ) ]]', '"$(cat "$prepared_inputs")" == "$cached_revision $cached_platform $cached_openclaw $cached_hermes $cached_dcode"', - '[[ "$cached_openclaw" =~ ^ghcr[.]io/nvidia/nemoclaw/sandbox-base@sha256:[a-f0-9]{64}$ ]]', - 'openclaw_digest="${cached_openclaw##*@}"', - 'docker buildx imagetools inspect "$cached_openclaw" --raw > "$work_dir/openclaw-exact.raw"', - '"sha256:$(sha256sum "$work_dir/openclaw-exact.raw" | awk \'{print $1}\')" == "$openclaw_digest"', - 'printf \'openclaw=%s\\n\' "$cached_openclaw" >> "$GITHUB_OUTPUT"', - 'docker buildx imagetools inspect "$DCODE_BASE_REF" --raw', - 'dcode_digest="${DCODE_BASE_REF##*@}"', - 'printf \'dcode=%s\\n\' "$DCODE_BASE_REF" >> "$GITHUB_OUTPUT"', + 'docker buildx imagetools inspect "$reference" --raw > "$work_dir/${name}-exact.raw"', + '"sha256:$(sha256sum "$work_dir/${name}-exact.raw" | awk \'{print $1}\')" == "$digest"', + 'printf \'%s=%s\\n\' "$name" "$reference" >> "$GITHUB_OUTPUT"', + "resolve_cached_base openclaw openclaw \"$cached_openclaw\" ghcr.io/nvidia/nemoclaw/sandbox-base ''", + 'resolve_cached_base hermes hermes "$cached_hermes" ghcr.io/nvidia/nemoclaw/hermes-sandbox-base "$HERMES_BASE_REF"', + 'resolve_cached_base dcode langchain-deepagents-code "$cached_dcode" ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base "$DCODE_BASE_REF"', ]); if (text(bases?.run).includes("ghcr.io/nvidia/nemoclaw/sandbox-base:latest")) { errors.push(`${JOB_ID} must reuse the OpenClaw base from the prepared build cache`); @@ -373,8 +447,9 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR errors.push(`${JOB_ID} build controller must execute trusted workflow code`); } requireValues(errors, `${JOB_ID} protected runtime build bases`, record(build?.env), { - BASE_HERMES: - "ghcr.io/nvidia/nemoclaw/hermes-sandbox-base@${{ steps.runtime-hermes-base.outputs.digest }}", + BASE_OPENCLAW: "${{ steps.runtime-bases.outputs.openclaw }}", + BASE_HERMES: "${{ steps.runtime-bases.outputs.hermes }}", + BASE_DCODE: "${{ steps.runtime-bases.outputs.dcode }}", RUNTIME_USER: "${{ steps.runtime-contract.outputs.runtime_user }}", }); @@ -401,11 +476,19 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR errors.push(`${JOB_ID} must expose NVIDIA_API_KEY only to trusted qualification code`); } requireFragments(errors, qualification, [ + 'node tools/e2e/protected-openshell-workspace.mts verify > "$E2E_ARTIFACT_DIR/openshell-projection-verified.json"', '[[ "$(git rev-parse --verify HEAD)" == "$NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA" ]]', - 'export OPENSHELL_BIN="$(command -v openshell)"', + 'OPENSHELL_BIN="$(command -v openshell)"\nexport OPENSHELL_BIN', "tools/e2e/live-vitest-invocation.mts run", `--test-path ${LIVE_TEST_PATH}`, ]); + const qualificationRun = text(qualification?.run); + const verifyPosition = qualificationRun.indexOf( + "node tools/e2e/protected-openshell-workspace.mts verify", + ); + if (verifyPosition < 0 || verifyPosition > qualificationRun.indexOf("OPENSHELL_BIN=")) { + errors.push(`${JOB_ID} must verify projected sources before runtime qualification`); + } if (text(qualification?.run).includes(".candidate-runtime")) { errors.push(`${JOB_ID} trusted qualification must not execute candidate checkout paths`); } @@ -438,6 +521,10 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR "Download exact protected runtime build cache", "Prepare E2E workspace", "Validate protected runtime activation contract", + "Bind reviewed candidate OpenShell runtime", + "Download reviewed OpenShell SDK archive", + "Install reviewed OpenShell SDK from trusted controller", + "Build trusted CLI with reviewed OpenShell runtime", "Resolve reviewed Hermes runtime base image", "Resolve digest-pinned amd64 runtime base images", "Start isolated protected runtime registry", @@ -445,6 +532,7 @@ export function validateManagedImageProtectedRuntimeWorkflow(workflow: WorkflowR "Install OpenShell CLI", "Run all-agent GPU, local inference, rollback, and cleanup qualification", "Remove isolated protected runtime registry", + "Restore trusted OpenShell sources", "Upload protected managed-image runtime artifacts", "Clean up Docker auth", ]); diff --git a/tools/e2e/pre-candidate-workflow-contract.mts b/tools/e2e/pre-candidate-workflow-contract.mts index 574d2614292..a98c358570a 100644 --- a/tools/e2e/pre-candidate-workflow-contract.mts +++ b/tools/e2e/pre-candidate-workflow-contract.mts @@ -83,6 +83,8 @@ export const PRE_CANDIDATE_STEP_ENV: Readonly> = { + "Resolve reviewed candidate OpenShell version": + "${{ contains(fromJSON(steps.matrix.outputs.selected_jobs), 'openshell-gateway-auth-contract') || contains(fromJSON(steps.matrix.outputs.selected_jobs), 'external-gateway-health') }}", "Authenticate manual PR dispatch": "${{ inputs.pr_number != '' || inputs.checkout_sha != '' || inputs.checkout_repository != '' || inputs.base_sha != '' || inputs.workflow_sha != '' }}", "Record trusted E2E dispatch receipt": "${{ github.event_name == 'workflow_dispatch' }}", diff --git a/tools/e2e/protected-openshell-projection.mts b/tools/e2e/protected-openshell-projection.mts new file mode 100644 index 00000000000..0b6531983c2 --- /dev/null +++ b/tools/e2e/protected-openshell-projection.mts @@ -0,0 +1,168 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + validateInstallerSources, + validateOpenShellFeatureGateSource, +} from "../../scripts/checks/extract-installer-pins.mts"; +import { isDeepStrictEqual } from "node:util"; +import { parseAuditConfig } from "../../scripts/audit-reviewed-npm-graph.mts"; +import { reviewedNpmDependencyLocations } from "../../scripts/lib/reviewed-npm-archive.mts"; + +export type ProtectedOpenShellCandidateSources = Parameters[0] & { + featureGateSource: string; +}; + +function replaceOne(source: string, pattern: RegExp, replacement: string, label: string): string { + if ([...source.matchAll(pattern)].length !== 1) { + throw new Error(`Protected OpenShell projection requires one ${label}`); + } + return source.replace(pattern, replacement); +} + +/** + * Keep the test controller's code except for independently template-verified + * OpenShell modules. Blueprint and fallback changes contain release data only. + * The caller must bind both source sets to its authenticated dispatch commits. + */ +export function projectProtectedOpenShellSources( + candidate: ProtectedOpenShellCandidateSources, + trusted: { blueprintSource: string; versionSource: string }, +): { releaseVersion: string; files: Record } { + const { releaseVersion } = validateInstallerSources(candidate); + validateOpenShellFeatureGateSource(candidate.featureGateSource, releaseVersion); + const qualified = [ + ...candidate.supervisorRuntimeSource.matchAll( + /^const QUALIFIED_STABLE_OPENSHELL_VERSION = "([0-9]+\.[0-9]+\.[0-9]+)";$/gm, + ), + ]; + if (qualified.length !== 1 || qualified[0]![1] !== releaseVersion) { + throw new Error("Protected OpenShell supervisor must select the candidate release"); + } + let blueprintSource = trusted.blueprintSource; + for (const bound of ["min", "max"] as const) { + blueprintSource = replaceOne( + blueprintSource, + new RegExp(`^${bound}_openshell_version: "[0-9]+\\.[0-9]+\\.[0-9]+"$`, "gm"), + `${bound}_openshell_version: "${releaseVersion}"`, + `${bound} blueprint version`, + ); + } + const versionSource = replaceOne( + trusted.versionSource, + /^export const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "[0-9]+\.[0-9]+\.[0-9]+";$/gm, + `export const SUPPORTED_OPENSHELL_FALLBACK_VERSION = "${releaseVersion}";`, + "fallback version", + ); + return { + releaseVersion, + files: { + "scripts/install-openshell.sh": candidate.installerSource, + "src/lib/onboard/docker-driver-gateway-runtime.ts": candidate.supervisorRuntimeSource, + "src/lib/onboard/openshell-feature-gate.ts": candidate.featureGateSource, + "src/lib/onboard/openshell-version.ts": versionSource, + "nemoclaw-blueprint/blueprint.yaml": blueprintSource, + }, + }; +} + +const SDK_NAME = "@nvidia/openshell-sdk"; +const SDK_LOCATION = `node_modules/${SDK_NAME}`; +type JsonObject = Record; + +function object(value: unknown): JsonObject { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("Protected SDK manifests must contain JSON objects"); + } + return value as JsonObject; +} + +function sdkManifest(source: string) { + const manifest = object(JSON.parse(source)); + const dependencies = object(manifest.optionalDependencies); + const version = dependencies[SDK_NAME]; + if (typeof version !== "string" || !/^\d+\.\d+\.\d+$/.test(version)) { + throw new Error("Protected SDK must use an exact optional dependency version"); + } + for (const field of ["dependencies", "devDependencies", "peerDependencies"]) { + if (manifest[field] !== undefined && Object.hasOwn(object(manifest[field]), SDK_NAME)) { + throw new Error("Protected SDK has ambiguous dependency declarations"); + } + } + return { manifest, dependencies, version }; +} + +function sdkLock(source: string, version: string) { + const lock = object(JSON.parse(source)); + if (lock.lockfileVersion !== 3) throw new Error("Protected SDK requires lockfileVersion 3"); + const packages = object(lock.packages) as Record; + const root = object(packages[""]); + const sdk = object(packages[SDK_LOCATION]); + if (object(root.optionalDependencies)[SDK_NAME] !== version || sdk.version !== version) { + throw new Error("Protected SDK manifest and lock identities disagree"); + } + return { lock, packages, root, sdk }; +} + +/** Select a reviewed SDK archive without adopting other candidate host dependencies. */ +export function projectProtectedOpenShellSdk( + candidate: { packageSource: string; lockSource: string }, + trusted: { packageSource: string; lockSource: string; auditSource: string }, + releaseVersion: string, +): { sdkVersion: string; sdkIntegrity: string; files: Record } { + const selected = sdkManifest(candidate.packageSource); + if (selected.version !== releaseVersion) + throw new Error("Protected SDK must match the selected OpenShell runtime"); + const baseline = sdkManifest(trusted.packageSource); + const current = sdkLock(trusted.lockSource, baseline.version); + const next = sdkLock(candidate.lockSource, selected.version); + const config = parseAuditConfig(trusted.auditSource); + const identities = [config.sourceRegistryPackage, config.sourceRegistryPackageReplacement].filter( + Boolean, + ); + for (const { sdk } of [current, next]) { + const identity = identities.find( + (entry) => entry?.packageSpec === `${SDK_NAME}@${String(sdk.version)}`, + ); + if (!identity || sdk.resolved !== identity.tarballUrl || sdk.integrity !== identity.integrity) { + throw new Error("Protected SDK archive is not trusted by the workflow commit"); + } + } + const metadata = ({ + version: _version, + resolved: _resolved, + integrity: _integrity, + ...rest + }: JsonObject) => rest; + if (!isDeepStrictEqual(metadata(current.sdk), metadata(next.sdk))) { + throw new Error("Protected SDK dependency metadata requires trusted controller review"); + } + const currentGraph = reviewedNpmDependencyLocations(current.packages, SDK_NAME); + const nextGraph = reviewedNpmDependencyLocations(next.packages, SDK_NAME); + if ( + !isDeepStrictEqual([...currentGraph].sort(), [...nextGraph].sort()) || + [...currentGraph].some( + (location) => + location !== SDK_LOCATION && + !isDeepStrictEqual(current.packages[location], next.packages[location]), + ) + ) { + throw new Error("Protected SDK transitive dependencies require trusted controller review"); + } + baseline.dependencies[SDK_NAME] = selected.version; + object(current.root.optionalDependencies)[SDK_NAME] = selected.version; + current.packages[SDK_LOCATION] = { + ...current.sdk, + version: selected.version, + resolved: next.sdk.resolved, + integrity: next.sdk.integrity, + }; + return { + sdkVersion: selected.version, + sdkIntegrity: String(next.sdk.integrity), + files: { + "package.json": `${JSON.stringify(baseline.manifest, null, 2)}\n`, + "package-lock.json": `${JSON.stringify(current.lock, null, 2)}\n`, + }, + }; +} diff --git a/tools/e2e/protected-openshell-workspace.mts b/tools/e2e/protected-openshell-workspace.mts new file mode 100644 index 00000000000..d79547898c3 --- /dev/null +++ b/tools/e2e/protected-openshell-workspace.mts @@ -0,0 +1,223 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { execFileSync } from "node:child_process"; +import { createHash, randomUUID } from "node:crypto"; +import { lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { dirname, join, relative, resolve } from "node:path"; +import { pathToFileURL } from "node:url"; +import { + projectProtectedOpenShellSources, + projectProtectedOpenShellSdk, +} from "./protected-openshell-projection.mts"; + +const SOURCE_PATHS = { + blueprintSource: "nemoclaw-blueprint/blueprint.yaml", + installerSource: "scripts/install-openshell.sh", + brevInstallerSource: "scripts/brev-launchable-ci-cpu.sh", + supervisorRuntimeSource: "src/lib/onboard/docker-driver-gateway-runtime.ts", + featureGateSource: "src/lib/onboard/openshell-feature-gate.ts", + packageSource: "package.json", + lockSource: "package-lock.json", +} as const; +const VERSION_PATH = "src/lib/onboard/openshell-version.ts"; +const MAX_SOURCE_BYTES = 1024 * 1024; + +export interface ProtectedOpenShellWorkspace { + trustedRoot: string; + candidateRoot: string; + workflowSha: string; + candidateSha: string; +} + +function git(root: string, args: string[]): string { + return execFileSync( + "git", + ["--no-replace-objects", "-c", "core.fsmonitor=false", "-C", root, ...args], + { + encoding: "utf8", + maxBuffer: MAX_SOURCE_BYTES + 1024, + env: { ...process.env, GIT_NO_LAZY_FETCH: "1", GIT_TERMINAL_PROMPT: "0" }, + stdio: ["ignore", "pipe", "pipe"], + }, + ); +} + +function assertCommit(root: string, sha: string): void { + if (!/^[a-f0-9]{40}$/.test(sha) || git(root, ["rev-parse", "--verify", "HEAD"]).trim() !== sha) { + throw new Error("Protected OpenShell workspace does not match its dispatch commit"); + } +} + +function committedSource(root: string, sha: string, path: string): string { + const entry = git(root, ["ls-tree", "-z", sha, "--", path]); + const match = /^(100644|100755) blob ([a-f0-9]{40})\t([^\0]+)\0$/.exec(entry); + if (!match || match[3] !== path) throw new Error(`Expected a regular committed source: ${path}`); + const source = git(root, ["cat-file", "blob", match[2]!]); + if ( + Buffer.byteLength(source) > MAX_SOURCE_BYTES || + source.includes("\0") || + source.includes("\ufffd") + ) { + throw new Error(`Invalid protected OpenShell source bytes: ${path}`); + } + return source; +} + +function safeFile(root: string, path: string): { path: string; mode: number; source: string } { + const absoluteRoot = resolve(root); + const absolutePath = join(absoluteRoot, path); + // The caller supplies a fixed repository path, never a candidate-selected destination. + for (let parent = dirname(absolutePath); ; parent = dirname(parent)) { + const stat = lstatSync(parent); + if (!stat.isDirectory() || stat.isSymbolicLink()) + throw new Error(`Unsafe source directory: ${path}`); + if (parent === absoluteRoot) break; + if (!relative(absoluteRoot, parent) || relative(absoluteRoot, parent).startsWith("..")) { + throw new Error("Source escaped the trusted workspace"); + } + } + const stat = lstatSync(absolutePath); + if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > MAX_SOURCE_BYTES) { + throw new Error(`Unsafe protected OpenShell file: ${path}`); + } + return { + path: absolutePath, + mode: stat.mode & 0o777, + source: readFileSync(absolutePath, "utf8"), + }; +} + +function replaceSource(path: string, source: string, mode: number): void { + const temporary = `${path}.openshell-projection-${randomUUID()}`; + try { + writeFileSync(temporary, source, { flag: "wx", mode }); + renameSync(temporary, path); + } finally { + rmSync(temporary, { force: true }); + } +} + +/** Apply only reviewed modules and release literals to an isolated trusted workflow checkout. */ +export function manageProtectedOpenShellWorkspace( + operation: "prepare" | "verify" | "restore", + input: ProtectedOpenShellWorkspace, +) { + if (!["prepare", "verify", "restore"].includes(operation)) + throw new Error("Invalid projection operation"); + assertCommit(input.trustedRoot, input.workflowSha); + assertCommit(input.candidateRoot, input.candidateSha); + const candidate = Object.fromEntries( + Object.entries(SOURCE_PATHS).map(([key, path]) => [ + key, + committedSource(input.candidateRoot, input.candidateSha, path), + ]), + ) as Record; + const projected = projectProtectedOpenShellSources(candidate, { + blueprintSource: committedSource( + input.trustedRoot, + input.workflowSha, + SOURCE_PATHS.blueprintSource, + ), + versionSource: committedSource(input.trustedRoot, input.workflowSha, VERSION_PATH), + }); + const sdk = projectProtectedOpenShellSdk( + candidate, + { + packageSource: committedSource(input.trustedRoot, input.workflowSha, "package.json"), + lockSource: committedSource(input.trustedRoot, input.workflowSha, "package-lock.json"), + auditSource: committedSource( + input.trustedRoot, + input.workflowSha, + "ci/reviewed-npm-audit.json", + ), + }, + projected.releaseVersion, + ); + Object.assign(projected.files, sdk.files); + const files = Object.entries(projected.files).map(([path, source]) => ({ + ...safeFile(input.trustedRoot, path), + relativePath: path, + projected: source, + original: committedSource(input.trustedRoot, input.workflowSha, path), + })); + const allowed = new Set(files.map((file) => file.relativePath)); + const changed = git(input.trustedRoot, [ + "diff", + "--no-ext-diff", + "--no-textconv", + "--name-only", + "-z", + input.workflowSha, + "--", + ]) + .split("\0") + .filter(Boolean); + if (changed.some((path) => !allowed.has(path))) + throw new Error("Unrelated changes in the trusted controller"); + for (const file of files) { + const valid = + operation === "prepare" + ? file.source === file.original + : operation === "verify" + ? file.source === file.projected + : file.source === file.original || file.source === file.projected; + if (!valid) throw new Error(`Unexpected ${operation} source: ${file.relativePath}`); + } + if (operation !== "verify") { + const written: typeof files = []; + try { + for (const file of files) { + const next = operation === "prepare" ? file.projected : file.original; + if (file.source === next) continue; + replaceSource(file.path, next, file.mode); + written.push(file); + } + } catch (error) { + for (const file of written.reverse()) replaceSource(file.path, file.source, file.mode); + throw error; + } + } + return { + schemaVersion: 1, + operation, + workflowSha: input.workflowSha, + candidateSha: input.candidateSha, + releaseVersion: projected.releaseVersion, + sdkVersion: sdk.sdkVersion, + sdkIntegrity: sdk.sdkIntegrity, + files: files.map((file) => ({ + path: file.relativePath, + sha256: createHash("sha256") + .update(operation === "restore" ? file.original : file.projected) + .digest("hex"), + })), + }; +} + +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + const operation = process.argv[2]; + if (process.argv.length !== 3 || !["prepare", "verify", "restore"].includes(operation ?? "")) { + throw new Error("Usage: protected-openshell-workspace.mts prepare|verify|restore"); + } + for (const name of [ + "GITHUB_WORKSPACE", + "NEMOCLAW_E2E_TESTED_ROOT", + "NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA", + "CHECKOUT_SHA", + ]) { + if (!process.env[name]) throw new Error(`Missing ${name}`); + } + console.log( + JSON.stringify( + manageProtectedOpenShellWorkspace(operation as "prepare" | "verify" | "restore", { + trustedRoot: process.env.GITHUB_WORKSPACE!, + candidateRoot: process.env.NEMOCLAW_E2E_TESTED_ROOT!, + workflowSha: process.env.NEMOCLAW_PROTECTED_MANAGED_IMAGE_WORKFLOW_SHA!, + candidateSha: process.env.CHECKOUT_SHA!, + }), + null, + 2, + ), + ); +} diff --git a/tools/e2e/workflow-boundary-policy.mts b/tools/e2e/workflow-boundary-policy.mts index 31c526d0d39..b8ab1d45540 100644 --- a/tools/e2e/workflow-boundary-policy.mts +++ b/tools/e2e/workflow-boundary-policy.mts @@ -63,6 +63,6 @@ export const E2E_ACTION_PROVENANCE = { export const E2E_JOB_POLICY = { cliArtifactProducer: "generate-matrix", - prepareNoBuild: ["managed-image-multiarch-startup"], - prepareTrustedBuild: ["managed-image-protected-runtime"], + prepareNoBuild: ["managed-image-multiarch-startup", "managed-image-protected-runtime"], + prepareTrustedBuild: [], } as const; diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index 6e1900c1e91..5c02662adce 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -1264,7 +1264,10 @@ function isReviewedLocalAction(jobName: string, step: WorkflowStep): boolean { step.uses === REVIEWED_HERMES_PLATFORM_ACTION) || (jobName === "managed-image-protected-runtime" && step.name === "Reuse or refresh reviewed audit evidence before the offline build" && - step.uses === "./.github/actions/ci-reviewed-npm-audit") + step.uses === "./.github/actions/ci-reviewed-npm-audit") || + (jobName === "managed-image-protected-runtime" && + step.name === "Install reviewed OpenShell SDK from trusted controller" && + step.uses === "./.github/actions/install-reviewed-openshell-sdk") ); } @@ -2651,7 +2654,7 @@ const PRE_CANDIDATE_RUN_SHA256: Readonly> = { "ee0b2e6c6aa4552b228bd1cc3ba4e1f9cd72701c30b81f7d5fbf9bc011fb51c7", "Authorize Launchable E2E maintainer dispatch": "bbf442a006b47016eda56133eb400a48c6931c55364c1220b84327b5ffd6f171", - "Generate E2E target matrix": "7b250c79a05973c6bc2f904195c174ddd6ffee80c62a2ff3362d7362e075b0ef", + "Generate E2E target matrix": "ee26da3b8da6b988773803d2a05f7763d560b565f145599c39d22b2e528e8c6b", }; function requirePreCandidateEnvironment( From 2cde387597ba1d7d36489ac6d5b30beddddc3d97 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 8 Oct 2026 16:12:04 -0700 Subject: [PATCH 4/4] fix(e2e): refresh candidate receipts and close qualification findings --- ci/pi-agent-qualification-v1-linux-amd64.json | 8 +- ci/pi-agent-qualification-v1-linux-arm64.json | 8 +- src/lib/agent/candidate-authority.ts | 4 +- test/e2e/fixtures/admin-approval-connect.sh | 16 ++- test/e2e/fixtures/admin-approval-connect.ts | 19 ++-- ...naged-image-activation-diagnostics.test.ts | 104 +++++++++++++++++- .../protected-openshell-workspace.test.ts | 42 ++++++- ...managed-image-publication-workflow.test.ts | 19 +++- tools/e2e/protected-openshell-workspace.mts | 39 +++++-- 9 files changed, 222 insertions(+), 37 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index dc71bc77af4..19e422c45fe 100644 --- a/ci/pi-agent-qualification-v1-linux-amd64.json +++ b/ci/pi-agent-qualification-v1-linux-amd64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/amd64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:3bf1dcebb4fdefe4ad588b15f287e2546a570c4464897835c37599de2ec1b66b", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:3bf1dcebb4fdefe4ad588b15f287e2546a570c4464897835c37599de2ec1b66b", + "digest": "sha256:aefc5eecd7bf6e3eea0e4df97cbca155a271e2e18d569cdc4acbf8008fdc943a", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:aefc5eecd7bf6e3eea0e4df97cbca155a271e2e18d569cdc4acbf8008fdc943a", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "9abef33ddf73105c8f3f952ced9ce4eb53252126", + "revision": "77e3ce673f6f14c277273de4033775a67fea2a9f", "release": "v0.1.0", - "cohort": "ghrun-37676667241-1" + "cohort": "ghrun-37850713619-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/ci/pi-agent-qualification-v1-linux-arm64.json b/ci/pi-agent-qualification-v1-linux-arm64.json index 8154ec8d0fd..57e0a5155d4 100644 --- a/ci/pi-agent-qualification-v1-linux-arm64.json +++ b/ci/pi-agent-qualification-v1-linux-arm64.json @@ -3,13 +3,13 @@ "agent": "pi", "platform": "linux/arm64", "image": "ghcr.io/nvidia/nemoclaw/pi-sandbox", - "digest": "sha256:f3d7ed13c07c7c3840414752aa72e77178fa957137951c25ad4afa84206b11ac", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:f3d7ed13c07c7c3840414752aa72e77178fa957137951c25ad4afa84206b11ac", + "digest": "sha256:b91f5d84e342d7b5d39460a4e4f9cfc2c4baeb32fd2d61f35f5dd3b468b243bd", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:b91f5d84e342d7b5d39460a4e4f9cfc2c4baeb32fd2d61f35f5dd3b468b243bd", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "9abef33ddf73105c8f3f952ced9ce4eb53252126", + "revision": "77e3ce673f6f14c277273de4033775a67fea2a9f", "release": "v0.1.0", - "cohort": "ghrun-37676667241-1" + "cohort": "ghrun-37850713619-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index 0ab2fb71aed..8da514f03f0 100644 --- a/src/lib/agent/candidate-authority.ts +++ b/src/lib/agent/candidate-authority.ts @@ -13,8 +13,8 @@ export const CANDIDATE_QUALIFICATION_RECEIPT_DIGESTS: Readonly< Record > = Object.freeze({ pi: Object.freeze([ - "ba5f7fc419ada9de012546d8bbaa7f251eb1a9075d1df82af573aaf57809cbe9", - "8bf8a0d80ec7e70687f0f696d8ff1fded3214e5858b6881a5380b4cf25faa455", + "bdd2220911935355cca02e4c45f32685a83528e585e069f05898f451d94bb7f7", + "618a0c6d4593a0b0d0a27eb44050fe6fd40c401332280fc738ba4675c32c20f9", ]), }); diff --git a/test/e2e/fixtures/admin-approval-connect.sh b/test/e2e/fixtures/admin-approval-connect.sh index 4fa6a3644a6..f590e3b37ea 100644 --- a/test/e2e/fixtures/admin-approval-connect.sh +++ b/test/e2e/fixtures/admin-approval-connect.sh @@ -27,13 +27,24 @@ cron_name=__NEMOCLAW_ADMIN_CRON_NAME__ expected_request_id=__NEMOCLAW_ADMIN_EXPECTED_REQUEST_ID__ verify_cron=__NEMOCLAW_ADMIN_VERIFY_CRON__ emit_admin_diagnostic() { - python3 - "$1" <<'PY_ADMIN_DIAGNOSTIC' + python3 - "$1" "${2:-command}" <<'PY_ADMIN_DIAGNOSTIC' import re, sys from pathlib import Path try: with Path(sys.argv[1]).open('rb') as stream: raw=stream.read(65536).decode('utf-8', errors='replace') except FileNotFoundError: raw='' +# Emit only fixed categories, never device records, identities, tokens or traceback text. +selection_checks=( + ('selection-state-read', r'canonical pairing-state|canonical device state|canonical primary device identity|FileNotFoundError|PermissionError|sqlite3\.'), + ('selection-local-identity', r'local CLI identity'), + ('selection-pending-count', r'expected exactly one pending request, found [0-9]+'), + ('selection-request-binding', r'pending admin request (?:has an invalid requestId|does not match the triggered request)'), + ('selection-client-role', r'does not belong to the expected CLI operator|roles? (?:must be|contains|is invalid)'), + ('selection-paired-binding', r'cron requestId (?:must match exactly one paired device|public key does not match its paired device)'), + ('selection-scopes', r'scopes?|paired tokens'), + ('selection-response', r'device state must be an object|records must be an array of objects|JSONDecodeError'), +) checks=( ('timeout', r'timed?\s*out|timeout'), ('pairing-required', r'device pairing|required.*pairing|pairing required'), @@ -42,6 +53,7 @@ checks=( ('gateway-unavailable', r'gateway|connection|econn|socket|network'), ('invalid-response', r'invalid|parse|json'), ) +if sys.argv[2] == 'selection': checks=selection_checks + checks label=next((name for name, pattern in checks if re.search(pattern, raw, re.IGNORECASE)), 'command-failed' if raw.strip() else 'no-output') print(f'ADMIN_DIAGNOSTIC={label}', file=sys.stderr) PY_ADMIN_DIAGNOSTIC @@ -89,7 +101,7 @@ if ! python3 - "$devices_json" "$request_id_file" "$expected_request_id" 2>"$sel __NEMOCLAW_ADMIN_REQUEST_SELECTOR_PY__ PY_ADMIN_REQUEST echo "ADMIN_REQUEST_SELECTION_FAILED" >&2 - emit_admin_diagnostic "$selector_err" + emit_admin_diagnostic "$selector_err" selection exit 26 fi request_id="$(cat "$request_id_file")" diff --git a/test/e2e/fixtures/admin-approval-connect.ts b/test/e2e/fixtures/admin-approval-connect.ts index c93aea42a4d..ea23491c496 100644 --- a/test/e2e/fixtures/admin-approval-connect.ts +++ b/test/e2e/fixtures/admin-approval-connect.ts @@ -12,6 +12,17 @@ const ADMIN_APPROVAL_CONNECT_SH = readFileSync( "utf8", ).trimEnd(); +export function adminApprovalBody( + cronName: string, + expectedRequestId?: string, + verifyCronConsumer = true, +): string { + return ADMIN_APPROVAL_CONNECT_SH.replace("__NEMOCLAW_ADMIN_CRON_NAME__", shellQuote(cronName)) + .replace("__NEMOCLAW_ADMIN_EXPECTED_REQUEST_ID__", shellQuote(expectedRequestId ?? "")) + .replace("__NEMOCLAW_ADMIN_VERIFY_CRON__", verifyCronConsumer ? "1" : "0") + .replace("__NEMOCLAW_ADMIN_REQUEST_SELECTOR_PY__", ADMIN_REQUEST_SELECTOR_PY); +} + export function adminApprovalConnectScript( cliPath: string, sandboxName: string, @@ -25,13 +36,7 @@ export function adminApprovalConnectScript( ): string { const cli = shellQuote(cliPath); const sandbox = shellQuote(sandboxName); - const body = ADMIN_APPROVAL_CONNECT_SH.replace( - "__NEMOCLAW_ADMIN_CRON_NAME__", - shellQuote(cronName), - ) - .replace("__NEMOCLAW_ADMIN_EXPECTED_REQUEST_ID__", shellQuote(expectedRequestId ?? "")) - .replace("__NEMOCLAW_ADMIN_VERIFY_CRON__", verifyCronConsumer ? "1" : "0") - .replace("__NEMOCLAW_ADMIN_REQUEST_SELECTOR_PY__", ADMIN_REQUEST_SELECTOR_PY); + const body = adminApprovalBody(cronName, expectedRequestId, verifyCronConsumer); const digest = createHash("sha256").update(body).digest("hex"); // Read once and verify those bytes before executing them in the prepared // shell. A replaced temporary file must never become an approval command. diff --git a/test/e2e/support/managed-image-activation-diagnostics.test.ts b/test/e2e/support/managed-image-activation-diagnostics.test.ts index 7f67a0baff4..723ec7f52e9 100644 --- a/test/e2e/support/managed-image-activation-diagnostics.test.ts +++ b/test/e2e/support/managed-image-activation-diagnostics.test.ts @@ -12,7 +12,10 @@ import { approveOpenClawAdminScope, exactRequestAdminApprovalConnectScript, } from "../live/openclaw-admin-scope.ts"; -import { adminApprovalConnectScript } from "../fixtures/admin-approval-connect.ts"; +import { + adminApprovalBody, + adminApprovalConnectScript, +} from "../fixtures/admin-approval-connect.ts"; import { createHostProcessWorkspace } from "../../helpers/host-process-harness.ts"; import { ADMIN_APPROVAL_TEST_CLI_SH, @@ -186,6 +189,102 @@ printf '%s\n' "$@" >"$MANAGED_ACTIVATION_FIXTURE/openclaw-args" } describe("managed image activation failure diagnostics", () => { + it.each<{ + diagnostic: string; + expectedRequestId?: string; + prepare: ( + env: NodeJS.ProcessEnv, + devices: { pending: Array> }, + secret: string, + ) => void; + }>([ + { + diagnostic: "selection-state-read", + prepare: (env, _devices, secret) => { + writeFileSync( + env.NEMOCLAW_OPENCLAW_PAIRING_STATE_HELPER!, + `def read_openclaw_pairing_state(*args, **kwargs):\n raise PermissionError("${secret}")\n`, + ); + }, + }, + { + diagnostic: "selection-request-binding", + expectedRequestId: "a96ada31-9cf9-4d99-97cc-978dcbb9fc39", + prepare: () => {}, + }, + { + diagnostic: "selection-pending-count", + prepare: (_env, devices) => { + devices.pending.push({ ...devices.pending[0] }); + }, + }, + { + diagnostic: "selection-scopes", + prepare: (_env, devices, secret) => { + devices.pending[0]!.scopes = [secret]; + }, + }, + ])( + "reports $diagnostic without approving or disclosing selector inputs", + ({ diagnostic, expectedRequestId, prepare }) => { + const fixture = createHostProcessWorkspace("nemoclaw-admin-body-diagnostic-"); + const requestId = "4edc8df0-20d0-4308-b0e8-850843ae0cf4"; + const secret = "selector-private-diagnostic-value"; + const approveLog = fixture.path("approve.log"); + // BSD mktemp without a template selects the system temp directory instead of TMPDIR. + fixture.writeExecutable( + "mktemp", + '#!/bin/sh\nexec /usr/bin/mktemp "$TMPDIR/tmp.XXXXXXXXXX"\n', + ); + fixture.writeExecutable( + "openclaw", + `#!/bin/sh +if [ "$1:$2" = "devices:list" ]; then cat "$FAKE_DEVICES_STATE"; exit 0; fi +printf '%s\\n' "$*" >"$MANAGED_ADMIN_APPROVE_LOG" +exit 91 +`, + ); + try { + const env = prepareManagedAdminState(fixture.root, requestId); + const devices = JSON.parse(readFileSync(env.FAKE_DEVICES_STATE!, "utf8")) as { + pending: Array>; + }; + prepare(env, devices, secret); + writeFileSync(env.FAKE_DEVICES_STATE!, JSON.stringify(devices)); + const result = fixture.run( + "/bin/bash", + [ + "--noprofile", + "--norc", + "-c", + adminApprovalBody("diagnostic", expectedRequestId ?? requestId), + ], + { + env: fixture.environment({ + ...env, + TMPDIR: fixture.root, + MANAGED_ADMIN_APPROVE_LOG: approveLog, + OPENCLAW_GATEWAY_PORT: "18789", + OPENCLAW_GATEWAY_TOKEN: secret, + }), + timeout: 10_000, + }, + ); + expect(result.status, result.stderr).toBe(26); + expect(result.stderr.trim()).toBe( + `ADMIN_REQUEST_SELECTION_FAILED\nADMIN_DIAGNOSTIC=${diagnostic}`, + ); + expect(result.stdout).toBe(""); + expect(result.output).not.toContain(secret); + expect(result.output).not.toContain(requestId); + expect(existsSync(approveLog)).toBe(false); + expect(fs.readdirSync(fixture.root).filter((name) => name.startsWith("tmp."))).toEqual([]); + } finally { + fixture.remove(); + } + }, + ); + it("adopts public OpenClaw and Hermes digests through Docker and Podman", () => { const reference = `ghcr.io/nvidia/nemoclaw/openclaw-sandbox@sha256:${"a".repeat(64)}`; expect(externalImageActivationAgents("docker")).toEqual(["openclaw", "hermes"]); @@ -492,6 +591,7 @@ ${exactRequestAdminApprovalConnectScript(cliPath, "fixture-sandbox", "managed-cr expect(result.status).not.toBe(0); expect(result.stderr).toContain("ADMIN_REQUEST_SELECTION_FAILED"); + expect(result.stderr).toContain("ADMIN_DIAGNOSTIC=selection-pending-count"); expect(existsSync(approveLog)).toBe(false); expect(result.stderr).not.toContain(requestId); } finally { @@ -581,7 +681,7 @@ ${adminApprovalConnectScript("nemoclaw", "fixture-sandbox", "managed-cron", outp expect(result.status).not.toBe(0); expect(result.stderr).toContain("ADMIN_REQUEST_SELECTION_FAILED"); - expect(result.stderr).toContain("ADMIN_DIAGNOSTIC=command-failed"); + expect(result.stderr).toContain("ADMIN_DIAGNOSTIC=selection-request-binding"); expect(existsSync(approveLog)).toBe(false); expect(result.stderr).not.toContain(outputRequestId); expect(result.stderr).not.toContain(canonicalRequestId); diff --git a/test/e2e/support/protected-openshell-workspace.test.ts b/test/e2e/support/protected-openshell-workspace.test.ts index 727b5a0006e..47fe8de860f 100644 --- a/test/e2e/support/protected-openshell-workspace.test.ts +++ b/test/e2e/support/protected-openshell-workspace.test.ts @@ -12,7 +12,12 @@ import { manageProtectedOpenShellWorkspace } from "../../../tools/e2e/protected- vi.mock("node:fs", async (importOriginal) => { const original = await importOriginal(); - return { ...original, renameSync: vi.fn(original.renameSync) }; + return { + ...original, + renameSync: vi.fn(original.renameSync), + openSync: vi.fn(original.openSync), + closeSync: vi.fn(original.closeSync), + }; }); const sources = [ @@ -29,6 +34,7 @@ const sources = [ const roots: string[] = []; afterEach(() => { vi.restoreAllMocks(); + vi.mocked(fs.openSync).mockReset(); for (const root of roots.splice(0)) fs.rmSync(root, { recursive: true, force: true }); }); @@ -209,6 +215,40 @@ describe("protected OpenShell workspace", () => { expect(git(input.trustedRoot, "diff", "--no-ext-diff")).toBe(before); }); + it("rejects a destination replaced with a symlink immediately before opening", async () => { + const input = fixture(); + const path = join(input.trustedRoot, "scripts/install-openshell.sh"); + const retained = `${path}.retained`; + const before = fs.statSync(path); + const { openSync: original } = await vi.importActual("node:fs"); + vi.mocked(fs.openSync).mockImplementationOnce((file, flags, mode) => { + expect(file).toBe(path); + fs.renameSync(path, retained); + fs.symlinkSync(retained, path); + return original(file, flags, mode); + }); + expect(() => manageProtectedOpenShellWorkspace("prepare", input)).toThrow(/Unsafe/); + expect(fs.readlinkSync(path)).toBe(retained); + expect(fs.statSync(retained)).toMatchObject({ + ino: before.ino, + size: before.size, + mtimeMs: before.mtimeMs, + }); + }); + + it("rejects a hard-linked destination and closes its opened descriptor", () => { + const input = fixture(); + const path = join(input.trustedRoot, "scripts/install-openshell.sh"); + fs.linkSync(path, `${path}.retained`); + vi.mocked(fs.openSync).mockClear(); + vi.mocked(fs.closeSync).mockClear(); + expect(() => manageProtectedOpenShellWorkspace("prepare", input)).toThrow(/Unsafe/); + const opened = vi.mocked(fs.openSync).mock.results.map((result) => result.value); + expect(opened.length).toBeGreaterThan(0); + expect(vi.mocked(fs.closeSync).mock.calls.map(([fd]) => fd)).toEqual(opened); + expect(fs.statSync(path).nlink).toBe(2); + }); + it("rolls back an incomplete prepare when a later replacement fails", async () => { const input = fixture(); const { renameSync: original } = await vi.importActual("node:fs"); diff --git a/test/inference/managed/managed-image-publication-workflow.test.ts b/test/inference/managed/managed-image-publication-workflow.test.ts index b2579485167..579297f5cdf 100644 --- a/test/inference/managed/managed-image-publication-workflow.test.ts +++ b/test/inference/managed/managed-image-publication-workflow.test.ts @@ -883,13 +883,18 @@ describe("complete managed-image publication workflow", () => { path.join(fakeBin, "docker"), `#!/bin/bash set -euo pipefail -if [ "\${1:-} \${2:-} \${3:-}" != "buildx imagetools inspect" ]; then - exit 90 -fi -if [[ "\${4:-}" == *":latest" ]]; then - cat "$ALIAS_RAW" +if [ "\${1:-} \${2:-} \${3:-}" = "buildx imagetools inspect" ]; then + if [[ "\${4:-}" == *":latest" ]]; then + cat "$ALIAS_RAW" + else + cat "$EXACT_RAW" + fi +elif [ "$*" = "pull --platform linux/amd64 $EXACT_REFERENCE" ]; then + exit 0 +elif [ "$*" = "image inspect $EXACT_REFERENCE" ]; then + printf '[{"Config":{"Labels":{"org.opencontainers.image.revision":"%s"}}}]' "$CANDIDATE_SHA" else - cat "$EXACT_RAW" + exit 90 fi `, { mode: 0o755 }, @@ -910,10 +915,12 @@ fi }).stdout.trim(), DISPLAY_NAME: "OpenClaw", EXACT_RAW: exactRaw, + EXACT_REFERENCE: `ghcr.io/nvidia/nemoclaw/sandbox-base@${digest}`, GITHUB_OUTPUT: output, GITHUB_STEP_SUMMARY: summary, LOCAL_BASE_REFERENCE: "nemoclaw-managed-pr/openclaw-base:test", PATH: `${fakeBin}:${process.env.PATH ?? ""}`, + PLATFORM: "linux/amd64", RUNNER_TEMP: temporaryRoot, }, }); diff --git a/tools/e2e/protected-openshell-workspace.mts b/tools/e2e/protected-openshell-workspace.mts index d79547898c3..39d222b4982 100644 --- a/tools/e2e/protected-openshell-workspace.mts +++ b/tools/e2e/protected-openshell-workspace.mts @@ -3,7 +3,17 @@ import { execFileSync } from "node:child_process"; import { createHash, randomUUID } from "node:crypto"; -import { lstatSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs"; +import { + closeSync, + constants, + fstatSync, + lstatSync, + openSync, + readFileSync, + renameSync, + rmSync, + writeFileSync, +} from "node:fs"; import { dirname, join, relative, resolve } from "node:path"; import { pathToFileURL } from "node:url"; import { @@ -77,15 +87,26 @@ function safeFile(root: string, path: string): { path: string; mode: number; sou throw new Error("Source escaped the trusted workspace"); } } - const stat = lstatSync(absolutePath); - if (!stat.isFile() || stat.isSymbolicLink() || stat.nlink !== 1 || stat.size > MAX_SOURCE_BYTES) { - throw new Error(`Unsafe protected OpenShell file: ${path}`); + let fd: number; + try { + fd = openSync(absolutePath, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); + } catch (cause) { + throw new Error(`Unsafe protected OpenShell file: ${path}`, { cause }); + } + try { + // Validate and read the same opened file; never reopen a checked pathname. + const stat = fstatSync(fd); + if (!stat.isFile() || stat.nlink !== 1 || stat.size > MAX_SOURCE_BYTES) { + throw new Error(`Unsafe protected OpenShell file: ${path}`); + } + return { + path: absolutePath, + mode: stat.mode & 0o777, + source: readFileSync(fd, "utf8"), + }; + } finally { + closeSync(fd); } - return { - path: absolutePath, - mode: stat.mode & 0o777, - source: readFileSync(absolutePath, "utf8"), - }; } function replaceSource(path: string, source: string, mode: number): void {