From 3d8bb1483baabdc26be10e1c55346363d677912e Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 09:48:56 -0700 Subject: [PATCH 01/11] fix(ci): admit guarded OpenShell 0.1.2 installer Signed-off-by: Prekshi Vyas --- scripts/checks/extract-installer-pins.mts | 2 + .../openshell-v012-installer-legacy-guard.sh | 125 ++++++++++++++++++ test/install/installer-hash-check.test.ts | 12 +- test/install/installer-hash-v012-suite.ts | 101 ++++++++++++++ 4 files changed, 231 insertions(+), 9 deletions(-) create mode 100644 test/fixtures/openshell-v012-installer-legacy-guard.sh create mode 100644 test/install/installer-hash-v012-suite.ts diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index fc475603837..27133c14d34 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -613,6 +613,8 @@ const TRUSTED_OPENSHELL_RELEASES: readonly OpenShellReleaseTrust[] = [ ...V00116_INSTALLER_TEMPLATE_BASELINE_SHA256, // Exact 0.1.2 pinned-sandbox feature check; runtime policy checks remain required. "610fa58bc4242f23e6ce5e22444dd595995c5a9466bf406a34e5a548869377bc", + // Exact #12603 standalone legacy-state guard; no adjacent helper is projected. + "3ac277104b411ea27963cbf9df41ce6f9e2d39b7c430781c73f88c5489ef4af5", ], manifests: [ { diff --git a/test/fixtures/openshell-v012-installer-legacy-guard.sh b/test/fixtures/openshell-v012-installer-legacy-guard.sh new file mode 100644 index 00000000000..c625b139fe2 --- /dev/null +++ b/test/fixtures/openshell-v012-installer-legacy-guard.sh @@ -0,0 +1,125 @@ +# shellcheck shell=bash +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# Every installation entrypoint must verify legacy state before downloading or +# replacing components. The Homebrew service-control operation above remains +# available so the installed legacy gateway can still be stopped and retired. +command -v node >/dev/null 2>&1 || fail "Node.js is required to verify legacy OpenShell state." +# Keep this guard in the installer: protected execution projects this file alone. +# shellcheck disable=SC2016 # JavaScript template literals are evaluated by Node.js. +node --input-type=module -e ' +import { spawnSync } from "node:child_process"; +import { closeSync, constants, fstatSync, openSync, readFileSync, readdirSync } from "node:fs"; +import { isAbsolute, join } from "node:path"; + +function deny(reason) { + throw new Error( + `Cannot replace OpenShell: ${reason}. Back up and retire the legacy gateway with the installed CLI before retrying. Existing components and gateway data were not changed.`, + ); +} + +function query(binary, args) { + const result = spawnSync(binary, args, { + encoding: "utf8", + timeout: 15_000, + killSignal: "SIGKILL", + maxBuffer: 1024 * 1024, + }); + if (result.error || result.status !== 0 || result.stderr.trim()) { + deny("the installed CLI could not verify legacy gateway state"); + } + return result.stdout.trim(); +} + +function missing(error) { + return error instanceof Error && "code" in error && error.code === "ENOENT"; +} + +function gatewayNames() { + const config = process.env.XDG_CONFIG_HOME || join(process.env.HOME || "", ".config"); + const system = process.env.OPENSHELL_SYSTEM_GATEWAY_DIR ?? "/etc/openshell"; + if (!isAbsolute(config) || !isAbsolute(system)) + deny("gateway configuration paths are not absolute"); + const names = new Map(); + for (const root of [join(config, "openshell", "gateways"), join(system, "gateways")]) { + let entries; + try { + entries = readdirSync(root, { withFileTypes: true }); + } catch (error) { + if (missing(error)) continue; + deny("legacy gateway registrations could not be read"); + } + for (const entry of entries) { + if (entry.isSymbolicLink()) deny("a legacy gateway registration is a symbolic link"); + if (!entry.isDirectory()) continue; + const metadataPath = join(root, entry.name, "metadata.json"); + // An absent record cannot prove retirement. Check and read the opened + // file, without following a substituted symlink or blocking on a FIFO. + const descriptor = openSync( + metadataPath, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + let metadata; + try { + if (!fstatSync(descriptor).isFile()) deny("legacy gateway metadata is not a regular file"); + metadata = JSON.parse(readFileSync(descriptor, "utf8")); + } finally { + closeSync(descriptor); + } + if ( + !/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(entry.name) || + metadata?.name !== entry.name || + typeof metadata.gateway_endpoint !== "string" || + !metadata.gateway_endpoint.trim() + ) { + deny("legacy gateway metadata is invalid"); + } + if (names.has(entry.name) && names.get(entry.name) !== metadata.gateway_endpoint) { + deny("user and system legacy gateway registrations disagree"); + } + names.set(entry.name, metadata.gateway_endpoint); + } + } + return [...names.keys()]; +} + +function verify() { + // Match the component installer PATH selection, not a different CLI override. + const binary = query("bash", ["-c", "command -v openshell || true"]); + if (binary) { + const version = /^openshell (\d+)\.(\d+)\.(\d+)(?:[.+-][A-Za-z0-9.+-]+)?$/.exec( + query(binary, ["--version"]), + ); + if (!version) deny("the installed CLI version is unknown"); + if (Number(version[1]) > 0 || Number(version[2]) > 0) return; + } + // Native gateway list silently omits corrupt metadata. Inspect registrations + // before querying each gateway, rather than trusting an empty gateway list. + const names = gatewayNames(); + if (names.length && (!binary || process.env.OPENSHELL_GATEWAY_ENDPOINT?.trim())) { + deny("legacy gateway inventory requires its installed CLI and recorded endpoint"); + } + for (const name of names) { + const inventory = JSON.parse(query(binary, ["sandbox", "list", "-g", name, "-o", "json"])); + const empty = Array.isArray(inventory) + ? inventory.length === 0 + : inventory !== null && + Array.isArray(inventory.sandboxes) && + inventory.sandboxes.length === 0 && + inventory.next_page_token === ""; + if (!empty) deny("a legacy gateway has sandboxes or an incomplete inventory"); + } +} + +try { + verify(); +} catch (error) { + console.error( + error instanceof Error && error.message.startsWith("Cannot replace OpenShell:") + ? error.message + : "Cannot replace OpenShell: legacy gateway state is unreadable. Preserve the installed CLI and resolve the registration before retrying.", + ); + process.exitCode = 1; +} +' diff --git a/test/install/installer-hash-check.test.ts b/test/install/installer-hash-check.test.ts index fd34b01a2a4..f5e7484c630 100644 --- a/test/install/installer-hash-check.test.ts +++ b/test/install/installer-hash-check.test.ts @@ -46,6 +46,7 @@ import { } from "../helpers/openshell-installer-template"; import { selectPreparedGatewayRuntime } from "../helpers/prepared-gateway-runtime"; +import { registerV012TemplateCases } from "./installer-hash-v012-suite"; const REPO_ROOT = path.join(import.meta.dirname, "../.."); const INSTALLER_TEMPLATE = fs.readFileSync( @@ -940,7 +941,7 @@ describe("installer hash verification", () => { it("verifies all installer and Brev pins from token-free checksum manifests", () => { const result = runFixture("complete"); - expect(result.status, result.stdout).toBe(0); + expect(result.status, result.stdout + result.stderr).toBe(0); expect(result.stdout).toContain("All installer hashes are current"); }); @@ -1052,14 +1053,7 @@ describe("installer hash verification", () => { ]); }); - it("admits only the exact thread-group supervisor template with OpenShell 0.1.2", () => { - const root = createFixture("0.1.2"); - prepareReleaseFixtureRuntime(REPO_ROOT, root, { currentProcessReader: true }); - const run = () => spawnSync("node", preparedReleaseArgs(REPO_ROOT, root), { encoding: "utf8" }); - expect(run().status).toBe(0); - fs.appendFileSync(path.join(root, "src/lib/onboard/docker-driver-gateway-runtime.ts"), "//x"); - expect(run()).toMatchObject({ status: 1, stderr: expect.stringContaining("not base-trusted") }); - }); + registerV012TemplateCases(REPO_ROOT, createFixture); it.each(V012_TRUST_MUTATIONS)( "rejects an altered OpenShell 0.1.2 %s", (_label, name, value, diagnostic) => { diff --git a/test/install/installer-hash-v012-suite.ts b/test/install/installer-hash-v012-suite.ts new file mode 100644 index 00000000000..ffc8eee9496 --- /dev/null +++ b/test/install/installer-hash-v012-suite.ts @@ -0,0 +1,101 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import path from "node:path"; +import { expect, it } from "vitest"; +import { + preparedReleaseArgs, + prepareReleaseFixtureRuntime, +} from "../helpers/openshell-installer-template"; + +const GUARDED_INSTALLER_SHA256 = "3ac277104b411ea27963cbf9df41ce6f9e2d39b7c430781c73f88c5489ef4af5"; + +function guardedInstaller(repoRoot: string, source: string): string { + const fixture = fs.readFileSync( + path.join(repoRoot, "test/fixtures/openshell-v012-installer-legacy-guard.sh"), + "utf8", + ); + const marker = "# Every installation entrypoint"; + assert.ok(fixture.includes(marker)); + const guard = fixture.slice(fixture.indexOf(marker)).trimEnd() + "\n\n"; + const before = [ + " # MCP policy enforcement and credential replacement execute in", + " # openshell-sandbox. When that host artifact is present, require the native", + " # MCP policy marker from that exact binary.", + ].join("\n"); + const after = [ + " # OpenShell 0.1.2 enforces MCP policy in its supervisor image. Recognize", + " # only its exact pinned sandbox artifacts here, not version text alone.", + " # Runtime policy verification still precedes credential/provider changes.", + ].join("\n"); + const fallback = + [ + " local sandbox_digest", + ' sandbox_digest="$(file_sha256 "$sandbox_bin")" || return 1', + ' if [ "$(pinned_sandbox_build_version "$sandbox_digest")" = "0.1.2" ]; then', + " return 0", + " fi", + ].join("\n") + "\n"; + const featureCheck = + ' if [[ "$sandbox_strings" != *"$OPENSHELL_SANDBOX_MCP_FEATURE"* ]]; then\n'; + const installStart = "# invalidState: a consumed"; + for (const required of [before, featureCheck, installStart]) assert.ok(source.includes(required)); + return source + .replace(before, after) + .replace(featureCheck, featureCheck + fallback) + .replace(installStart, guard + installStart); +} + +// Share the collected test file's fixture lifecycle and temporary-directory cleanup. +export function registerV012TemplateCases( + repoRoot: string, + createFixture: (version: string) => string, +): void { + it("admits only the exact thread-group supervisor template with OpenShell 0.1.2", () => { + const root = createFixture("0.1.2"); + prepareReleaseFixtureRuntime(repoRoot, root, { currentProcessReader: true }); + const run = () => spawnSync("node", preparedReleaseArgs(repoRoot, root), { encoding: "utf8" }); + expect(run().status).toBe(0); + fs.appendFileSync(path.join(root, "src/lib/onboard/docker-driver-gateway-runtime.ts"), "//x"); + expect(run()).toMatchObject({ status: 1, stderr: expect.stringContaining("not base-trusted") }); + }); + + it("admits the exact standalone legacy guard but rejects altered guard behavior", () => { + const root = createFixture("0.1.2"); + prepareReleaseFixtureRuntime(repoRoot, root); + const installer = path.join(root, "scripts/install-openshell.sh"); + const source = guardedInstaller(repoRoot, fs.readFileSync(installer, "utf8")); + fs.writeFileSync(installer, source); + const run = () => spawnSync("node", preparedReleaseArgs(repoRoot, root), { encoding: "utf8" }); + const accepted = run(); + expect(accepted.status, accepted.stderr).toBe(0); + const pins = JSON.parse(accepted.stdout) as { + source: string; + operationalTemplateSha256: string; + }[]; + const installers = pins.filter((pin) => pin.source === "installer"); + expect(installers.length).toBeGreaterThan(0); + expect( + installers.every((pin) => pin.operationalTemplateSha256 === GUARDED_INSTALLER_SHA256), + ).toBe(true); + + for (const [original, replacement] of [ + ["constants.O_NOFOLLOW", "0"], + [" verify();", " // verify();"], + ["if (missing(error)) continue;", "continue;"], + ]) { + const mutated = source.replace(original, replacement); + expect(mutated).not.toBe(source); + fs.writeFileSync(installer, mutated); + const denied = run(); + expect(denied).toMatchObject({ + status: 1, + stdout: "", + stderr: expect.stringContaining("installer operational template is not base-trusted"), + }); + } + }); +} From 1edc1af4e301c40fa7739de966ca29bf8ea2e184 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 11:12:46 -0700 Subject: [PATCH 02/11] fix(e2e): admit reviewed candidate installer trust without workflow edits Signed-off-by: Prekshi Vyas --- .../candidate-upgrade-admission.yaml | 91 +++++ .github/workflows/e2e.yaml | 2 + .github/workflows/installer-hash-check.yaml | 11 + ci/openshell-upgrade-trust.json | 5 + scripts/check-installer-hash.sh | 19 +- scripts/checks/extract-installer-pins.mts | 259 +++++++++++--- scripts/checks/openshell-trust-data.mts | 132 +++++++ ...ndidate-upgrade-admission-workflow.test.ts | 173 +++++++++ test/e2e/README.md | 58 +++ .../support/candidate-openshell-trust.test.ts | 335 ++++++++++++++++++ .../candidate-upgrade-admission.test.ts | 220 ++++++++++++ .../openshell-v012-installer-legacy-guard.sh | 1 - test/helpers/openshell-installer-template.ts | 17 + test/install/installer-hash-check.test.ts | 29 +- test/install/installer-hash-v012-suite.ts | 59 ++- tools/e2e/candidate-openshell-trust.mts | 120 +++++++ tools/e2e/candidate-openshell-version.mts | 63 ++-- tools/e2e/candidate-upgrade-admission.mts | 198 +++++++++++ 18 files changed, 1685 insertions(+), 107 deletions(-) create mode 100644 .github/workflows/candidate-upgrade-admission.yaml create mode 100644 ci/openshell-upgrade-trust.json create mode 100644 scripts/checks/openshell-trust-data.mts create mode 100644 test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts create mode 100644 test/e2e/support/candidate-openshell-trust.test.ts create mode 100644 test/e2e/support/candidate-upgrade-admission.test.ts create mode 100644 tools/e2e/candidate-openshell-trust.mts create mode 100644 tools/e2e/candidate-upgrade-admission.mts diff --git a/.github/workflows/candidate-upgrade-admission.yaml b/.github/workflows/candidate-upgrade-admission.yaml new file mode 100644 index 00000000000..b60fa6b8df8 --- /dev/null +++ b/.github/workflows/candidate-upgrade-admission.yaml @@ -0,0 +1,91 @@ +# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +# SPDX-License-Identifier: Apache-2.0 + +# This status complements the native installer hash check; both must pass. +# Candidate files are API data. No candidate checkout or candidate code executes. +name: Security / Candidate Upgrade Admission +on: + pull_request_target: + types: [opened, reopened, synchronize, edited, ready_for_review] + issue_comment: + types: [created, edited, deleted] +permissions: + contents: read + pull-requests: read +jobs: + candidate-upgrade-admission: + if: ${{ github.repository == 'NVIDIA/NemoClaw' && ((github.event_name == 'pull_request_target' && github.event.pull_request.base.ref == 'main' && github.event.pull_request.head.repo.full_name == 'NVIDIA/NemoClaw') || (github.event_name == 'issue_comment' && github.event.issue.pull_request && (contains(github.event.comment.body, 'NemoClaw-Upgrade-E2E:') || contains(github.event.changes.body.from, 'NemoClaw-Upgrade-E2E:')))) }} + concurrency: + group: candidate-upgrade-admission-${{ github.event.pull_request.number || github.event.issue.number }} + cancel-in-progress: false + runs-on: ubuntu-latest + timeout-minutes: 5 + permissions: + contents: read + pull-requests: read + statuses: write + steps: + - name: Invalidate candidate upgrade admission + id: identity + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 + with: + script: | + if (context.repo.owner !== "NVIDIA" || context.repo.repo !== "NemoClaw") throw new Error("Unexpected upgrade repository"); + if (!["pull_request_target", "issue_comment"].includes(context.eventName)) throw new Error("Unexpected upgrade event"); + const marker = value => typeof value === "string" && value.includes("NemoClaw-Upgrade-E2E:"); + if (context.eventName === "issue_comment" && (!context.payload.issue?.pull_request || (!marker(context.payload.comment?.body) && !marker(context.payload.changes?.body?.from)))) return; + const number = context.payload.pull_request?.number ?? context.payload.issue?.number; + if (!Number.isSafeInteger(number) || number <= 0) throw new Error("Invalid upgrade PR number"); + const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: number }); + if (pr.state !== "open") return; + if (pr.head.repo?.full_name !== "NVIDIA/NemoClaw" || pr.base.repo?.full_name !== "NVIDIA/NemoClaw" || pr.base.ref !== "main") throw new Error("Unsupported upgrade PR identity"); + if (!/^[a-f0-9]{40}$/.test(pr.head.sha) || !/^[a-f0-9]{40}$/.test(pr.base.sha)) throw new Error("Invalid upgrade commits"); + await github.rest.repos.createCommitStatus({ + ...context.repo, sha: pr.head.sha, context: "check-hash", state: "pending", + description: "Candidate upgrade trust is being checked", + target_url: context.serverUrl + "/" + context.repo.owner + "/" + context.repo.repo + "/actions/runs/" + context.runId, + }); + core.setOutput("pr_number", String(number)); + core.setOutput("head_sha", pr.head.sha); + core.setOutput("base_sha", pr.base.sha); + - name: Check out trusted admission code + if: ${{ steps.identity.outputs.head_sha != '' }} + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ steps.identity.outputs.base_sha }} + persist-credentials: false + - name: Set up trusted admission runtime + if: ${{ steps.identity.outputs.head_sha != '' }} + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 + with: + node-version: 24.18.1 + - name: Recheck candidate upgrade admission + id: admission + if: ${{ steps.identity.outputs.head_sha != '' }} + env: + GITHUB_TOKEN: ${{ github.token }} + CANDIDATE_REPOSITORY: NVIDIA/NemoClaw + CANDIDATE_SHA: ${{ steps.identity.outputs.head_sha }} + UPGRADE_PR_NUMBER: ${{ steps.identity.outputs.pr_number }} + UPGRADE_BASE_SHA: ${{ steps.identity.outputs.base_sha }} + run: node --no-warnings tools/e2e/candidate-openshell-version.mts + - name: Report current candidate upgrade admission + if: ${{ always() && steps.identity.outputs.head_sha != '' }} + uses: actions/github-script@3a2844b7e9c422d3c10d287c895573f7108da1b3 + env: + UPGRADE_PR_NUMBER: ${{ steps.identity.outputs.pr_number }} + UPGRADE_CANDIDATE_SHA: ${{ steps.identity.outputs.head_sha }} + UPGRADE_BASE_SHA: ${{ steps.identity.outputs.base_sha }} + UPGRADE_OUTCOME: ${{ steps.admission.outcome }} + with: + script: | + const { data: pr } = await github.rest.pulls.get({ ...context.repo, pull_number: Number(process.env.UPGRADE_PR_NUMBER) }); + const current = pr.state === "open" && pr.head.sha === process.env.UPGRADE_CANDIDATE_SHA && pr.base.sha === process.env.UPGRADE_BASE_SHA; + const passed = current && process.env.UPGRADE_OUTCOME === "success"; + await github.rest.repos.createCommitStatus({ + ...context.repo, sha: process.env.UPGRADE_CANDIDATE_SHA, context: "check-hash", + state: passed ? "success" : "failure", + description: passed ? "Current candidate upgrade admission passed" : "Upgrade admission failed or did not complete", + target_url: context.serverUrl + "/" + context.repo.owner + "/" + context.repo.repo + "/actions/runs/" + context.runId, + }); diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 41f6920989b..7fbd1afa330 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -710,6 +710,8 @@ jobs: env: CANDIDATE_REPOSITORY: ${{ inputs.checkout_repository || github.repository }} CANDIDATE_SHA: ${{ inputs.checkout_sha || github.sha }} + UPGRADE_PR_NUMBER: ${{ inputs.pr_number }} + UPGRADE_BASE_SHA: ${{ inputs.base_sha }} GITHUB_TOKEN: ${{ github.token }} run: node --no-warnings tools/e2e/candidate-openshell-version.mts diff --git a/.github/workflows/installer-hash-check.yaml b/.github/workflows/installer-hash-check.yaml index ea7d0fc4f78..7320ff2abb1 100644 --- a/.github/workflows/installer-hash-check.yaml +++ b/.github/workflows/installer-hash-check.yaml @@ -30,6 +30,7 @@ on: permissions: contents: read + pull-requests: read jobs: check-hash: @@ -69,6 +70,11 @@ jobs: .github/actions/ci-installer-hash-check scripts/check-installer-hash.sh scripts/checks/extract-installer-pins.mts + scripts/checks/openshell-trust-data.mts + ci/openshell-upgrade-trust.json + tools/e2e/candidate-openshell-trust.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts sparse-checkout-cone-mode: false - name: Set up trusted installer hash parser runtime @@ -87,6 +93,11 @@ jobs: - name: Verify pull request installer hashes from reviewed code if: github.event_name == 'pull_request' uses: ./.trusted-installer-hash/.github/actions/ci-installer-hash-check + env: + GITHUB_TOKEN: ${{ github.token }} + UPGRADE_PR_NUMBER: ${{ github.event.pull_request.number }} + UPGRADE_CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} + UPGRADE_BASE_SHA: ${{ github.event.pull_request.base.sha }} with: repo-root: ${{ github.workspace }} diff --git a/ci/openshell-upgrade-trust.json b/ci/openshell-upgrade-trust.json new file mode 100644 index 00000000000..fbadb7d59a2 --- /dev/null +++ b/ci/openshell-upgrade-trust.json @@ -0,0 +1,5 @@ +{ + "schemaVersion": 1, + "releases": [], + "revokedTemplateSha256": [] +} diff --git a/scripts/check-installer-hash.sh b/scripts/check-installer-hash.sh index 1662a879ced..2057f151c19 100755 --- a/scripts/check-installer-hash.sh +++ b/scripts/check-installer-hash.sh @@ -83,6 +83,7 @@ check_openshell_release_assets() { local pin_records parser_error parser_errors record_type parsed_version release_version record_extra local selected_release_version="" release_versions="" version_pin_records local count brev_count published_count expected_published_count failures=0 + local -a parser_command=() local -a manifest_specs=() workspace=$(mktemp -d) trap 'rm -rf "$workspace"' RETURN @@ -101,13 +102,17 @@ check_openshell_release_assets() { # removalCondition: replace this parser when both installers directly consume # one canonical machine-readable pin manifest. parser_errors="${workspace}/pin-parser-errors.txt" - if ! pin_records=$(node \ - "${CHECKER_ROOT}/checks/extract-installer-pins.mts" \ - --blueprint "${REPO_ROOT}/nemoclaw-blueprint/blueprint.yaml" \ - --installer "$installer" \ - --brev-installer "$brev_installer" \ - --supervisor-runtime "$supervisor_runtime" \ - --format release-tsv 2>"$parser_errors"); then + parser_command=(node "${CHECKER_ROOT}/checks/extract-installer-pins.mts" + --blueprint "${REPO_ROOT}/nemoclaw-blueprint/blueprint.yaml" + --installer "$installer" + --brev-installer "$brev_installer" + --supervisor-runtime "$supervisor_runtime" + --format release-tsv) + if [[ -n "${UPGRADE_PR_NUMBER:-}" ]]; then + export UPGRADE_CANDIDATE_ROOT="$REPO_ROOT" + parser_command=(node "${CHECKER_ROOT}/../tools/e2e/candidate-openshell-trust.mts") + fi + if ! pin_records=$("${parser_command[@]}" 2>"$parser_errors"); then echo " STALE: unable to extract the OpenShell installer pin tables with trusted parser code." while IFS= read -r parser_error; do echo " ${parser_error}" diff --git a/scripts/checks/extract-installer-pins.mts b/scripts/checks/extract-installer-pins.mts index 27133c14d34..41674619896 100644 --- a/scripts/checks/extract-installer-pins.mts +++ b/scripts/checks/extract-installer-pins.mts @@ -5,6 +5,11 @@ import { createHash } from "node:crypto"; import fs from "node:fs"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { isDeepStrictEqual } from "node:util"; +import { + parseOpenShellTrustRegistry, + type OpenShellTrustRegistry, +} from "./openshell-trust-data.mts"; type Token = { end: number; @@ -58,7 +63,8 @@ type OpenShellPinLayout = { installer: ConsumerPinLayout; }; -type OpenShellReleaseTrust = { +export type OpenShellReleaseTrust = { + revokedTemplateSha256?: readonly string[]; brevTemplateSha256: readonly string[]; featureGateTemplateSha256?: readonly string[]; formula: { @@ -614,7 +620,7 @@ const TRUSTED_OPENSHELL_RELEASES: readonly OpenShellReleaseTrust[] = [ // Exact 0.1.2 pinned-sandbox feature check; runtime policy checks remain required. "610fa58bc4242f23e6ce5e22444dd595995c5a9466bf406a34e5a548869377bc", // Exact #12603 standalone legacy-state guard; no adjacent helper is projected. - "3ac277104b411ea27963cbf9df41ce6f9e2d39b7c430781c73f88c5489ef4af5", + "4d5970db104adeddcb90e38ff13f482c5e41e47897007c14b181c5ab2c3f9ff2", ], manifests: [ { @@ -722,10 +728,13 @@ function validateTrustedRelease(release: OpenShellReleaseTrust): void { } } -function trustedRelease(version: string): OpenShellReleaseTrust { - const duplicateVersions = TRUSTED_OPENSHELL_RELEASES.map((release) => release.version).filter( - (candidate, index, versions) => versions.indexOf(candidate) !== index, - ); +function trustedRelease( + version: string, + releases: readonly OpenShellReleaseTrust[] = currentOpenShellTrust(), +): OpenShellReleaseTrust { + const duplicateVersions = releases + .map((release) => release.version) + .filter((candidate, index, versions) => versions.indexOf(candidate) !== index); if (duplicateVersions.length > 0) { fail( `trusted OpenShell release records contain duplicate versions: ${[ @@ -733,18 +742,136 @@ function trustedRelease(version: string): OpenShellReleaseTrust { ].join(", ")}`, ); } - for (const release of TRUSTED_OPENSHELL_RELEASES) validateTrustedRelease(release); - const release = TRUSTED_OPENSHELL_RELEASES.find((candidate) => candidate.version === version); + for (const release of releases) validateTrustedRelease(release); + const release = releases.find((candidate) => candidate.version === version); if (!release) fail(`OpenShell v${version} is not in the base-trusted release records`); return release; } +/** The caller must authenticate the candidate record independently before invoking this parser. */ +export function extendReviewedOpenShellTrust( + release: OpenShellReleaseTrust, + previous: readonly OpenShellReleaseTrust[] = TRUSTED_OPENSHELL_RELEASES, +): readonly OpenShellReleaseTrust[] { + validateTrustedRelease(release); + const existing = previous.find((entry) => entry.version === release.version); + const identities = (entry: OpenShellReleaseTrust) => ({ + formula: entry.formula, + manifests: entry.manifests, + pinLayout: entry.pinLayout, + sandboxBuilds: entry.sandboxBuilds, + supervisor: entry.supervisor && { + image: entry.supervisor.image, + manifestDigest: entry.supervisor.manifestDigest, + required: entry.supervisor.required, + }, + }); + if (existing && !isDeepStrictEqual(identities(existing), identities(release))) { + fail("Reviewed upgrade cannot replace an existing release's artifact identities"); + } + const merged = existing + ? { + ...existing, + installerTemplateSha256: [ + ...new Set([...existing.installerTemplateSha256, ...release.installerTemplateSha256]), + ], + brevTemplateSha256: [ + ...new Set([...existing.brevTemplateSha256, ...release.brevTemplateSha256]), + ], + featureGateTemplateSha256: [ + ...new Set([ + ...(existing.featureGateTemplateSha256 ?? []), + ...(release.featureGateTemplateSha256 ?? []), + ]), + ], + supervisor: + existing.supervisor && release.supervisor + ? { + ...existing.supervisor, + runtimeTemplateSha256: [ + ...new Set([ + ...existing.supervisor.runtimeTemplateSha256, + ...release.supervisor.runtimeTemplateSha256, + ]), + ], + } + : existing.supervisor, + } + : release; + const releases = [...previous.filter((entry) => entry.version !== release.version), merged]; + trustedRelease(release.version, releases); + return releases; +} + +/** Resolve data beside this trusted parser, never relative to candidate inputs or the working directory. */ +export function readOpenShellTrustRegistry(): OpenShellTrustRegistry { + return parseOpenShellTrustRegistry( + readInstallerInput( + fileURLToPath(new URL("../../ci/openshell-upgrade-trust.json", import.meta.url)), + "trusted OpenShell registry", + ), + ); +} + +function templateHashes(release: OpenShellReleaseTrust): readonly string[] { + return [ + ...release.installerTemplateSha256, + ...release.brevTemplateSha256, + ...(release.featureGateTemplateSha256 ?? []), + ...(release.supervisor?.runtimeTemplateSha256 ?? []), + ]; +} + +/** Preserve history across candidate admission and subsequent main-branch execution. */ +export function resolveOpenShellTrustRegistry( + registry: OpenShellTrustRegistry, + previous?: OpenShellTrustRegistry, +): readonly OpenShellReleaseTrust[] { + if (previous) { + if ( + previous.revokedTemplateSha256.some((hash) => !registry.revokedTemplateSha256.includes(hash)) + ) + fail("Upgrade registry cannot remove a template revocation"); + for (const release of previous.releases) { + const retained = registry.releases.find((entry) => entry.version === release.version); + if ( + !retained || + !isDeepStrictEqual(extendReviewedOpenShellTrust(retained, [release])[0], retained) + ) + fail("Upgrade registry must retain previous release identities and templates"); + } + } + const releases = registry.releases.reduce( + (prior, release) => extendReviewedOpenShellTrust(release, prior), + TRUSTED_OPENSHELL_RELEASES, + ); + const knownHashes = new Set(releases.flatMap(templateHashes)); + if (registry.revokedTemplateSha256.some((hash) => !knownHashes.has(hash))) + fail("Upgrade registry cannot revoke an unknown template"); + if (registry.revokedTemplateSha256.length === 0) return releases; + return releases.map((release) => ({ + ...release, + revokedTemplateSha256: registry.revokedTemplateSha256, + })); +} + +function currentOpenShellTrust(): readonly OpenShellReleaseTrust[] { + return resolveOpenShellTrustRegistry(readOpenShellTrustRegistry()); +} + +function allowedTemplates( + release: OpenShellReleaseTrust, + hashes: readonly string[], +): readonly string[] { + return hashes.filter((hash) => !release.revokedTemplateSha256?.includes(hash)); +} + // Pull-request CI executes this parser from a trusted checkout while these // paths point into the mutable PR tree. Reject links and special files before // reading, verify that the opened file is still the one inspected, and cap the // bytes consumed so PR-authored input cannot redirect or exhaust the verifier. // Regression coverage lives in test/install/installer-hash-check.test.ts. -function readInstallerInput(inputPath: string, sourceLabel: string): string { +export function readInstallerInput(inputPath: string, sourceLabel: string): string { let parentStats: fs.Stats; try { parentStats = fs.lstatSync(path.dirname(inputPath)); @@ -855,10 +982,11 @@ export function validateReleasePinLayout( releaseVersion: string, consumer: "installer" | "Brev launchable", sourceLabel: string, + releases: readonly OpenShellReleaseTrust[] = currentOpenShellTrust(), ): InstallerPin[] { // Resolve the base-trusted record before inspecting the candidate-authored // table shape. A candidate must never select its own layout contract. - const release = trustedRelease(releaseVersion); + const release = trustedRelease(releaseVersion, releases); const layout = consumer === "installer" ? release.pinLayout.installer : release.pinLayout.brev; const manifestNames = new Set(release.manifests.map((manifest) => manifest.asset)); const manifestPins = pins.filter((pin) => manifestNames.has(pin.asset)); @@ -1329,9 +1457,10 @@ function extractSandboxBuildPins(source: string): SandboxBuildPin[] { function assertTrustedSandboxBuildPins( pins: SandboxBuildPin[], release: OpenShellReleaseTrust, + releases: readonly OpenShellReleaseTrust[], ): void { const pinKey = (pin: SandboxBuildPin): string => `${pin.version}:${pin.sha256}`; - const trustedPins = TRUSTED_OPENSHELL_RELEASES.flatMap((trustedRelease) => + const trustedPins = releases.flatMap((trustedRelease) => trustedRelease.sandboxBuilds.map((pin) => ({ ...pin, version: trustedRelease.version })), ); const trustedKeys = new Set(trustedPins.map(pinKey)); @@ -1428,10 +1557,11 @@ function extractSupervisorManifestPins( function assertTrustedSupervisorManifestPins( pins: SupervisorManifestPin[], release: OpenShellReleaseTrust, + releases: readonly OpenShellReleaseTrust[], ): void { const pinKey = (pin: SupervisorManifestPin): string => `${pin.image}|${pin.version}|${pin.manifestDigest}`; - const trustedPins = TRUSTED_OPENSHELL_RELEASES.flatMap((trustedRelease) => + const trustedPins = releases.flatMap((trustedRelease) => trustedRelease.supervisor ? [{ ...trustedRelease.supervisor, version: trustedRelease.version }] : [], @@ -1775,12 +1905,15 @@ function parseCliOptions(argv: string[]): CliOptions { return { blueprint, brevInstaller, format, installer, supervisorRuntime }; } -export function validateInstallerSources(sources: { - blueprintSource: string; - installerSource: string; - brevInstallerSource: string; - supervisorRuntimeSource: string; -}) { +export function validateInstallerSources( + sources: { + blueprintSource: string; + installerSource: string; + brevInstallerSource: string; + supervisorRuntimeSource: string; + }, + releases: readonly OpenShellReleaseTrust[] = currentOpenShellTrust(), +) { const { blueprintSource, installerSource, brevInstallerSource, supervisorRuntimeSource } = sources; const installerPins = extractInstallerPins(installerSource, { @@ -1802,9 +1935,12 @@ export function validateInstallerSources(sources: { installerReleaseVersions.length === 1 ? "installer pin table" : `installer pin table for ${version}`, + releases, ), ); - const installerReleases = installerReleaseVersions.map(trustedRelease); + const installerReleases = installerReleaseVersions.map((version) => + trustedRelease(version, releases), + ); const brevReleaseVersions = [...new Set(brevPins.map((pin) => pin.releaseVersion))].sort(); if (brevReleaseVersions.length !== 1) { fail( @@ -1820,18 +1956,22 @@ export function validateInstallerSources(sources: { releaseVersion, "Brev launchable", "Brev pin table", + releases, ); const pins = [...installerAssetPins, ...brevAssetPins]; - const release = trustedRelease(releaseVersion); + const release = trustedRelease(releaseVersion, releases); const sandboxBuildPins = extractSandboxBuildPins(installerSource); - assertTrustedSandboxBuildPins(sandboxBuildPins, release); + assertTrustedSandboxBuildPins(sandboxBuildPins, release, releases); const supervisor = release.supervisor ?? fail( `release ${release.version} must have exactly one base-trusted supervisor manifest identity`, ); - const supervisorManifestPins = extractSupervisorManifestPins(supervisorRuntimeSource, supervisor); - assertTrustedSupervisorManifestPins(supervisorManifestPins, release); + const supervisorManifestPins = extractSupervisorManifestPins(supervisorRuntimeSource, { + ...supervisor, + runtimeTemplateSha256: allowedTemplates(release, supervisor.runtimeTemplateSha256), + }); + assertTrustedSupervisorManifestPins(supervisorManifestPins, release, releases); const installerTemplateSha256 = assertTrustedTemplate( installerSource, ["openshell_pinned_sha256", "pinned_sandbox_build_version"], @@ -1840,14 +1980,14 @@ export function validateInstallerSources(sources: { /^MAX_VERSION="([0-9]+\.[0-9]+\.[0-9]+)"$/gm, /^DEV_MIN_VERSION="([0-9]+\.[0-9]+\.[0-9]+)"$/gm, ], - release.installerTemplateSha256, + allowedTemplates(release, release.installerTemplateSha256), "installer", ); const brevTemplateSha256 = assertTrustedTemplate( brevInstallerSource, ["openshell_cli_pinned_sha256"], [/^\s*stable\s*\|\s*auto\)\s*OPENSHELL_VERSION="v([0-9]+\.[0-9]+\.[0-9]+)"\s*;;\s*$/gm], - release.brevTemplateSha256, + allowedTemplates(release, release.brevTemplateSha256), "Brev launchable", ); for (const [label, runtimeVersion] of [ @@ -1865,8 +2005,12 @@ export function validateInstallerSources(sources: { } /** Validate the host feature-check module before protected E2E adopts its template. */ -export function validateOpenShellFeatureGateSource(source: string, releaseVersion: string): void { - const release = trustedRelease(releaseVersion); +export function validateOpenShellFeatureGateSource( + source: string, + releaseVersion: string, + releases: readonly OpenShellReleaseTrust[] = currentOpenShellTrust(), +): void { + const release = trustedRelease(releaseVersion, releases); if (Buffer.byteLength(source) > MAX_INSTALLER_INPUT_BYTES || source.includes("\0")) { fail("feature gate source is invalid or too large"); } @@ -1888,7 +2032,7 @@ export function validateOpenShellFeatureGateSource(source: string, releaseVersio return [{ sha256: match[1]!, version: match[2]! }]; }); const allowed = new Set( - TRUSTED_OPENSHELL_RELEASES.flatMap((record) => + releases.flatMap((record) => record.sandboxBuilds.map((pin) => `${record.version}:${pin.sha256}`), ), ); @@ -1906,20 +2050,44 @@ export function validateOpenShellFeatureGateSource(source: string, releaseVersio const normalized = source.slice(0, bodyStart) + "" + source.slice(end); const digest = createHash("sha256").update(normalized).digest("hex"); - if (!release.featureGateTemplateSha256?.includes(digest)) { + if (!allowedTemplates(release, release.featureGateTemplateSha256 ?? []).includes(digest)) { fail(`feature gate operational template is not base-trusted; actual_sha256=${digest}`); } } +/** Emit the same bounded records for base trust and independently reviewed candidate trust. */ +export function installerReleaseTsv({ + pins, + installerReleases, +}: ReturnType): string { + return ( + [ + ...installerReleases.flatMap((release) => + release.manifests.map( + (manifest) => + `manifest\t${release.version}\tOpenShell release\t${manifest.asset}\t${manifest.sha256}`, + ), + ), + ...installerReleases.map( + (release) => + `formula\t${release.version}\t${release.formula.url}\t${release.formula.asset}\t${release.formula.sha256}`, + ), + ...pins.map( + (pin) => `pin\t${pin.releaseVersion}\t${pin.source}\t${pin.asset}\t${pin.sha256}`, + ), + ].join("\n") + "\n" + ); +} + 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"), - }); + const selected = validateInstallerSources({ + blueprintSource: readInstallerInput(options.blueprint, "blueprint"), + installerSource: readInstallerInput(options.installer, "installer"), + brevInstallerSource: readInstallerInput(options.brevInstaller, "Brev launchable"), + supervisorRuntimeSource: readInstallerInput(options.supervisorRuntime, "supervisor runtime"), + }); + const { pins, installerTemplateSha256, brevTemplateSha256 } = selected; if (options.format === "json") { process.stdout.write( `${JSON.stringify( @@ -1933,24 +2101,7 @@ function runCli(): void { return; } if (options.format === "release-tsv") { - process.stdout.write( - [ - ...installerReleases.flatMap((installerRelease) => - installerRelease.manifests.map( - (manifest) => - `manifest\t${installerRelease.version}\tOpenShell release\t${manifest.asset}\t${manifest.sha256}`, - ), - ), - ...installerReleases.map( - (installerRelease) => - `formula\t${installerRelease.version}\t${installerRelease.formula.url}\t${installerRelease.formula.asset}\t${installerRelease.formula.sha256}`, - ), - ...pins.map( - (pin) => `pin\t${pin.releaseVersion}\t${pin.source}\t${pin.asset}\t${pin.sha256}`, - ), - ].join("\n"), - ); - process.stdout.write("\n"); + process.stdout.write(installerReleaseTsv(selected)); return; } process.stdout.write( diff --git a/scripts/checks/openshell-trust-data.mts b/scripts/checks/openshell-trust-data.mts new file mode 100644 index 00000000000..5d50b672b82 --- /dev/null +++ b/scripts/checks/openshell-trust-data.mts @@ -0,0 +1,132 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import type { OpenShellReleaseTrust } from "./extract-installer-pins.mts"; + +type ObjectValue = Record; +function object(value: unknown, keys: string[], optional: string[] = []): ObjectValue { + if (!value || typeof value !== "object" || Array.isArray(value)) + throw new Error("Invalid upgrade trust record"); + const result = value as ObjectValue; + if ( + keys.some((key) => !Object.hasOwn(result, key)) || + Object.keys(result).some((key) => !keys.includes(key) && !optional.includes(key)) + ) { + throw new Error("Upgrade trust record has missing or unexpected fields"); + } + return result; +} +function text(value: unknown, pattern: RegExp): string { + if ( + typeof value !== "string" || + value.length > 256 || + /[\r\n]/u.test(value) || + !pattern.test(value) + ) { + throw new Error("Invalid upgrade trust identity"); + } + return value; +} +function list(value: unknown, parse: (item: unknown) => T): T[] { + if (!Array.isArray(value) || value.length === 0 || value.length > 64) + throw new Error("Invalid upgrade trust list"); + return value.map(parse); +} +function boolean(value: unknown): boolean { + if (typeof value !== "boolean") throw new Error("Invalid upgrade trust requirement"); + return value; +} +const sha256 = (value: unknown) => text(value, /^[a-f0-9]{64}$/u); +const asset = (value: unknown) => text(value, /^openshell[A-Za-z0-9._+-]*$/u); +const hashes = (value: unknown) => list(value, sha256); +function layout(value: unknown) { + const entry = object(value, ["assets", "manifests"]); + return { assets: list(entry.assets, asset), manifests: list(entry.manifests, asset) }; +} + +/** Parse inert, already-reviewed data; this function does not grant admission. */ +function parseRelease(value: unknown): OpenShellReleaseTrust { + const entry = object(value, [ + "version", + "formula", + "manifests", + "pinLayout", + "sandboxBuilds", + "supervisor", + "installerTemplateSha256", + "brevTemplateSha256", + "featureGateTemplateSha256", + ]); + const version = text(entry.version, /^\d+\.\d+\.\d+$/u); + const formula = object(entry.formula, ["asset", "sha256", "url"]); + if ( + formula.asset !== "openshell.rb" || + formula.url !== `https://github.com/NVIDIA/OpenShell/releases/download/v${version}/openshell.rb` + ) { + throw new Error("Upgrade formula must come from the selected NVIDIA/OpenShell release"); + } + const pins = object(entry.pinLayout, ["installer", "brev"]); + const supervisor = object(entry.supervisor, [ + "image", + "manifestDigest", + "required", + "runtimeTemplateSha256", + ]); + if (supervisor.image !== "ghcr.io/nvidia/openshell/supervisor") + throw new Error("Invalid upgrade supervisor repository"); + return { + version, + formula: { asset: "openshell.rb", sha256: sha256(formula.sha256), url: formula.url }, + manifests: list(entry.manifests, (item) => { + const manifest = object(item, ["asset", "sha256"]); + return { asset: asset(manifest.asset), sha256: sha256(manifest.sha256) }; + }), + pinLayout: { installer: layout(pins.installer), brev: layout(pins.brev) }, + sandboxBuilds: list(entry.sandboxBuilds, (item) => { + const binary = object(item, ["sha256", "required"]); + return { sha256: sha256(binary.sha256), required: boolean(binary.required) }; + }), + supervisor: { + image: supervisor.image, + manifestDigest: text(supervisor.manifestDigest, /^sha256:[a-f0-9]{64}$/u), + required: boolean(supervisor.required), + runtimeTemplateSha256: hashes(supervisor.runtimeTemplateSha256), + }, + installerTemplateSha256: hashes(entry.installerTemplateSha256), + brevTemplateSha256: hashes(entry.brevTemplateSha256), + featureGateTemplateSha256: hashes(entry.featureGateTemplateSha256), + }; +} + +export type OpenShellTrustRegistry = { + schemaVersion: 1; + releases: readonly OpenShellReleaseTrust[]; + revokedTemplateSha256: readonly string[]; +}; + +/** Parsing does not confer trust; the caller owns the source's provenance. */ +export function parseOpenShellTrustRegistry(source: string): OpenShellTrustRegistry { + if (Buffer.byteLength(source) > 1024 * 1024) + throw new Error("Upgrade trust registry exceeds its size limit"); + const envelope = object(JSON.parse(source), [ + "schemaVersion", + "releases", + "revokedTemplateSha256", + ]); + if (envelope.schemaVersion !== 1) throw new Error("Unsupported upgrade trust schema"); + if ( + !Array.isArray(envelope.releases) || + envelope.releases.length > 128 || + !Array.isArray(envelope.revokedTemplateSha256) || + envelope.revokedTemplateSha256.length > 1024 + ) + throw new Error("Invalid upgrade trust registry lists"); + const releases = envelope.releases.map(parseRelease); + const revokedTemplateSha256 = envelope.revokedTemplateSha256.map(sha256); + if ( + new Set(releases.map((release) => release.version)).size !== releases.length || + new Set(revokedTemplateSha256).size !== revokedTemplateSha256.length + ) + throw new Error("Duplicate upgrade trust registry entry"); + return { schemaVersion: 1, releases, revokedTemplateSha256 }; +} diff --git a/test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts b/test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts new file mode 100644 index 00000000000..72c047ee2f8 --- /dev/null +++ b/test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts @@ -0,0 +1,173 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { readYaml, type WorkflowJob } from "../../helpers/e2e-workflow-contract"; + +const workflow = readYaml<{ jobs: Record }>( + ".github/workflows/candidate-upgrade-admission.yaml", +); +const steps = workflow.jobs["candidate-upgrade-admission"]!.steps!; +const start = steps.find((step) => step.id === "identity")!.with!.script as string; +const finish = steps.find((step) => step.name === "Report current candidate upgrade admission")! + .with!.script as string; +const AsyncFunction = Object.getPrototypeOf(async () => undefined).constructor; +const head = "a".repeat(40); +const base = "b".repeat(40); + +function fixture() { + const pr = { + state: "open", + head: { sha: head, repo: { full_name: "NVIDIA/NemoClaw" } }, + base: { sha: base, ref: "main", repo: { full_name: "NVIDIA/NemoClaw" } }, + }; + const context = { + eventName: "pull_request_target", + repo: { owner: "NVIDIA", repo: "NemoClaw" }, + serverUrl: "https://github.com", + runId: 456, + payload: { + pull_request: { number: 123 }, + issue: { number: 123, pull_request: {} }, + comment: { body: `NemoClaw-Upgrade-E2E: approve ${head} ${base}` }, + changes: { body: { from: "" } }, + }, + }; + const outputs: Record = {}; + const status = vi.fn(async (_value: unknown) => ({})); + const get = vi.fn(async () => ({ data: pr })); + const github = { rest: { pulls: { get }, repos: { createCommitStatus: status } } }; + return { + pr, + context, + status, + outputs, + get, + start: () => + new AsyncFunction("github", "context", "core", start)(github, context, { + setOutput: (name: string, value: string) => { + outputs[name] = value; + }, + }), + finish: (outcome: string) => + new AsyncFunction("github", "context", "process", finish)(github, context, { + env: { + UPGRADE_PR_NUMBER: "123", + UPGRADE_CANDIDATE_SHA: head, + UPGRADE_BASE_SHA: base, + UPGRADE_OUTCOME: outcome, + }, + }), + }; +} + +describe("candidate upgrade admission status", () => { + it("does not admit a PR closed during verification", async () => { + const f = fixture(); + await f.start(); + f.pr.state = "closed"; + await f.finish("success"); + expect(f.status).toHaveBeenLastCalledWith(expect.objectContaining({ state: "failure" })); + }); + + it.each(["approve", "revoke", "quoted approve"])( + "invalidates the merge status for %s without granting permission", + async (action) => { + const f = fixture(); + f.context.eventName = "issue_comment"; + f.context.payload.comment.body = `NemoClaw-Upgrade-E2E: ${action} ${head} ${base}`; + await f.start(); + expect(f.status).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + sha: head, + context: "check-hash", + state: "pending", + }), + ); + expect(f.outputs).toEqual({ pr_number: "123", head_sha: head, base_sha: base }); + }, + ); + + it("refreshes when editing removes the approval marker", async () => { + const f = fixture(); + f.context.eventName = "issue_comment"; + f.context.payload.changes.body.from = f.context.payload.comment.body; + f.context.payload.comment.body = "removed"; + await f.start(); + expect(f.status).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ state: "pending" })); + }); + + it.each(["pull_request", "push", "workflow_dispatch"])( + "rejects untrusted or unrelated event %s", + async (event) => { + const f = fixture(); + f.context.eventName = event; + await expect(f.start()).rejects.toThrow(/Unexpected upgrade event/); + expect(f.status).not.toHaveBeenCalled(); + }, + ); + + it.each([ + [ + "fork", + (f: ReturnType) => { + f.pr.head.repo.full_name = "other/NemoClaw"; + }, + ], + [ + "base", + (f: ReturnType) => { + f.pr.base.ref = "release"; + }, + ], + [ + "commit", + (f: ReturnType) => { + f.pr.head.sha = "main"; + }, + ], + [ + "number", + (f: ReturnType) => { + f.context.payload.pull_request.number = 0; + }, + ], + ] as const)("rejects invalid %s before writing status", async (_label, mutate) => { + const f = fixture(); + mutate(f); + await expect(f.start()).rejects.toThrow(); + expect(f.status).not.toHaveBeenCalled(); + }); + + it.each(["failure", "cancelled", "skipped", ""])( + "does not turn %s into admission", + async (outcome) => { + const f = fixture(); + await f.finish(outcome); + expect(f.status).toHaveBeenCalledExactlyOnceWith( + expect.objectContaining({ + sha: head, + context: "check-hash", + state: "failure", + }), + ); + }, + ); + + it.each(["head", "base"] as const)("denies stale success when the %s changes", async (key) => { + const f = fixture(); + f.pr[key].sha = "c".repeat(40); + await f.finish("success"); + expect(f.status).toHaveBeenCalledExactlyOnceWith(expect.objectContaining({ state: "failure" })); + }); + + it("reports success only for a completed check on the current open PR", async () => { + const f = fixture(); + await f.start(); + await f.finish("success"); + expect(f.status.mock.calls.map(([value]) => value)).toEqual([ + expect.objectContaining({ sha: head, context: "check-hash", state: "pending" }), + expect.objectContaining({ sha: head, context: "check-hash", state: "success" }), + ]); + }); +}); diff --git a/test/e2e/README.md b/test/e2e/README.md index fef91269b58..4d9f19a313a 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -202,6 +202,64 @@ 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. +### Candidate OpenShell release admission + +An upgrade PR can carry `ci/openshell-upgrade-trust.json` instead of requiring a +separate PR to add each release record to the base verifier. +The JSON contains `schemaVersion: 1`, a `releases` array, and +`revokedTemplateSha256`. Each release records the version, official formula and +checksum-manifest identities, installer and Brev pin layouts, sandbox hashes, +supervisor digest, and operational-template hashes. It cannot replace artifact +identities for a release already recorded on the base. Later upgrades must +retain prior records and revocations. Revoked hashes cannot authorize execution, +even when retained in a historical record. + +This manifest cannot approve itself. A different human with current repository +`maintain` or `admin` permission must review the exact source and post one whole +comment: `NemoClaw-Upgrade-E2E: approve `. The corresponding +`revoke` command withdraws that decision. The latest eligible decision wins; +edited comments, PR-author comments, stale commits, forks, and closed PRs do not +authorize admission. The trusted reader rechecks the PR, comments, and current +permissions before and after fetching the fixed source paths. + +The trusted installer checker compares local sources with the approved commit. +It then verifies upstream checksum and formula records through the existing +network-backed hash check. The E2E version selector uses the same admission. +Unchanged registry data needs no additional approval; base-trusted template +checks still apply. Neither reader executes candidate scripts or grants merge permission. +Missing permission evidence fails closed. + +After merge, the verifier reads the registry beside its trusted checkout, never +from the candidate working directory. Normal branch protection and independent +review govern that transition. An open PR's temporary admission is not merge authority. +`Security / Candidate Upgrade Admission` refreshes the `check-hash` commit status +on upstream PR changes and approval-comment creation, editing, or deletion. +When `check-hash` is required, both that status and the native hash check must pass. +An interrupted refresh remains pending or fails; it cannot reuse an earlier success. + +This does not yet extend the protected runtime's source projection, approve a new +SDK dependency graph, qualify Pi, or add ARM64 candidate catalogs. A data-admission +comment is not permission to execute arbitrary candidate code on a protected +host. Those boundaries require their own supported implementation and validation; +passing the hash check is not full E2E qualification. + +### Accepted candidate-execution direction + +Decision: **Accept**, recorded October 14, 2026. Accountable maintainer: +Prekshi Vyas, through the explicit task instruction accepting this design. +The reason is to support routine upgrades in one PR, or two when a genuine +trust/bootstrap prerequisite is required. Placement remains the existing trusted +E2E controller and managed-image publication pipeline. + +Controllers stay trusted. Complete reviewed candidate code belongs in disposable +isolated test environments, without shared protected-host authority or host +credential mounts. Resources must remain run-owned, with verified cleanup or +retained failure evidence. Existing data, mTLS and unrelated resources stay intact. +Compatibility includes candidate pins, lockfiles, SDK graphs and platform contracts. +Validation requires real-verifier denial tests, lifecycle and cleanup tests, +independent review, and authorized live E2E. This acceptance does not establish +that the remaining SDK, protected-runtime, Pi or ARM64 work is implemented. + 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/candidate-openshell-trust.test.ts b/test/e2e/support/candidate-openshell-trust.test.ts new file mode 100644 index 00000000000..62264b7b79d --- /dev/null +++ b/test/e2e/support/candidate-openshell-trust.test.ts @@ -0,0 +1,335 @@ +// 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 { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { tmpdir } from "node:os"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + installerReleaseTsv, + resolveOpenShellTrustRegistry, + validateInstallerSources, +} from "../../../scripts/checks/extract-installer-pins.mts"; +import { candidateOpenShellVersion } from "../../../tools/e2e/candidate-openshell-version.mts"; +import { + CANDIDATE_OPENSHELL_SOURCES, + CANDIDATE_OPENSHELL_TRUST_PATH, + reviewedCandidateOpenShellTrust, + assertCandidateInstallerCheckout, + verifyCandidateInstallerTrust, +} from "../../../tools/e2e/candidate-openshell-trust.mts"; +import { parseOpenShellTrustRegistry } from "../../../scripts/checks/openshell-trust-data.mts"; +import { copyTrustedInstallerVerifier } from "../../helpers/openshell-installer-template"; + +const identity = { prNumber: 123, candidateSha: "a".repeat(40), baseSha: "b".repeat(40) }; +const version = "9.8.7"; +const temporaryRoots: string[] = []; +afterEach(() => + temporaryRoots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })), +); + +function fixture() { + const sources = Object.fromEntries( + Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ + key, + readFileSync(new URL(`../../../${path}`, import.meta.url), "utf8"), + ]), + ) as Record; + const current = validateInstallerSources(sources); + const release = structuredClone(current.installerReleases[0]!); + const prior = release.version; + release.version = version; + release.formula.url = `https://github.com/NVIDIA/OpenShell/releases/download/v${version}/openshell.rb`; + release.sandboxBuilds = [{ required: false, sha256: "f".repeat(64) }]; + sources.blueprintSource = sources.blueprintSource.replaceAll(`"${prior}"`, `"${version}"`); + sources.installerSource = sources.installerSource + .replaceAll(`v${prior}:`, `v${version}:`) + .replaceAll(`MIN_VERSION="${prior}"`, `MIN_VERSION="${version}"`) + .replaceAll(`MAX_VERSION="${prior}"`, `MAX_VERSION="${version}"`) + .replace( + ' case "$digest" in', + ` case "$digest" in\n ${"f".repeat(64)})\n printf '%s\\n' "${version}"\n ;;`, + ); + sources.brevInstallerSource = sources.brevInstallerSource + .replaceAll(`v${prior}:`, `v${version}:`) + .replaceAll(`OPENSHELL_VERSION="v${prior}"`, `OPENSHELL_VERSION="v${version}"`); + const supervisorHeader = + "const OPENSHELL_SUPERVISOR_MANIFEST_DIGESTS: Readonly> = {\n"; + sources.supervisorRuntimeSource = sources.supervisorRuntimeSource + .replace( + supervisorHeader, + `${supervisorHeader} "${version}": "${release.supervisor!.manifestDigest}",\n`, + ) + .replace( + `QUALIFIED_STABLE_OPENSHELL_VERSION = "${prior}"`, + `QUALIFIED_STABLE_OPENSHELL_VERSION = "${version}"`, + ); + const normalizedSupervisor = sources.supervisorRuntimeSource.replace( + /(?<=const OPENSHELL_SUPERVISOR_MANIFEST_DIGESTS: Readonly> = \{\n)[\s\S]*?(?=\n\};)/u, + "", + ); + release.supervisor!.runtimeTemplateSha256 = [ + createHash("sha256").update(normalizedSupervisor).digest("hex"), + ]; + const files: Record = Object.fromEntries( + Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ + path, + sources[key as keyof typeof sources], + ]), + ); + files[CANDIDATE_OPENSHELL_TRUST_PATH] = JSON.stringify({ + schemaVersion: 1, + releases: [release], + revokedTemplateSha256: [], + }); + const repository = { full_name: "NVIDIA/NemoClaw" }; + const approvals = [ + { + id: 50, + user: { type: "User", login: "reviewer" }, + created_at: "2026-10-14T00:00:00Z", + updated_at: "2026-10-14T00:00:00Z", + body: `NemoClaw-Upgrade-E2E: approve ${identity.candidateSha} ${identity.baseSha}`, + }, + ]; + const routes: Record = { + "/repos/NVIDIA/NemoClaw/pulls/123": { + number: 123, + state: "open", + user: { login: "author" }, + head: { sha: identity.candidateSha, repo: repository }, + base: { sha: identity.baseSha, ref: "main", repo: repository }, + }, + "/repos/NVIDIA/NemoClaw/issues/123/comments?per_page=100&page=1": approvals, + "/repos/NVIDIA/NemoClaw/collaborators/reviewer/permission": { role_name: "maintain" }, + }; + const request = vi.fn(async (path: string): Promise => { + const sourcePath = new URL(path, "https://api.github.com").pathname.replace( + "/repos/NVIDIA/NemoClaw/contents/", + "", + ); + const content = files[sourcePath]; + return content === undefined + ? routes[path] + : { + type: "file", + path: sourcePath, + encoding: "base64", + size: Buffer.byteLength(content), + content: Buffer.from(content).toString("base64"), + }; + }); + return { files, sources, release, approvals, request }; +} + +describe("reviewed candidate OpenShell trust", () => { + it("validates the merged registry without the old PR remaining open", () => { + const f = fixture(); + const registry = parseOpenShellTrustRegistry(f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!); + const mergedTrust = resolveOpenShellTrustRegistry(registry); + expect(validateInstallerSources(f.sources, mergedTrust).releaseVersion).toBe(version); + const next = structuredClone(registry); + const nextRelease = structuredClone(f.release); + nextRelease.version = "9.8.8"; + nextRelease.formula.url = + "https://github.com/NVIDIA/OpenShell/releases/download/v9.8.8/openshell.rb"; + const nextRegistry = { ...next, releases: [...next.releases, nextRelease] }; + const nextTrust = resolveOpenShellTrustRegistry(nextRegistry, registry); + expect(validateInstallerSources(f.sources, nextTrust).releaseVersion).toBe(version); + expect(nextTrust.find((entry) => entry.version === "9.8.8")?.formula).toEqual( + nextRelease.formula, + ); + }); + + it("keeps revoked templates forbidden after merge and across later upgrades", () => { + const f = fixture(); + const selected = validateInstallerSources( + f.sources, + resolveOpenShellTrustRegistry( + parseOpenShellTrustRegistry(f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!), + ), + ); + const registry = parseOpenShellTrustRegistry(f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!); + const revoked = { ...registry, revokedTemplateSha256: [selected.installerTemplateSha256] }; + expect(() => + validateInstallerSources(f.sources, resolveOpenShellTrustRegistry(revoked)), + ).toThrow(/operational template/); + expect(() => resolveOpenShellTrustRegistry(registry, revoked)).toThrow( + /remove a template revocation/, + ); + }); + + it.each([ + [ + "release history", + (registry: ReturnType) => ({ ...registry, releases: [] }), + ], + [ + "artifact identity", + (registry: ReturnType) => ({ + ...registry, + releases: registry.releases.map((release) => ({ + ...release, + formula: { ...release.formula, sha256: "0".repeat(64) }, + })), + }), + ], + [ + "template history", + (registry: ReturnType) => ({ + ...registry, + releases: registry.releases.map((release) => ({ + ...release, + installerTemplateSha256: ["0".repeat(64)], + })), + }), + ], + ] as const)("rejects removal or replacement of %s", (_label, mutate) => { + const f = fixture(); + const registry = parseOpenShellTrustRegistry(f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!); + expect(() => resolveOpenShellTrustRegistry(mutate(registry), registry)).toThrow( + /retain previous|replace an existing/, + ); + }); + + it("binds the inspected checkout and complete upstream verification records to the approved source", async () => { + const f = fixture(); + const approved = await reviewedCandidateOpenShellTrust(identity, f.request); + const root = mkdtempSync(join(tmpdir(), "candidate-installer-trust-")); + temporaryRoots.push(root); + Object.entries(CANDIDATE_OPENSHELL_SOURCES).forEach(([key, path]) => { + mkdirSync(dirname(join(root, path)), { recursive: true }); + writeFileSync(join(root, path), approved.sources[key as keyof typeof approved.sources]); + }); + mkdirSync(join(root, "ci"), { recursive: true }); + writeFileSync( + join(root, CANDIDATE_OPENSHELL_TRUST_PATH), + f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!, + ); + await expect(verifyCandidateInstallerTrust(root, identity, f.request)).resolves.toEqual( + approved.selected, + ); + expect(() => assertCandidateInstallerCheckout(root, approved.sources)).not.toThrow(); + const records = installerReleaseTsv(approved.selected).trimEnd().split("\n"); + expect(records.filter((line) => line.startsWith(`manifest\t${version}\t`))).toHaveLength(3); + expect(records).toContain( + `formula\t${version}\t${f.release.formula.url}\topenshell.rb\t${f.release.formula.sha256}`, + ); + expect(records.filter((line) => line.startsWith("pin\t"))).toHaveLength( + approved.selected.pins.length, + ); + writeFileSync( + join(root, CANDIDATE_OPENSHELL_SOURCES.installerSource), + "unapproved replacement", + ); + expect(() => assertCandidateInstallerCheckout(root, approved.sources)).toThrow( + /differs from the approved commit/, + ); + await expect(verifyCandidateInstallerTrust(root, identity, f.request)).rejects.toThrow( + /differs from the approved commit/, + ); + }); + + it("checks unchanged registry consumers without requesting another approval", async () => { + const request = vi.fn(); + const root = new URL("../../../", import.meta.url).pathname; + const selected = await verifyCandidateInstallerTrust(root, identity, request); + expect(selected.pins.length).toBeGreaterThan(0); + expect(request).not.toHaveBeenCalled(); + }); + + it("loads merged trust beside the CLI verifier instead of the candidate working directory", () => { + const f = fixture(); + const root = mkdtempSync(join(tmpdir(), "merged-installer-trust-")); + temporaryRoots.push(root); + const trusted = join(root, "trusted"); + const candidate = join(root, "candidate"); + copyTrustedInstallerVerifier(new URL("../../../", import.meta.url).pathname, trusted); + Object.entries(f.files).forEach(([path, source]) => { + mkdirSync(dirname(join(candidate, path)), { recursive: true }); + writeFileSync(join(candidate, path), source); + }); + writeFileSync( + join(trusted, CANDIDATE_OPENSHELL_TRUST_PATH), + f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!, + ); + writeFileSync( + join(candidate, CANDIDATE_OPENSHELL_TRUST_PATH), + '{"candidateSelfApproval":true}', + ); + const args = [ + join(trusted, "scripts/checks/extract-installer-pins.mts"), + "--blueprint", + join(candidate, CANDIDATE_OPENSHELL_SOURCES.blueprintSource), + "--installer", + join(candidate, CANDIDATE_OPENSHELL_SOURCES.installerSource), + "--brev-installer", + join(candidate, CANDIDATE_OPENSHELL_SOURCES.brevInstallerSource), + "--supervisor-runtime", + join(candidate, CANDIDATE_OPENSHELL_SOURCES.supervisorRuntimeSource), + "--format", + "release-tsv", + ]; + const result = spawnSync(process.execPath, args, { cwd: candidate, encoding: "utf8" }); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toContain(`manifest\t${version}\t`); + const merged = parseOpenShellTrustRegistry(f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!); + writeFileSync( + join(trusted, CANDIDATE_OPENSHELL_TRUST_PATH), + JSON.stringify({ + ...merged, + revokedTemplateSha256: f.release.installerTemplateSha256, + }), + ); + const revoked = spawnSync(process.execPath, args, { cwd: candidate, encoding: "utf8" }); + expect(revoked.status).toBe(1); + expect(revoked.stdout).toBe(""); + expect(revoked.stderr).toContain("operational template"); + }); + + it("admits a previously unknown release through the real verifier after independent approval", async () => { + const f = fixture(); + expect(() => validateInstallerSources(f.sources)).toThrow( + /not in the base-trusted release records/, + ); + await expect( + candidateOpenShellVersion("NVIDIA/NemoClaw", identity.candidateSha, f.request, identity), + ).resolves.toBe(version); + expect(f.request.mock.calls.some(([path]) => path.includes("/permission"))).toBe(true); + }); + + it("does not let a candidate manifest approve its own release", async () => { + const f = fixture(); + f.approvals.length = 0; + await expect(reviewedCandidateOpenShellTrust(identity, f.request)).rejects.toThrow( + /independent maintainer/, + ); + }); + + it("still rejects operations that differ from the approved template", async () => { + const f = fixture(); + f.files[CANDIDATE_OPENSHELL_SOURCES.installerSource] += "\nunreviewed_operation\n"; + await expect(reviewedCandidateOpenShellTrust(identity, f.request)).rejects.toThrow( + /operational template/, + ); + }); + + it.each([{ schemaVersion: 2 }, { extra: true }, { releases: [{}] }])( + "rejects malformed reviewed data %j", + (change) => { + const f = fixture(); + expect(() => + parseOpenShellTrustRegistry( + JSON.stringify({ + schemaVersion: 1, + releases: [f.release], + revokedTemplateSha256: [], + ...change, + }), + ), + ).toThrow(); + }, + ); +}); diff --git a/test/e2e/support/candidate-upgrade-admission.test.ts b/test/e2e/support/candidate-upgrade-admission.test.ts new file mode 100644 index 00000000000..e91958a61ea --- /dev/null +++ b/test/e2e/support/candidate-upgrade-admission.test.ts @@ -0,0 +1,220 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { describe, expect, it, vi } from "vitest"; +import { readApprovedCandidateUpgrade } from "../../../tools/e2e/candidate-upgrade-admission.mts"; + +const identity = { prNumber: 123, candidateSha: "a".repeat(40), baseSha: "b".repeat(40) }; +const sourcePath = "ci/candidate.json"; +function fixture() { + const repository = { full_name: "NVIDIA/NemoClaw" }; + const pr = { + number: identity.prNumber, + state: "open", + user: { login: "author" }, + head: { sha: identity.candidateSha, repo: { ...repository } }, + base: { sha: identity.baseSha, ref: "main", repo: { ...repository } }, + }; + const approval = { + id: 50, + user: { login: "reviewer", type: "User" }, + created_at: "2026-10-14T00:00:00Z", + updated_at: "2026-10-14T00:00:00Z", + body: `NemoClaw-Upgrade-E2E: approve ${identity.candidateSha} ${identity.baseSha}`, + }; + const records = [approval]; + const permission = { role_name: "maintain" }; + const source = '{"version":"9.8.7"}'; + const blob = { + type: "file", + path: sourcePath, + encoding: "base64", + size: Buffer.byteLength(source), + content: Buffer.from(source).toString("base64"), + }; + const routes = new Map([ + ["/repos/NVIDIA/NemoClaw/pulls/123", pr], + ["/repos/NVIDIA/NemoClaw/issues/123/comments?per_page=100&page=1", records], + ["/repos/NVIDIA/NemoClaw/collaborators/reviewer/permission", permission], + [`/repos/NVIDIA/NemoClaw/contents/${sourcePath}?ref=${identity.candidateSha}`, blob], + ]); + const request = vi.fn(async (path: string): Promise => routes.get(path)); + return { pr, approval, records, permission, source, blob, request, routes }; +} + +describe("candidate upgrade admission", () => { + it("reads reviewed commit data and rechecks both PR identity and current maintainer authority", async () => { + const f = fixture(); + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], f.request)).resolves.toEqual({ + sources: { [sourcePath]: f.source }, + reviewer: "reviewer", + commentId: 50, + }); + expect(f.request.mock.calls.filter(([path]) => path.endsWith("/permission"))).toHaveLength(2); + expect(f.request.mock.calls.filter(([path]) => path.endsWith("/pulls/123"))).toHaveLength(2); + }); + + it.each([{ prNumber: 0 }, { candidateSha: "main" }, { baseSha: "main" }])( + "rejects invalid identity %j before any request", + async (change) => { + const f = fixture(); + await expect( + readApprovedCandidateUpgrade({ ...identity, ...change }, [sourcePath], f.request), + ).rejects.toThrow(/immutable/); + expect(f.request).not.toHaveBeenCalled(); + }, + ); + + it.each(["write", "read", "triage", "none", "custom-role"])( + "rejects the %s role before reading candidate data", + async (role) => { + const f = fixture(); + f.permission.role_name = role; + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], f.request)).rejects.toThrow( + /independent maintainer/, + ); + expect(f.request.mock.calls.some(([path]) => path.includes("/contents/"))).toBe(false); + }, + ); + + it.each([ + "author", + "bot", + "edited", + "quoted", + "newline", + "old-commit", + "old-base", + "revoke", + "deleted", + ])("rejects %s approval records", async (kind) => { + const f = fixture(); + const mutations: Record void> = { + author: () => { + f.approval.user.login = "AUTHOR"; + }, + bot: () => { + f.approval.user.type = "Bot"; + }, + edited: () => { + f.approval.updated_at = "2026-10-14T00:01:00Z"; + }, + quoted: () => { + f.approval.body = `> ${f.approval.body}`; + }, + newline: () => { + f.approval.body += "\n"; + }, + "old-commit": () => { + f.approval.body = f.approval.body.replace(identity.candidateSha, "c".repeat(40)); + }, + "old-base": () => { + f.approval.body = f.approval.body.replace(identity.baseSha, "c".repeat(40)); + }, + revoke: () => { + f.approval.body = f.approval.body.replace("approve", "revoke"); + }, + deleted: () => { + f.records.length = 0; + }, + }; + mutations[kind]!(); + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], f.request)).rejects.toThrow( + /independent maintainer/, + ); + }); + + it.each(["closed", "fork", "base", "head"])( + "rejects a PR with changed %s identity", + async (kind) => { + const f = fixture(); + const mutations: Record void> = { + closed: () => { + f.pr.state = "closed"; + }, + fork: () => { + f.pr.head.repo.full_name = "other/NemoClaw"; + }, + base: () => { + f.pr.base.ref = "release"; + }, + head: () => { + f.pr.head.sha = "c".repeat(40); + }, + }; + mutations[kind]!(); + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], f.request)).rejects.toThrow( + /open upstream PR/, + ); + }, + ); + + it("reads every page and honors a later revocation", async () => { + const f = fixture(); + f.routes.set( + "/repos/NVIDIA/NemoClaw/issues/123/comments?per_page=100&page=1", + Array.from({ length: 100 }, (_, i) => ({ ...f.approval, id: i + 1 })), + ); + f.routes.set("/repos/NVIDIA/NemoClaw/issues/123/comments?per_page=100&page=2", [ + { ...f.approval, id: 101, body: f.approval.body.replace("approve", "revoke") }, + ]); + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], f.request)).rejects.toThrow( + /independent maintainer/, + ); + }); + + it.each(["head", "revocation", "role", "deletion"])( + "rejects %s changes during source acquisition", + async (kind) => { + const f = fixture(); + const mutations: Record void> = { + head: () => { + f.pr.head.sha = "c".repeat(40); + }, + revocation: () => { + f.records.push({ + ...f.approval, + id: 51, + body: f.approval.body.replace("approve", "revoke"), + }); + }, + role: () => { + f.permission.role_name = "read"; + }, + deletion: () => { + f.records.length = 0; + }, + }; + const request = async (path: string) => { + const result = await f.request(path); + path.includes("/contents/") && mutations[kind]!(); + return result; + }; + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], request)).rejects.toThrow(); + }, + ); + + it.each([ + { type: "symlink" }, + { size: 2_000_000 }, + { size: 0 }, + { path: "other" }, + { target: "other" }, + { content: "AA==", size: 1 }, + { content: "/w==", size: 1 }, + ])("rejects unsafe candidate file %j", async (change) => { + const f = fixture(); + Object.assign(f.blob, change); + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], f.request)).rejects.toThrow( + /Invalid candidate/, + ); + }); + + it("does not treat incomplete API access as approval", async () => { + const f = fixture(); + f.request.mockRejectedValueOnce(new Error("API denied")); + await expect(readApprovedCandidateUpgrade(identity, [sourcePath], f.request)).rejects.toThrow( + "API denied", + ); + }); +}); diff --git a/test/fixtures/openshell-v012-installer-legacy-guard.sh b/test/fixtures/openshell-v012-installer-legacy-guard.sh index c625b139fe2..15389703b9b 100644 --- a/test/fixtures/openshell-v012-installer-legacy-guard.sh +++ b/test/fixtures/openshell-v012-installer-legacy-guard.sh @@ -92,7 +92,6 @@ function verify() { query(binary, ["--version"]), ); if (!version) deny("the installed CLI version is unknown"); - if (Number(version[1]) > 0 || Number(version[2]) > 0) return; } // Native gateway list silently omits corrupt metadata. Inspect registrations // before querying each gateway, rather than trusting an empty gateway list. diff --git a/test/helpers/openshell-installer-template.ts b/test/helpers/openshell-installer-template.ts index 7c1619bc658..9ef813ac564 100644 --- a/test/helpers/openshell-installer-template.ts +++ b/test/helpers/openshell-installer-template.ts @@ -7,6 +7,23 @@ import path from "node:path"; import { v00116Pins, v012Pins } from "./openshell-release-fixtures"; import { selectHistoricalGatewayProcessReader } from "./prepared-gateway-runtime"; +/** Stage the verifier and its inert registry for both candidate and separate trusted checkouts. */ +export function copyTrustedInstallerVerifier(repoRoot: string, targetRoot: string): void { + [ + "scripts/check-installer-hash.sh", + "scripts/checks/extract-installer-pins.mts", + "scripts/checks/openshell-trust-data.mts", + "ci/openshell-upgrade-trust.json", + "tools/e2e/candidate-openshell-trust.mts", + "tools/e2e/candidate-upgrade-admission.mts", + "tools/e2e/base-image-publication.mts", + ].forEach((file) => { + const target = path.join(targetRoot, file); + fs.mkdirSync(path.dirname(target), { recursive: true }); + fs.copyFileSync(path.join(repoRoot, file), target); + }); +} + export function brevMutationFixtures( ASSET_DIGESTS: ReadonlyMap, ASSETS: readonly string[], diff --git a/test/install/installer-hash-check.test.ts b/test/install/installer-hash-check.test.ts index f5e7484c630..61eec9fa6db 100644 --- a/test/install/installer-hash-check.test.ts +++ b/test/install/installer-hash-check.test.ts @@ -39,6 +39,7 @@ import { addV00106OperationalTrust, alterRequiredReleaseValue, brevMutationFixtures, + copyTrustedInstallerVerifier, preparedReleaseArgs, prepareReleaseFixtureRuntime, installerReleaseTemplate, @@ -599,17 +600,12 @@ function createFixture( const checksDir = path.join(scriptsDir, "checks"); const binDir = path.join(fixtureRoot, "bin"); tempDirs.push(fixtureRoot); - fs.mkdirSync(checksDir, { recursive: true }); + copyTrustedInstallerVerifier(REPO_ROOT, fixtureRoot); fs.mkdirSync(binDir, { recursive: true }); fs.mkdirSync(path.join(fixtureRoot, "nemoclaw-blueprint"), { recursive: true, }); fs.mkdirSync(path.join(fixtureRoot, "src/lib/onboard"), { recursive: true }); - const checker = fs.readFileSync( - path.join(REPO_ROOT, "scripts", "check-installer-hash.sh"), - "utf8", - ); - fs.writeFileSync(path.join(scriptsDir, "check-installer-hash.sh"), checker); fs.writeFileSync( path.join(checksDir, "extract-installer-pins.mts"), trustSyntheticSupervisorRuntimeTemplate( @@ -752,6 +748,7 @@ function runFixture( openshellVersion?: string, trustedChecker = false, formatting: PinFormatting = "canonical", + candidateAdmission = false, ) { const fixtureRoot = createFixture(openshellVersion, formatting); const targetChecker = path.join(fixtureRoot, "scripts", "check-installer-hash.sh"); @@ -764,12 +761,7 @@ function runFixture( "extract-installer-pins.mts", ); tempDirs.push(trustedRoot); - fs.mkdirSync(path.dirname(trustedParserPath), { recursive: true }); - fs.copyFileSync(path.join(REPO_ROOT, "scripts", "check-installer-hash.sh"), trustedCheckerPath); - fs.copyFileSync( - path.join(REPO_ROOT, "scripts", "checks", "extract-installer-pins.mts"), - trustedParserPath, - ); + copyTrustedInstallerVerifier(REPO_ROOT, trustedRoot); const parserSource = fs.readFileSync(trustedParserPath, "utf8"); const mutateParser = PARSER_MUTATIONS[mode]; const mutatedParserSource = mutateParser?.(parserSource) ?? parserSource; @@ -806,8 +798,11 @@ function runFixture( encoding: "utf8", env: { ...process.env, - GITHUB_TOKEN: "", + GITHUB_TOKEN: candidateAdmission ? "fixture-unused-token" : "", GH_TOKEN: "", + UPGRADE_PR_NUMBER: candidateAdmission ? "123" : "", + UPGRADE_CANDIDATE_SHA: candidateAdmission ? "a".repeat(40) : "", + UPGRADE_BASE_SHA: candidateAdmission ? "b".repeat(40) : "", NEMOCLAW_INSTALLER_HASH_REPO_ROOT: trustedChecker ? fixtureRoot : "", NEMOCLAW_TEST_CURL_MODE: mode.includes("bypass") || mode === "brev-mismatch" ? "complete" : mode, @@ -857,6 +852,14 @@ function parseNpmReplacement(source: string, digest: string, trustedDigest = dig } describe("installer hash verification", () => { + it("keeps upstream asset verification when candidate admission uses unchanged base trust", () => { + expectTrustedRelease( + runFixture("complete", "0.0.116", true, "canonical", true), + "0.0.116", + CHECKSUM_MANIFESTS, + ASSET_DIGESTS_BY_VERSION.get("0.0.116")!, + ); + }); // source-shape-contract: security -- Exact absence of the retired Brev digest prevents a stale installer template from regaining authorization it("does not base-trust the obsolete Brev npm replacement digest", () => { const parserSource = fs.readFileSync( diff --git a/test/install/installer-hash-v012-suite.ts b/test/install/installer-hash-v012-suite.ts index ffc8eee9496..70c03d1eeda 100644 --- a/test/install/installer-hash-v012-suite.ts +++ b/test/install/installer-hash-v012-suite.ts @@ -11,7 +11,7 @@ import { prepareReleaseFixtureRuntime, } from "../helpers/openshell-installer-template"; -const GUARDED_INSTALLER_SHA256 = "3ac277104b411ea27963cbf9df41ce6f9e2d39b7c430781c73f88c5489ef4af5"; +const GUARDED_INSTALLER_SHA256 = "4d5970db104adeddcb90e38ff13f482c5e41e47897007c14b181c5ab2c3f9ff2"; function guardedInstaller(repoRoot: string, source: string): string { const fixture = fs.readFileSync( @@ -86,6 +86,10 @@ export function registerV012TemplateCases( ["constants.O_NOFOLLOW", "0"], [" verify();", " // verify();"], ["if (missing(error)) continue;", "continue;"], + [ + ' if (!version) deny("the installed CLI version is unknown");', + ' if (!version) deny("the installed CLI version is unknown");\n if (Number(version[1]) > 0 || Number(version[2]) > 0) return;', + ], ]) { const mutated = source.replace(original, replacement); expect(mutated).not.toBe(source); @@ -98,4 +102,57 @@ export function registerV012TemplateCases( }); } }); + + it.each(["0.1.2", "1.0.0"])( + "preserves registered legacy data after a partial CLI upgrade to %s", + (installedVersion) => { + const root = createFixture("0.1.2"); + prepareReleaseFixtureRuntime(repoRoot, root); + const installer = path.join(root, "scripts/install-openshell.sh"); + fs.writeFileSync(installer, guardedInstaller(repoRoot, fs.readFileSync(installer, "utf8"))); + const config = path.join(root, "config"); + const registration = path.join(config, "openshell/gateways/nemoclaw"); + fs.mkdirSync(registration, { recursive: true }); + const metadata = path.join(registration, "metadata.json"); + const retained = path.join(registration, "retained-state"); + const binary = path.join(root, "bin/openshell"); + const calls = path.join(root, "calls"); + const download = path.join(root, "download"); + fs.writeFileSync( + metadata, + JSON.stringify({ name: "nemoclaw", gateway_endpoint: "https://localhost:8080" }), + ); + fs.writeFileSync(retained, "legacy user data\n"); + fs.writeFileSync( + binary, + `#!/bin/sh\nprintf '%s\\n' "$*" >> '${calls}'\ncase "$1" in\n --version) printf 'openshell ${installedVersion}\\n' ;;\n sandbox) printf '[{"name":"retained-sandbox"}]\\n' ;;\n *) exit 99 ;;\nesac\n`, + { mode: 0o755 }, + ); + fs.writeFileSync(path.join(root, "bin/curl"), `#!/bin/sh\ntouch '${download}'\nexit 99\n`, { + mode: 0o755, + }); + const paths = [metadata, retained, binary]; + const before = paths.map((file) => fs.readFileSync(file, "utf8")); + const result = spawnSync("bash", [installer], { + encoding: "utf8", + env: { + ...process.env, + HOME: root, + XDG_CONFIG_HOME: config, + OPENSHELL_SYSTEM_GATEWAY_DIR: path.join(root, "system"), + OPENSHELL_GATEWAY_ENDPOINT: "", + PATH: `${path.join(root, "bin")}:${process.env.PATH}`, + }, + }); + expect(result).toMatchObject({ + status: 1, + stderr: expect.stringContaining( + "a legacy gateway has sandboxes or an incomplete inventory", + ), + }); + expect(fs.readFileSync(calls, "utf8")).toBe("--version\nsandbox list -g nemoclaw -o json\n"); + expect(fs.existsSync(download)).toBe(false); + expect(paths.map((file) => fs.readFileSync(file, "utf8"))).toEqual(before); + }, + ); } diff --git a/tools/e2e/candidate-openshell-trust.mts b/tools/e2e/candidate-openshell-trust.mts new file mode 100644 index 00000000000..1606a816c20 --- /dev/null +++ b/tools/e2e/candidate-openshell-trust.mts @@ -0,0 +1,120 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + readOpenShellTrustRegistry, + resolveOpenShellTrustRegistry, + installerReleaseTsv, + readInstallerInput, + validateInstallerSources, +} from "../../scripts/checks/extract-installer-pins.mts"; +import { + readApprovedCandidateUpgrade, + type CandidateUpgradeIdentity, + type UpgradeRequest, +} from "./candidate-upgrade-admission.mts"; +import { pathToFileURL } from "node:url"; +import { isAbsolute, join } from "node:path"; +import { isDeepStrictEqual } from "node:util"; +import { githubRequest } from "./base-image-publication.mts"; +import { parseOpenShellTrustRegistry } from "../../scripts/checks/openshell-trust-data.mts"; + +export const CANDIDATE_OPENSHELL_TRUST_PATH = "ci/openshell-upgrade-trust.json"; +export const CANDIDATE_OPENSHELL_SOURCES = { + 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; + +/** Read the approved manifest and its consumers from the same immutable commit, without execution. */ +export async function reviewedCandidateOpenShellTrust( + identity: CandidateUpgradeIdentity, + request: UpgradeRequest, +) { + const admission = await readApprovedCandidateUpgrade( + identity, + [...Object.values(CANDIDATE_OPENSHELL_SOURCES), CANDIDATE_OPENSHELL_TRUST_PATH], + request, + ); + const registry = parseOpenShellTrustRegistry(admission.sources[CANDIDATE_OPENSHELL_TRUST_PATH]!); + const releases = resolveOpenShellTrustRegistry(registry, readOpenShellTrustRegistry()); + const sources = Object.fromEntries( + Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ + key, + admission.sources[path]!, + ]), + ) as Record; + const selected = validateInstallerSources(sources, releases); + if (!registry.releases.some((release) => release.version === selected.releaseVersion)) + throw new Error("Upgrade trust registry does not select the candidate release"); + return { + registrySource: admission.sources[CANDIDATE_OPENSHELL_TRUST_PATH]!, + sources, + releases, + selected, + reviewer: admission.reviewer, + commentId: admission.commentId, + }; +} + +/** Verify unchanged base trust without a new approval; changed trust must pass live admission. */ +export async function verifyCandidateInstallerTrust( + root: string, + identity: CandidateUpgradeIdentity, + request: UpgradeRequest, +) { + if (!isAbsolute(root)) + throw new Error("Candidate verification requires an absolute checkout root"); + const registrySource = readInstallerInput( + join(root, CANDIDATE_OPENSHELL_TRUST_PATH), + "candidate OpenShell registry", + ); + const registry = parseOpenShellTrustRegistry(registrySource); + const base = readOpenShellTrustRegistry(); + if (isDeepStrictEqual(registry, base)) { + const sources = Object.fromEntries( + Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ + key, + readInstallerInput(join(root, path), path), + ]), + ) as Record; + return validateInstallerSources(sources, resolveOpenShellTrustRegistry(base)); + } + const approved = await reviewedCandidateOpenShellTrust(identity, request); + if (registrySource !== approved.registrySource) + throw new Error("Candidate registry differs from the approved commit"); + assertCandidateInstallerCheckout(root, approved.sources); + return approved.selected; +} + +/** Refuse a green hash check for bytes other than the independently approved commit. */ +export function assertCandidateInstallerCheckout( + root: string, + sources: Record, +): void { + if (!isAbsolute(root)) + throw new Error("Candidate verification requires an absolute checkout root"); + for (const [key, path] of Object.entries(CANDIDATE_OPENSHELL_SOURCES)) { + if (readInstallerInput(join(root, path), path) !== sources[key as keyof typeof sources]) { + throw new Error(`Candidate checkout differs from the approved commit: ${path}`); + } + } +} + +// This command emits inert records only. The shell check still fetches and hashes +// upstream assets; it never executes the approved candidate installer. +if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) { + if (process.argv.length !== 2 || !process.env.GITHUB_TOKEN) + throw new Error("Candidate installer verification requires authenticated GitHub access"); + const selected = await verifyCandidateInstallerTrust( + process.env.UPGRADE_CANDIDATE_ROOT ?? "", + { + prNumber: Number(process.env.UPGRADE_PR_NUMBER), + candidateSha: process.env.UPGRADE_CANDIDATE_SHA ?? "", + baseSha: process.env.UPGRADE_BASE_SHA ?? "", + }, + (url) => githubRequest(url, process.env.GITHUB_TOKEN!), + ); + process.stdout.write(installerReleaseTsv(selected)); +} diff --git a/tools/e2e/candidate-openshell-version.mts b/tools/e2e/candidate-openshell-version.mts index fc597acdc58..743569ec545 100644 --- a/tools/e2e/candidate-openshell-version.mts +++ b/tools/e2e/candidate-openshell-version.mts @@ -3,15 +3,19 @@ import { appendFileSync } from "node:fs"; import { pathToFileURL } from "node:url"; -import { validateInstallerSources } from "../../scripts/checks/extract-installer-pins.mts"; +import { + validateInstallerSources, + readOpenShellTrustRegistry, +} from "../../scripts/checks/extract-installer-pins.mts"; +import { parseOpenShellTrustRegistry } from "../../scripts/checks/openshell-trust-data.mts"; +import { isDeepStrictEqual } from "node:util"; +import { readCandidateUpgradeSource } from "./candidate-upgrade-admission.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; +import { + CANDIDATE_OPENSHELL_SOURCES as SOURCE_PATHS, + CANDIDATE_OPENSHELL_TRUST_PATH, + reviewedCandidateOpenShellTrust, +} from "./candidate-openshell-trust.mts"; // Runs from the trusted workflow checkout, before any candidate code executes. // Candidate files are inert inputs to the existing release/template verifier. @@ -19,36 +23,27 @@ export async function candidateOpenShellVersion( repository: string, candidateSha: string, request: (path: string) => Promise, + review?: { prNumber: number; baseSha: string }, ): 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] = await readCandidateUpgradeSource( + request, + candidateSha, + sourcePath, + ); + } + if (review) { + const registry = parseOpenShellTrustRegistry( + await readCandidateUpgradeSource(request, candidateSha, CANDIDATE_OPENSHELL_TRUST_PATH), + ); + if (!isDeepStrictEqual(registry, readOpenShellTrustRegistry())) { + const approved = await reviewedCandidateOpenShellTrust({ ...review, candidateSha }, request); + return approved.selected.releaseVersion; } - sources[key as keyof typeof SOURCE_PATHS] = bytes.toString("utf8"); } return validateInstallerSources(sources).releaseVersion; } @@ -60,6 +55,12 @@ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) process.env.CANDIDATE_REPOSITORY ?? "", process.env.CANDIDATE_SHA ?? "", (url) => githubRequest(url, process.env.GITHUB_TOKEN ?? ""), + process.env.UPGRADE_PR_NUMBER + ? { + prNumber: Number(process.env.UPGRADE_PR_NUMBER), + baseSha: process.env.UPGRADE_BASE_SHA ?? "", + } + : undefined, ); appendFileSync(output, `version=${version}\n`); console.log(`Reviewed candidate OpenShell release: ${version}`); diff --git a/tools/e2e/candidate-upgrade-admission.mts b/tools/e2e/candidate-upgrade-admission.mts new file mode 100644 index 00000000000..501aa2d03c6 --- /dev/null +++ b/tools/e2e/candidate-upgrade-admission.mts @@ -0,0 +1,198 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +/** Authenticate permission to test candidate artifacts; never grants merge or host-code authority. */ +export interface CandidateUpgradeIdentity { + prNumber: number; + candidateSha: string; + baseSha: string; +} + +export type UpgradeRequest = (path: string) => Promise; +type RecordValue = Record; +const REPOSITORY = "NVIDIA/NemoClaw"; +const PREFIX = `/repos/${REPOSITORY}`; +const SHA = /^[a-f0-9]{40}$/u; +const LOGIN = /^[a-zA-Z0-9][a-zA-Z0-9-]{0,38}$/u; +const MAX_PAGES = 100; +const MAX_SOURCE_BYTES = 1024 * 1024; + +function record(value: unknown): RecordValue { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("Upgrade admission received an invalid GitHub record"); + } + return value as RecordValue; +} + +function assertIdentity(identity: CandidateUpgradeIdentity): void { + if ( + !Number.isSafeInteger(identity.prNumber) || + identity.prNumber < 1 || + !SHA.test(identity.candidateSha) || + !SHA.test(identity.baseSha) + ) + throw new Error("Upgrade admission requires a PR number and immutable candidate/base commits"); +} + +function assertPullRequest(value: unknown, identity: CandidateUpgradeIdentity): string { + const pr = record(value); + const head = record(pr.head); + const base = record(pr.base); + const author = record(pr.user); + if ( + pr.number !== identity.prNumber || + pr.state !== "open" || + head.sha !== identity.candidateSha || + base.sha !== identity.baseSha || + base.ref !== "main" || + record(head.repo).full_name !== REPOSITORY || + record(base.repo).full_name !== REPOSITORY || + typeof author.login !== "string" || + !LOGIN.test(author.login) + ) + throw new Error("Upgrade admission no longer matches the open upstream PR"); + return author.login.toLowerCase(); +} + +async function comments(request: UpgradeRequest, prNumber: number): Promise { + const result: RecordValue[] = []; + const seen = new Set(); + for (let page = 1; page <= MAX_PAGES; page++) { + const values = await request(`${PREFIX}/issues/${prNumber}/comments?per_page=100&page=${page}`); + if (!Array.isArray(values) || values.length > 100) { + throw new Error("Upgrade admission could not read complete PR comments"); + } + for (const value of values) { + const entry = record(value); + if (!Number.isSafeInteger(entry.id) || Number(entry.id) < 1 || seen.has(Number(entry.id))) { + throw new Error("Upgrade admission received duplicate or invalid comment identities"); + } + seen.add(Number(entry.id)); + result.push(entry); + } + if (values.length < 100) return result; + } + throw new Error("Upgrade admission comment pagination exceeded its bound"); +} + +type Decision = { id: number; login: string; action: "approve" | "revoke" }; + +async function currentDecision( + request: UpgradeRequest, + identity: CandidateUpgradeIdentity, + author: string, +): Promise { + const candidates: Decision[] = []; + const permissions = new Map(); + for (const entry of await comments(request, identity.prNumber)) { + const match = + typeof entry.body === "string" + ? /^NemoClaw-Upgrade-E2E: (approve|revoke) ([a-f0-9]{40}) ([a-f0-9]{40})$/u.exec(entry.body) + : null; + if ( + !match || + match[0] !== entry.body || + match[2] !== identity.candidateSha || + match[3] !== identity.baseSha + ) + continue; + // Edited records are not authority: moderation can retain the original author's identity. + if ( + typeof entry.created_at !== "string" || + !Number.isFinite(Date.parse(entry.created_at)) || + entry.created_at !== entry.updated_at + ) + continue; + const user = record(entry.user); + const login = typeof user.login === "string" ? user.login : ""; + if (user.type !== "User" || !LOGIN.test(login) || login.toLowerCase() === author) continue; + const key = login.toLowerCase(); + if (!permissions.has(key)) { + const response = record(await request(`${PREFIX}/collaborators/${login}/permission`)); + // Repository membership or author_association is not a permission check. + const role = response.role_name; + permissions.set(key, role === "maintain" || role === "admin"); + } + if (permissions.get(key)) { + candidates.push({ id: Number(entry.id), login, action: match[1] as Decision["action"] }); + } + } + const latest = candidates.sort((left, right) => right.id - left.id)[0]; + if (!latest || latest.action !== "approve") { + throw new Error( + "Candidate upgrade needs an independent maintainer's current commit-bound E2E approval", + ); + } + return latest; +} + +export async function readCandidateUpgradeSource( + request: UpgradeRequest, + sha: string, + path: string, +): Promise { + if (!SHA.test(sha)) throw new Error("Candidate source requires an immutable commit"); + if ( + path.includes("\n") || + !/^[A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*$/u.test(path) || + path.split("/").some((part) => part === "." || part === "..") + ) { + throw new Error("Invalid candidate upgrade source path"); + } + const blob = record(await request(`${PREFIX}/contents/${path}?ref=${sha}`)); + if ( + blob.type !== "file" || + blob.path !== path || + blob.encoding !== "base64" || + !Number.isSafeInteger(blob.size) || + Number(blob.size) < 1 || + Number(blob.size) > MAX_SOURCE_BYTES || + typeof blob.content !== "string" || + blob.content.length > 1_500_000 || + blob.target !== undefined || + blob.submodule_git_url !== undefined + ) + throw new Error(`Invalid candidate upgrade source: ${path}`); + const bytes = Buffer.from(blob.content, "base64"); + const value = bytes.toString("utf8"); + if (bytes.length !== blob.size || bytes.includes(0) || !Buffer.from(value).equals(bytes)) { + throw new Error(`Invalid candidate upgrade source bytes: ${path}`); + } + return value; +} + +/** + * Read inert inputs between two live admission checks. No caller-supplied receipt, candidate + * workflow, cached role, or local manifest can substitute for the independent GitHub decision. + * Call again before a later privileged phase; the returned data is not reusable authorization. + */ +export async function readApprovedCandidateUpgrade( + input: CandidateUpgradeIdentity, + paths: readonly string[], + request: UpgradeRequest, +): Promise<{ sources: Readonly>; reviewer: string; commentId: number }> { + const identity = Object.freeze({ ...input }); + const selection = [...paths]; + assertIdentity(identity); + if ( + selection.length === 0 || + selection.length > 32 || + new Set(selection).size !== selection.length + ) { + throw new Error("Upgrade admission requires a bounded, unique source selection"); + } + const prPath = `${PREFIX}/pulls/${identity.prNumber}`; + const author = assertPullRequest(await request(prPath), identity); + const before = await currentDecision(request, identity, author); + const sources: Record = Object.create(null); + for (const path of selection) + sources[path] = await readCandidateUpgradeSource(request, identity.candidateSha, path); + if (assertPullRequest(await request(prPath), identity) !== author) { + throw new Error("Upgrade admission PR author changed during source acquisition"); + } + const after = await currentDecision(request, identity, author); + if (before.id !== after.id || before.login !== after.login) { + throw new Error("Upgrade admission decision changed during source acquisition"); + } + return { sources: Object.freeze(sources), reviewer: after.login, commentId: after.id }; +} From e3b279cb9e57c7327dbddb39fde7dd1d2085168d Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 13:12:28 -0700 Subject: [PATCH 03/11] fix(e2e): preserve trusted history for older upgrade candidates --- test/e2e/README.md | 26 +-- .../support/candidate-openshell-trust.test.ts | 173 +++++++-------- .../shared-e2e-workflow-boundary.test.ts | 3 + test/helpers/candidate-openshell-trust.ts | 200 ++++++++++++++++++ test/helpers/openshell-installer-template.ts | 1 + tools/e2e/candidate-openshell-trust.mts | 82 ++++++- tools/e2e/candidate-openshell-version.mts | 11 +- tools/e2e/pre-candidate-workflow-contract.mts | 2 + 8 files changed, 371 insertions(+), 127 deletions(-) create mode 100644 test/helpers/candidate-openshell-trust.ts diff --git a/test/e2e/README.md b/test/e2e/README.md index 4d9f19a313a..62d7cbd8eb2 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -225,8 +225,11 @@ permissions before and after fetching the fixed source paths. The trusted installer checker compares local sources with the approved commit. It then verifies upstream checksum and formula records through the existing network-backed hash check. The E2E version selector uses the same admission. -Unchanged registry data needs no additional approval; base-trusted template -checks still apply. Neither reader executes candidate scripts or grants merge permission. +Registry data already covered by trusted history needs no additional approval. +The trusted checkout's current revocations and template checks still apply to older candidates. +Candidates predating the registry can use only base-trusted records. The API reader +requires a complete directory listing to establish absence; request failures never mean absence. +Neither reader executes candidate scripts or grants merge permission. Missing permission evidence fails closed. After merge, the verifier reads the registry beside its trusted checkout, never @@ -235,6 +238,8 @@ review govern that transition. An open PR's temporary admission is not merge aut `Security / Candidate Upgrade Admission` refreshes the `check-hash` commit status on upstream PR changes and approval-comment creation, editing, or deletion. When `check-hash` is required, both that status and the native hash check must pass. +An approval comment refreshes only the commit status. If the native hash check +failed before approval, rerun that job after approval. An interrupted refresh remains pending or fails; it cannot reuse an earlier success. This does not yet extend the protected runtime's source projection, approve a new @@ -243,23 +248,6 @@ comment is not permission to execute arbitrary candidate code on a protected host. Those boundaries require their own supported implementation and validation; passing the hash check is not full E2E qualification. -### Accepted candidate-execution direction - -Decision: **Accept**, recorded October 14, 2026. Accountable maintainer: -Prekshi Vyas, through the explicit task instruction accepting this design. -The reason is to support routine upgrades in one PR, or two when a genuine -trust/bootstrap prerequisite is required. Placement remains the existing trusted -E2E controller and managed-image publication pipeline. - -Controllers stay trusted. Complete reviewed candidate code belongs in disposable -isolated test environments, without shared protected-host authority or host -credential mounts. Resources must remain run-owned, with verified cleanup or -retained failure evidence. Existing data, mTLS and unrelated resources stay intact. -Compatibility includes candidate pins, lockfiles, SDK graphs and platform contracts. -Validation requires real-verifier denial tests, lifecycle and cleanup tests, -independent review, and authorized live E2E. This acceptance does not establish -that the remaining SDK, protected-runtime, Pi or ARM64 work is implemented. - 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/candidate-openshell-trust.test.ts b/test/e2e/support/candidate-openshell-trust.test.ts index 62264b7b79d..9b725b58257 100644 --- a/test/e2e/support/candidate-openshell-trust.test.ts +++ b/test/e2e/support/candidate-openshell-trust.test.ts @@ -1,9 +1,8 @@ // 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 { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; +import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs"; import { dirname, join } from "node:path"; import { tmpdir } from "node:os"; import { afterEach, describe, expect, it, vi } from "vitest"; @@ -19,112 +18,102 @@ import { reviewedCandidateOpenShellTrust, assertCandidateInstallerCheckout, verifyCandidateInstallerTrust, + readCandidateOpenShellRegistry, } from "../../../tools/e2e/candidate-openshell-trust.mts"; import { parseOpenShellTrustRegistry } from "../../../scripts/checks/openshell-trust-data.mts"; import { copyTrustedInstallerVerifier } from "../../helpers/openshell-installer-template"; -const identity = { prNumber: 123, candidateSha: "a".repeat(40), baseSha: "b".repeat(40) }; -const version = "9.8.7"; +import { + fixture, + runCoveredRegistry, + identity, + version, +} from "../../helpers/candidate-openshell-trust"; const temporaryRoots: string[] = []; afterEach(() => temporaryRoots.splice(0).forEach((root) => rmSync(root, { recursive: true, force: true })), ); -function fixture() { - const sources = Object.fromEntries( - Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ - key, - readFileSync(new URL(`../../../${path}`, import.meta.url), "utf8"), - ]), - ) as Record; - const current = validateInstallerSources(sources); - const release = structuredClone(current.installerReleases[0]!); - const prior = release.version; - release.version = version; - release.formula.url = `https://github.com/NVIDIA/OpenShell/releases/download/v${version}/openshell.rb`; - release.sandboxBuilds = [{ required: false, sha256: "f".repeat(64) }]; - sources.blueprintSource = sources.blueprintSource.replaceAll(`"${prior}"`, `"${version}"`); - sources.installerSource = sources.installerSource - .replaceAll(`v${prior}:`, `v${version}:`) - .replaceAll(`MIN_VERSION="${prior}"`, `MIN_VERSION="${version}"`) - .replaceAll(`MAX_VERSION="${prior}"`, `MAX_VERSION="${version}"`) - .replace( - ' case "$digest" in', - ` case "$digest" in\n ${"f".repeat(64)})\n printf '%s\\n' "${version}"\n ;;`, - ); - sources.brevInstallerSource = sources.brevInstallerSource - .replaceAll(`v${prior}:`, `v${version}:`) - .replaceAll(`OPENSHELL_VERSION="v${prior}"`, `OPENSHELL_VERSION="v${version}"`); - const supervisorHeader = - "const OPENSHELL_SUPERVISOR_MANIFEST_DIGESTS: Readonly> = {\n"; - sources.supervisorRuntimeSource = sources.supervisorRuntimeSource - .replace( - supervisorHeader, - `${supervisorHeader} "${version}": "${release.supervisor!.manifestDigest}",\n`, - ) - .replace( - `QUALIFIED_STABLE_OPENSHELL_VERSION = "${prior}"`, - `QUALIFIED_STABLE_OPENSHELL_VERSION = "${version}"`, - ); - const normalizedSupervisor = sources.supervisorRuntimeSource.replace( - /(?<=const OPENSHELL_SUPERVISOR_MANIFEST_DIGESTS: Readonly> = \{\n)[\s\S]*?(?=\n\};)/u, - "", +describe("reviewed candidate OpenShell trust", () => { + it.each( + (["installer", "version"] as const).flatMap((consumer) => + (["older", "empty", "absent"] as const).map((scenario) => ({ consumer, scenario })), + ), + )( + "accepts $scenario candidate registry in $consumer using current trusted history", + ({ consumer, scenario }) => { + const result = runCoveredRegistry(consumer, scenario, temporaryRoots); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout).toBe(version); + }, ); - release.supervisor!.runtimeTemplateSha256 = [ - createHash("sha256").update(normalizedSupervisor).digest("hex"), - ]; - const files: Record = Object.fromEntries( - Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ - path, - sources[key as keyof typeof sources], - ]), + + it.each( + (["installer", "version"] as const).flatMap((consumer) => + ( + [ + "revoked", + "absent-revoked", + "absent-untrusted", + "symlink", + "new-template", + "changed-artifact", + ] as const + ).map((scenario) => ({ + consumer, + scenario, + })), + ), + )( + "rejects $scenario candidate in $consumer despite older registry compatibility", + ({ consumer, scenario }) => { + const result = runCoveredRegistry(consumer, scenario, temporaryRoots); + expect(result.status).toBe(1); + expect(result.stdout).toBe(""); + expect(result.stderr).toContain( + scenario.endsWith("revoked") + ? "operational template" + : scenario === "absent-untrusted" + ? "not in the base-trusted release records" + : scenario === "symlink" + ? "regular file" + : "fresh approval required", + ); + }, ); - files[CANDIDATE_OPENSHELL_TRUST_PATH] = JSON.stringify({ - schemaVersion: 1, - releases: [release], - revokedTemplateSha256: [], - }); - const repository = { full_name: "NVIDIA/NemoClaw" }; - const approvals = [ + + it.each([ + { label: "non-directory", entries: {} }, { - id: 50, - user: { type: "User", login: "reviewer" }, - created_at: "2026-10-14T00:00:00Z", - updated_at: "2026-10-14T00:00:00Z", - body: `NemoClaw-Upgrade-E2E: approve ${identity.candidateSha} ${identity.baseSha}`, + label: "truncated", + entries: Array.from({ length: 1000 }, (_, index) => ({ path: `ci/${index}`, type: "file" })), }, - ]; - const routes: Record = { - "/repos/NVIDIA/NemoClaw/pulls/123": { - number: 123, - state: "open", - user: { login: "author" }, - head: { sha: identity.candidateSha, repo: repository }, - base: { sha: identity.baseSha, ref: "main", repo: repository }, + { label: "duplicate", entries: [{ path: "ci/other" }, { path: "ci/other" }] }, + { label: "outside-directory", entries: [{ path: "other/manifest.json" }] }, + { label: "null-entry", entries: [null] }, + { + label: "submodule", + entries: [ + { path: CANDIDATE_OPENSHELL_TRUST_PATH, type: "file", submodule_git_url: "untrusted" }, + ], }, - "/repos/NVIDIA/NemoClaw/issues/123/comments?per_page=100&page=1": approvals, - "/repos/NVIDIA/NemoClaw/collaborators/reviewer/permission": { role_name: "maintain" }, - }; - const request = vi.fn(async (path: string): Promise => { - const sourcePath = new URL(path, "https://api.github.com").pathname.replace( - "/repos/NVIDIA/NemoClaw/contents/", - "", - ); - const content = files[sourcePath]; - return content === undefined - ? routes[path] - : { - type: "file", - path: sourcePath, - encoding: "base64", - size: Buffer.byteLength(content), - content: Buffer.from(content).toString("base64"), - }; + ])("does not infer registry absence from $label listing", async ({ entries }) => { + await expect( + readCandidateOpenShellRegistry(identity.candidateSha, async () => entries), + ).rejects.toThrow(/listing|regular file/); }); - return { files, sources, release, approvals, request }; -} -describe("reviewed candidate OpenShell trust", () => { + it.each(["403", "404", "500"])( + "does not infer registry absence from API failure %s", + async (status) => { + await expect( + readCandidateOpenShellRegistry(identity.candidateSha, async () => { + throw new Error(`GitHub API request failed with HTTP ${status}`); + }), + ).rejects.toThrow(`HTTP ${status}`); + }, + ); + it("validates the merged registry without the old PR remaining open", () => { const f = fixture(); const registry = parseOpenShellTrustRegistry(f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!); diff --git a/test/e2e/support/shared-e2e-workflow-boundary.test.ts b/test/e2e/support/shared-e2e-workflow-boundary.test.ts index f1fcc735501..a4076337251 100644 --- a/test/e2e/support/shared-e2e-workflow-boundary.test.ts +++ b/test/e2e/support/shared-e2e-workflow-boundary.test.ts @@ -508,6 +508,7 @@ describe("pre-candidate execution environment identity", () => { "Install trusted E2E planner dependencies", "Generate E2E target matrix", "Stage immutable native Podman E2E toolchains", + "Resolve reviewed candidate OpenShell version", ]; const owners = [ { name: "workflow", select: (workflow: Workflow) => workflow }, @@ -563,6 +564,8 @@ describe("pre-candidate execution environment identity", () => { { owner: owners[6]!, bindingName: "GITHUB_TOKEN" }, { owner: owners[11]!, bindingName: "NEMOCLAW_E2E_CREDENTIALS_ALLOWED" }, { owner: owners[11]!, bindingName: "NEMOCLAW_E2E_INCLUDE_STAGING_BREV_LAUNCHABLE" }, + { owner: owners[13]!, bindingName: "UPGRADE_PR_NUMBER" }, + { owner: owners[13]!, bindingName: "UPGRADE_BASE_SHA" }, ]; const bindingChanges = [ { diff --git a/test/helpers/candidate-openshell-trust.ts b/test/helpers/candidate-openshell-trust.ts new file mode 100644 index 00000000000..b18a1926e2c --- /dev/null +++ b/test/helpers/candidate-openshell-trust.ts @@ -0,0 +1,200 @@ +// 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 { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync, symlinkSync } from "node:fs"; +import { dirname, join } from "node:path"; +import { pathToFileURL } from "node:url"; +import { tmpdir } from "node:os"; +import { vi } from "vitest"; +import { validateInstallerSources } from "../../scripts/checks/extract-installer-pins.mts"; +import { + CANDIDATE_OPENSHELL_SOURCES, + CANDIDATE_OPENSHELL_TRUST_PATH, +} from "../../tools/e2e/candidate-openshell-trust.mts"; +import { parseOpenShellTrustRegistry } from "../../scripts/checks/openshell-trust-data.mts"; +import { copyTrustedInstallerVerifier } from "./openshell-installer-template"; + +export const identity = { prNumber: 123, candidateSha: "a".repeat(40), baseSha: "b".repeat(40) }; +export const version = "9.8.7"; + +export function fixture() { + const sources = Object.fromEntries( + Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ + key, + readFileSync(new URL(`../../${path}`, import.meta.url), "utf8"), + ]), + ) as Record; + const current = validateInstallerSources(sources); + const release = structuredClone(current.installerReleases[0]!); + const prior = release.version; + release.version = version; + release.formula.url = `https://github.com/NVIDIA/OpenShell/releases/download/v${version}/openshell.rb`; + release.sandboxBuilds = [{ required: false, sha256: "f".repeat(64) }]; + sources.blueprintSource = sources.blueprintSource.replaceAll(`"${prior}"`, `"${version}"`); + sources.installerSource = sources.installerSource + .replaceAll(`v${prior}:`, `v${version}:`) + .replaceAll(`MIN_VERSION="${prior}"`, `MIN_VERSION="${version}"`) + .replaceAll(`MAX_VERSION="${prior}"`, `MAX_VERSION="${version}"`) + .replace( + ' case "$digest" in', + ` case "$digest" in\n ${"f".repeat(64)})\n printf '%s\\n' "${version}"\n ;;`, + ); + sources.brevInstallerSource = sources.brevInstallerSource + .replaceAll(`v${prior}:`, `v${version}:`) + .replaceAll(`OPENSHELL_VERSION="v${prior}"`, `OPENSHELL_VERSION="v${version}"`); + const supervisorHeader = + "const OPENSHELL_SUPERVISOR_MANIFEST_DIGESTS: Readonly> = {\n"; + sources.supervisorRuntimeSource = sources.supervisorRuntimeSource + .replace( + supervisorHeader, + `${supervisorHeader} "${version}": "${release.supervisor!.manifestDigest}",\n`, + ) + .replace( + `QUALIFIED_STABLE_OPENSHELL_VERSION = "${prior}"`, + `QUALIFIED_STABLE_OPENSHELL_VERSION = "${version}"`, + ); + const normalizedSupervisor = sources.supervisorRuntimeSource.replace( + /(?<=const OPENSHELL_SUPERVISOR_MANIFEST_DIGESTS: Readonly> = \{\n)[\s\S]*?(?=\n\};)/u, + "", + ); + release.supervisor!.runtimeTemplateSha256 = [ + createHash("sha256").update(normalizedSupervisor).digest("hex"), + ]; + const files: Record = Object.fromEntries( + Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ + path, + sources[key as keyof typeof sources], + ]), + ); + files[CANDIDATE_OPENSHELL_TRUST_PATH] = JSON.stringify({ + schemaVersion: 1, + releases: [release], + revokedTemplateSha256: [], + }); + const repository = { full_name: "NVIDIA/NemoClaw" }; + const approvals = [ + { + id: 50, + user: { type: "User", login: "reviewer" }, + created_at: "2026-10-14T00:00:00Z", + updated_at: "2026-10-14T00:00:00Z", + body: `NemoClaw-Upgrade-E2E: approve ${identity.candidateSha} ${identity.baseSha}`, + }, + ]; + const routes: Record = { + "/repos/NVIDIA/NemoClaw/pulls/123": { + number: 123, + state: "open", + user: { login: "author" }, + head: { sha: identity.candidateSha, repo: repository }, + base: { sha: identity.baseSha, ref: "main", repo: repository }, + }, + "/repos/NVIDIA/NemoClaw/issues/123/comments?per_page=100&page=1": approvals, + "/repos/NVIDIA/NemoClaw/collaborators/reviewer/permission": { role_name: "maintain" }, + }; + const request = vi.fn(async (path: string): Promise => { + const sourcePath = new URL(path, "https://api.github.com").pathname.replace( + "/repos/NVIDIA/NemoClaw/contents/", + "", + ); + const content = files[sourcePath]; + if (sourcePath === "ci") + return Object.keys(files) + .filter((path) => path.startsWith("ci/")) + .map((path) => ({ path, type: "file" })); + return content === undefined + ? routes[path] + : { + type: "file", + path: sourcePath, + encoding: "base64", + size: Buffer.byteLength(content), + content: Buffer.from(content).toString("base64"), + }; + }); + return { files, sources, release, approvals, request }; +} + +export function runCoveredRegistry( + consumer: "installer" | "version", + scenario: + | "older" + | "empty" + | "absent" + | "absent-revoked" + | "absent-untrusted" + | "symlink" + | "revoked" + | "new-template" + | "changed-artifact", + temporaryRoots: string[], +) { + const f = fixture(); + const root = mkdtempSync(join(tmpdir(), "older-candidate-trust-")); + temporaryRoots.push(root); + const trusted = join(root, "trusted"); + const candidate = join(root, "candidate"); + copyTrustedInstallerVerifier(new URL("../../", import.meta.url).pathname, trusted); + const oldRegistry = parseOpenShellTrustRegistry(f.files[CANDIDATE_OPENSHELL_TRUST_PATH]!); + const nextRelease = { + ...structuredClone(f.release), + version: "9.8.8", + formula: { + ...f.release.formula, + url: "https://github.com/NVIDIA/OpenShell/releases/download/v9.8.8/openshell.rb", + }, + }; + writeFileSync( + join(trusted, CANDIDATE_OPENSHELL_TRUST_PATH), + JSON.stringify({ + ...oldRegistry, + releases: scenario === "absent-untrusted" ? [] : [...oldRegistry.releases, nextRelease], + revokedTemplateSha256: scenario.endsWith("revoked") ? f.release.installerTemplateSha256 : [], + }), + ); + const candidateRegistry = structuredClone(oldRegistry); + if (scenario === "empty") candidateRegistry.releases = []; + if (scenario === "new-template") + candidateRegistry.releases[0]!.installerTemplateSha256 = ["0".repeat(64)]; + if (scenario === "changed-artifact") + candidateRegistry.releases[0]!.formula.sha256 = "0".repeat(64); + f.files[CANDIDATE_OPENSHELL_TRUST_PATH] = JSON.stringify(candidateRegistry); + Object.entries(f.files).forEach(([path, source]) => { + mkdirSync(dirname(join(candidate, path)), { recursive: true }); + writeFileSync(join(candidate, path), source); + }); + if (scenario.startsWith("absent") || scenario === "symlink") + rmSync(join(candidate, CANDIDATE_OPENSHELL_TRUST_PATH)); + if (scenario === "symlink") + symlinkSync("missing.json", join(candidate, CANDIDATE_OPENSHELL_TRUST_PATH)); + // Exercise both real consumers against a distinct trusted checkout. Approval reads + // fail so an older candidate cannot pass by accidentally obtaining fresh admission. + return spawnSync( + process.execPath, + [ + "--input-type=module", + "-e", + `import { readFileSync, readdirSync } from 'node:fs'; + import { verifyCandidateInstallerTrust } from ${JSON.stringify(pathToFileURL(join(trusted, "tools/e2e/candidate-openshell-trust.mts")).href)}; + import { candidateOpenShellVersion } from ${JSON.stringify(pathToFileURL(join(trusted, "tools/e2e/candidate-openshell-version.mts")).href)}; + const identity = ${JSON.stringify(identity)}; + const root = ${JSON.stringify(candidate)}; + const request = async (url) => { + const parsed = new URL(url, 'https://api.github.com'); + if (!parsed.pathname.startsWith('/repos/NVIDIA/NemoClaw/contents/')) + throw new Error('fresh approval required'); + const path = parsed.pathname.slice('/repos/NVIDIA/NemoClaw/contents/'.length); + if (path === 'ci') return readdirSync(root + '/ci', { withFileTypes: true }).map(entry => ({ path: 'ci/' + entry.name, type: entry.isFile() ? 'file' : 'symlink' })); + const content = readFileSync(root + '/' + path); + return { type: 'file', path, encoding: 'base64', size: content.length, content: content.toString('base64') }; + }; + const selected = ${JSON.stringify(consumer)} === 'installer' + ? (await verifyCandidateInstallerTrust(root, identity, request)).releaseVersion + : await candidateOpenShellVersion('NVIDIA/NemoClaw', identity.candidateSha, request, identity); + process.stdout.write(selected);`, + ], + { cwd: candidate, encoding: "utf8" }, + ); +} diff --git a/test/helpers/openshell-installer-template.ts b/test/helpers/openshell-installer-template.ts index 9ef813ac564..ba4f0287032 100644 --- a/test/helpers/openshell-installer-template.ts +++ b/test/helpers/openshell-installer-template.ts @@ -15,6 +15,7 @@ export function copyTrustedInstallerVerifier(repoRoot: string, targetRoot: strin "scripts/checks/openshell-trust-data.mts", "ci/openshell-upgrade-trust.json", "tools/e2e/candidate-openshell-trust.mts", + "tools/e2e/candidate-openshell-version.mts", "tools/e2e/candidate-upgrade-admission.mts", "tools/e2e/base-image-publication.mts", ].forEach((file) => { diff --git a/tools/e2e/candidate-openshell-trust.mts b/tools/e2e/candidate-openshell-trust.mts index 1606a816c20..37ec6f9425d 100644 --- a/tools/e2e/candidate-openshell-trust.mts +++ b/tools/e2e/candidate-openshell-trust.mts @@ -10,16 +10,25 @@ import { } from "../../scripts/checks/extract-installer-pins.mts"; import { readApprovedCandidateUpgrade, + readCandidateUpgradeSource, type CandidateUpgradeIdentity, type UpgradeRequest, } from "./candidate-upgrade-admission.mts"; import { pathToFileURL } from "node:url"; +import { lstatSync } from "node:fs"; import { isAbsolute, join } from "node:path"; -import { isDeepStrictEqual } from "node:util"; import { githubRequest } from "./base-image-publication.mts"; -import { parseOpenShellTrustRegistry } from "../../scripts/checks/openshell-trust-data.mts"; +import { + parseOpenShellTrustRegistry, + type OpenShellTrustRegistry, +} from "../../scripts/checks/openshell-trust-data.mts"; export const CANDIDATE_OPENSHELL_TRUST_PATH = "ci/openshell-upgrade-trust.json"; +const emptyRegistry = (): OpenShellTrustRegistry => ({ + schemaVersion: 1, + releases: [], + revokedTemplateSha256: [], +}); export const CANDIDATE_OPENSHELL_SOURCES = { blueprintSource: "nemoclaw-blueprint/blueprint.yaml", installerSource: "scripts/install-openshell.sh", @@ -27,6 +36,50 @@ export const CANDIDATE_OPENSHELL_SOURCES = { supervisorRuntimeSource: "src/lib/onboard/docker-driver-gateway-runtime.ts", } as const; +/** Establish absence from a complete immutable directory listing, never from an API error. */ +export async function readCandidateOpenShellRegistry( + candidateSha: string, + request: UpgradeRequest, +): Promise { + if (!/^[a-f0-9]{40}$/u.test(candidateSha)) + throw new Error("Candidate registry requires an immutable commit"); + const entries = await request(`/repos/NVIDIA/NemoClaw/contents/ci?ref=${candidateSha}`); + // GitHub caps directory responses at 1,000 entries. At the cap, absence is inconclusive. + if (!Array.isArray(entries) || entries.length >= 1000) + throw new Error("Candidate registry directory listing is incomplete or invalid"); + const paths = new Set(); + for (const entry of entries) { + if ( + !entry || + typeof entry !== "object" || + typeof entry.path !== "string" || + !/^ci\/[A-Za-z0-9_.-]+$/u.test(entry.path) || + paths.has(entry.path) + ) + throw new Error("Candidate registry directory listing is invalid"); + paths.add(entry.path); + if ( + entry.path === CANDIDATE_OPENSHELL_TRUST_PATH && + (entry.type !== "file" || entry.submodule_git_url !== undefined || entry.target !== undefined) + ) + throw new Error("Candidate registry must be a regular file"); + } + return paths.has(CANDIDATE_OPENSHELL_TRUST_PATH) + ? parseOpenShellTrustRegistry( + await readCandidateUpgradeSource(request, candidateSha, CANDIDATE_OPENSHELL_TRUST_PATH), + ) + : emptyRegistry(); +} + +function candidateRegistrySource(root: string): string | undefined { + const parent = lstatSync(join(root, "ci")); + if (parent.isSymbolicLink() || !parent.isDirectory()) + throw new Error("Candidate registry parent must be a real directory"); + const path = join(root, CANDIDATE_OPENSHELL_TRUST_PATH); + if (lstatSync(path, { throwIfNoEntry: false }) === undefined) return undefined; + return readInstallerInput(path, "candidate OpenShell registry"); +} + /** Read the approved manifest and its consumers from the same immutable commit, without execution. */ export async function reviewedCandidateOpenShellTrust( identity: CandidateUpgradeIdentity, @@ -58,7 +111,20 @@ export async function reviewedCandidateOpenShellTrust( }; } -/** Verify unchanged base trust without a new approval; changed trust must pass live admission. */ +/** Older candidate data needs no new approval when trusted history already covers it. */ +export function registryCoveredByTrusted( + candidate: OpenShellTrustRegistry, + trusted: OpenShellTrustRegistry, +): boolean { + try { + resolveOpenShellTrustRegistry(trusted, candidate); + return true; + } catch { + return false; + } +} + +/** Verify base-covered trust without a new approval; new trust must pass live admission. */ export async function verifyCandidateInstallerTrust( root: string, identity: CandidateUpgradeIdentity, @@ -66,13 +132,11 @@ export async function verifyCandidateInstallerTrust( ) { if (!isAbsolute(root)) throw new Error("Candidate verification requires an absolute checkout root"); - const registrySource = readInstallerInput( - join(root, CANDIDATE_OPENSHELL_TRUST_PATH), - "candidate OpenShell registry", - ); - const registry = parseOpenShellTrustRegistry(registrySource); + const registrySource = candidateRegistrySource(root); + const registry = + registrySource === undefined ? emptyRegistry() : parseOpenShellTrustRegistry(registrySource); const base = readOpenShellTrustRegistry(); - if (isDeepStrictEqual(registry, base)) { + if (registryCoveredByTrusted(registry, base)) { const sources = Object.fromEntries( Object.entries(CANDIDATE_OPENSHELL_SOURCES).map(([key, path]) => [ key, diff --git a/tools/e2e/candidate-openshell-version.mts b/tools/e2e/candidate-openshell-version.mts index 743569ec545..f0ec62f7ce9 100644 --- a/tools/e2e/candidate-openshell-version.mts +++ b/tools/e2e/candidate-openshell-version.mts @@ -7,14 +7,13 @@ import { validateInstallerSources, readOpenShellTrustRegistry, } from "../../scripts/checks/extract-installer-pins.mts"; -import { parseOpenShellTrustRegistry } from "../../scripts/checks/openshell-trust-data.mts"; -import { isDeepStrictEqual } from "node:util"; import { readCandidateUpgradeSource } from "./candidate-upgrade-admission.mts"; import { githubRequest } from "./base-image-publication.mts"; import { CANDIDATE_OPENSHELL_SOURCES as SOURCE_PATHS, - CANDIDATE_OPENSHELL_TRUST_PATH, + readCandidateOpenShellRegistry, reviewedCandidateOpenShellTrust, + registryCoveredByTrusted, } from "./candidate-openshell-trust.mts"; // Runs from the trusted workflow checkout, before any candidate code executes. @@ -37,10 +36,8 @@ export async function candidateOpenShellVersion( ); } if (review) { - const registry = parseOpenShellTrustRegistry( - await readCandidateUpgradeSource(request, candidateSha, CANDIDATE_OPENSHELL_TRUST_PATH), - ); - if (!isDeepStrictEqual(registry, readOpenShellTrustRegistry())) { + const registry = await readCandidateOpenShellRegistry(candidateSha, request); + if (!registryCoveredByTrusted(registry, readOpenShellTrustRegistry())) { const approved = await reviewedCandidateOpenShellTrust({ ...review, candidateSha }, request); return approved.selected.releaseVersion; } diff --git a/tools/e2e/pre-candidate-workflow-contract.mts b/tools/e2e/pre-candidate-workflow-contract.mts index a98c358570a..d5a15a7b489 100644 --- a/tools/e2e/pre-candidate-workflow-contract.mts +++ b/tools/e2e/pre-candidate-workflow-contract.mts @@ -78,6 +78,8 @@ export const PRE_CANDIDATE_STEP_ENV: Readonly Date: Wed, 14 Oct 2026 14:13:47 -0700 Subject: [PATCH 04/11] feat(ci): admit reviewed candidate SDK artifacts Signed-off-by: Prekshi Vyas --- .../actions/ci-cli-coverage-merge/action.yaml | 1 + .../actions/ci-cli-coverage-shard/action.yaml | 1 + .../actions/ci-compile-artifacts/action.yaml | 1 + .github/actions/ci-install-dependencies.sh | 3 + .../ci-installer-integration/action.yaml | 1 + .../actions/ci-plugin-coverage/action.yaml | 1 + .github/actions/ci-static-checks/action.yaml | 1 + .../candidate-upgrade-admission.yaml | 56 +++ .github/workflows/e2e.yaml | 1 + .github/workflows/pr.yaml | 70 +++- ci/source-shape-test-budget.json | 2 +- scripts/checks/candidate-openshell-sdk.mts | 258 ++++++++++++++ .../checks/package-openshell-sdk-for-pr.mts | 117 ++++++- scripts/checks/prepare-ci-npm-install.mts | 318 ++++-------------- scripts/lib/reviewed-ci-npm-install.mts | 264 +++++++++++++++ scripts/lib/reviewed-npm-cache.mts | 10 +- ...ndidate-upgrade-admission-workflow.test.ts | 70 ++++ .../pr-workflow-contract.test.ts | 18 +- test/e2e/README.md | 19 +- .../candidate-openshell-sdk-artifact.test.ts | 108 ++++++ .../candidate-openshell-sdk-install.test.ts | 162 +++++++++ .../candidate-openshell-sdk.test.ts | 296 ++++++++++++++++ .../ci-install-dependencies.test.ts | 24 ++ .../package-openshell-sdk-for-pr.test.ts | 44 +++ .../repository/prepare-ci-npm-install.test.ts | 23 ++ test/support/candidate-openshell-sdk.ts | 239 +++++++++++++ 26 files changed, 1837 insertions(+), 271 deletions(-) create mode 100644 scripts/checks/candidate-openshell-sdk.mts create mode 100644 scripts/lib/reviewed-ci-npm-install.mts create mode 100644 test/repository/candidate-openshell-sdk-artifact.test.ts create mode 100644 test/repository/candidate-openshell-sdk-install.test.ts create mode 100644 test/repository/candidate-openshell-sdk.test.ts create mode 100644 test/support/candidate-openshell-sdk.ts diff --git a/.github/actions/ci-cli-coverage-merge/action.yaml b/.github/actions/ci-cli-coverage-merge/action.yaml index 9dff906b96e..83729523f89 100644 --- a/.github/actions/ci-cli-coverage-merge/action.yaml +++ b/.github/actions/ci-cli-coverage-merge/action.yaml @@ -44,6 +44,7 @@ runs: shell: bash env: NODE_AUTH_TOKEN: ${{ github.event_name == 'push' && github.token || '' }} + GITHUB_TOKEN: ${{ github.event_name == 'pull_request' && github.token || '' }} run: bash "$GITHUB_ACTION_PATH/../ci-install-dependencies.sh" none - name: Download compiled CLI artifact diff --git a/.github/actions/ci-cli-coverage-shard/action.yaml b/.github/actions/ci-cli-coverage-shard/action.yaml index 68738ae1c73..03d8a2e956a 100644 --- a/.github/actions/ci-cli-coverage-shard/action.yaml +++ b/.github/actions/ci-cli-coverage-shard/action.yaml @@ -95,6 +95,7 @@ runs: shell: bash env: NODE_AUTH_TOKEN: ${{ github.event_name == 'push' && github.token || '' }} + GITHUB_TOKEN: ${{ github.event_name == 'pull_request' && github.token || '' }} run: bash "$GITHUB_ACTION_PATH/../ci-install-dependencies.sh" production - name: Validate changed live E2E mock parity diff --git a/.github/actions/ci-compile-artifacts/action.yaml b/.github/actions/ci-compile-artifacts/action.yaml index 684e0c28494..066ac79de68 100644 --- a/.github/actions/ci-compile-artifacts/action.yaml +++ b/.github/actions/ci-compile-artifacts/action.yaml @@ -43,6 +43,7 @@ runs: shell: bash env: NODE_AUTH_TOKEN: ${{ github.event_name == 'push' && github.token || '' }} + GITHUB_TOKEN: ${{ github.event_name == 'pull_request' && github.token || '' }} run: bash "$GITHUB_ACTION_PATH/../ci-install-dependencies.sh" - name: Compile CLI and plugin diff --git a/.github/actions/ci-install-dependencies.sh b/.github/actions/ci-install-dependencies.sh index 2b873f56665..71108d52c66 100755 --- a/.github/actions/ci-install-dependencies.sh +++ b/.github/actions/ci-install-dependencies.sh @@ -71,6 +71,9 @@ NEMOCLAW_CI_NPM_CACHE="$npm_cache" \ NEMOCLAW_OPEN_SHELL_SDK_ARTIFACT_DIRECTORY="${RUNNER_TEMP:-$target_root/.ci-artifacts}/openshell-sdk" \ node "$trusted_root/scripts/checks/prepare-ci-npm-install.mts" +# Admission credentials belong to trusted preparation, not candidate dependency installation. +unset GITHUB_TOKEN GH_TOKEN + trusted_npmrc="" cleanup() { if [ -n "$trusted_npmrc" ]; then diff --git a/.github/actions/ci-installer-integration/action.yaml b/.github/actions/ci-installer-integration/action.yaml index 4f29fed36a2..0695f3e0bc2 100644 --- a/.github/actions/ci-installer-integration/action.yaml +++ b/.github/actions/ci-installer-integration/action.yaml @@ -23,6 +23,7 @@ runs: shell: bash env: NODE_AUTH_TOKEN: ${{ github.event_name == 'push' && github.token || '' }} + GITHUB_TOKEN: ${{ github.event_name == 'pull_request' && github.token || '' }} run: bash "$GITHUB_ACTION_PATH/../ci-install-dependencies.sh" - name: Build installer integration artifacts diff --git a/.github/actions/ci-plugin-coverage/action.yaml b/.github/actions/ci-plugin-coverage/action.yaml index 77cbf2040c9..a5e068f6244 100644 --- a/.github/actions/ci-plugin-coverage/action.yaml +++ b/.github/actions/ci-plugin-coverage/action.yaml @@ -23,6 +23,7 @@ runs: shell: bash env: NODE_AUTH_TOKEN: ${{ github.event_name == 'push' && github.token || '' }} + GITHUB_TOKEN: ${{ github.event_name == 'pull_request' && github.token || '' }} run: bash "$GITHUB_ACTION_PATH/../ci-install-dependencies.sh" - name: Run plugin coverage diff --git a/.github/actions/ci-static-checks/action.yaml b/.github/actions/ci-static-checks/action.yaml index 13299285063..71bbdb7c63d 100644 --- a/.github/actions/ci-static-checks/action.yaml +++ b/.github/actions/ci-static-checks/action.yaml @@ -44,6 +44,7 @@ runs: shell: bash env: NODE_AUTH_TOKEN: ${{ github.event_name == 'push' && github.token || '' }} + GITHUB_TOKEN: ${{ github.event_name == 'pull_request' && github.token || '' }} run: bash "$GITHUB_ACTION_PATH/../ci-install-dependencies.sh" - name: Verify reviewed runtime bundles diff --git a/.github/workflows/candidate-upgrade-admission.yaml b/.github/workflows/candidate-upgrade-admission.yaml index b60fa6b8df8..cd13f222ed2 100644 --- a/.github/workflows/candidate-upgrade-admission.yaml +++ b/.github/workflows/candidate-upgrade-admission.yaml @@ -24,6 +24,10 @@ jobs: contents: read pull-requests: read statuses: write + outputs: + pr_number: ${{ steps.identity.outputs.pr_number }} + head_sha: ${{ steps.identity.outputs.head_sha }} + base_sha: ${{ steps.identity.outputs.base_sha }} steps: - name: Invalidate candidate upgrade admission id: identity @@ -89,3 +93,55 @@ jobs: description: passed ? "Current candidate upgrade admission passed" : "Upgrade admission failed or did not complete", target_url: context.serverUrl + "/" + context.repo.owner + "/" + context.repo.repo + "/actions/runs/" + context.runId, }); + + candidate-sdk-package: + needs: candidate-upgrade-admission + if: ${{ needs.candidate-upgrade-admission.outputs.head_sha != '' }} + runs-on: ubuntu-latest + timeout-minutes: 10 + permissions: + contents: read + pull-requests: read + packages: read + steps: + - name: Check out trusted SDK producer + uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 + with: + repository: NVIDIA/NemoClaw + ref: ${{ needs.candidate-upgrade-admission.outputs.base_sha }} + persist-credentials: false + - name: Set up trusted package runtime + uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 + with: + node-version: 24.18.1 + registry-url: https://npm.pkg.github.com + scope: "@nvidia" + - name: Install reviewed npm + uses: ./.github/actions/setup-reviewed-npm + - name: Package a newly admitted SDK + id: package + env: + GITHUB_TOKEN: ${{ github.token }} + NODE_AUTH_TOKEN: ${{ github.token }} + UPGRADE_PR_NUMBER: ${{ needs.candidate-upgrade-admission.outputs.pr_number }} + CANDIDATE_SHA: ${{ needs.candidate-upgrade-admission.outputs.head_sha }} + UPGRADE_BASE_SHA: ${{ needs.candidate-upgrade-admission.outputs.base_sha }} + run: | + node --input-type=module <<'NODE' + import { appendFileSync } from 'node:fs'; + import { join } from 'node:path'; + import { packageCandidateOpenShellSdkIfRequired } from './scripts/checks/package-openshell-sdk-for-pr.mts'; + import { githubRequest } from './tools/e2e/base-image-publication.mts'; + const identity = { prNumber: Number(process.env.UPGRADE_PR_NUMBER), candidateSha: process.env.CANDIDATE_SHA, baseSha: process.env.UPGRADE_BASE_SHA }; + const result = await packageCandidateOpenShellSdkIfRequired(join(process.env.RUNNER_TEMP, 'candidate-sdk'), identity, path => githubRequest(path, process.env.GITHUB_TOKEN)); + appendFileSync(process.env.GITHUB_OUTPUT, `required=${result.required}\n`); + if (result.required) appendFileSync(process.env.GITHUB_OUTPUT, `bundle_name=${result.bundleName}\nartifact_name=${result.artifactName}\n`); + NODE + - name: Upload the verified candidate SDK + if: steps.package.outputs.required == 'true' + uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a + with: + name: ${{ steps.package.outputs.bundle_name }} + path: ${{ runner.temp }}/candidate-sdk/${{ steps.package.outputs.artifact_name }} + if-no-files-found: error + retention-days: 7 diff --git a/.github/workflows/e2e.yaml b/.github/workflows/e2e.yaml index 7fbd1afa330..e1871d732a8 100644 --- a/.github/workflows/e2e.yaml +++ b/.github/workflows/e2e.yaml @@ -818,6 +818,7 @@ jobs: scripts/check-dist-sourcemaps.mts scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 6d8e05082f7..0eb79c17651 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -11,6 +11,12 @@ on: permissions: contents: read + pull-requests: read + +env: + UPGRADE_PR_NUMBER: ${{ github.event.pull_request.number }} + CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} + UPGRADE_BASE_SHA: ${{ github.event.pull_request.base.sha }} concurrency: group: ${{ github.workflow }}-${{ github.ref }}-${{ github.event.action != 'edited' || github.event.changes.base != null }} @@ -132,6 +138,10 @@ jobs: ci/reviewed-npm-audit.json scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts @@ -199,6 +209,7 @@ jobs: permissions: actions: read contents: read + pull-requests: read outputs: required: ${{ steps.locate.outputs.required }} runs-on: ubuntu-latest @@ -209,7 +220,9 @@ jobs: with: persist-credentials: false sparse-checkout: | + package.json package-lock.json + nemoclaw/package.json nemoclaw/package-lock.json sparse-checkout-cone-mode: false @@ -224,6 +237,10 @@ jobs: ci/reviewed-npm-audit.json scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/npm-diagnostics.sh scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts @@ -237,6 +254,7 @@ jobs: id: locate env: GH_TOKEN: ${{ github.token }} + GITHUB_TOKEN: ${{ github.token }} HEAD_REPOSITORY: ${{ github.event.pull_request.head.repo.full_name }} REPOSITORY_ID: ${{ github.repository_id }} run: | @@ -253,22 +271,32 @@ jobs: artifact_name="$(jq -er '.artifactName | select(type == "string" and test("^[a-z0-9][a-z0-9._-]*\\.tgz$"))' <<<"$decision")" bundle="$(jq -cS '[.sourceRegistryPackage, .sourceRegistryPackageReplacement // empty]' .trusted-sdk-package-decision/ci/reviewed-npm-audit.json | sha256sum | cut -d ' ' -f 1)" bundle_name="reviewed-openshell-sdk-$bundle" + candidate="$(jq -er '.candidate // false | tostring' <<<"$decision")" + if [ "$candidate" = "true" ]; then + bundle_name="$(jq -er '.bundleName | select(test("^candidate-openshell-sdk-[0-9]+-[a-f0-9]{40}-[a-f0-9]{40}-[0-9]+$"))' <<<"$decision")" + fi if ! artifacts="$(gh api --paginate --slurp "repos/$GITHUB_REPOSITORY/actions/artifacts?name=$bundle_name&per_page=100" 2>/dev/null)"; then echo "::error::Could not list approved SDK artifacts. Restore Actions access, then rerun this CI job." exit 1 fi - artifact="$(jq -cer --arg name "$bundle_name" --argjson repo "$REPOSITORY_ID" ' + artifact="$(jq -cer --arg name "$bundle_name" --arg candidate "$candidate" --argjson repo "$REPOSITORY_ID" ' [.[] | .artifacts[] | select(.name == $name and .expired == false - and .workflow_run.head_branch == "main" and .workflow_run.head_repository_id == $repo)] + and ($candidate == "true" or .workflow_run.head_branch == "main") and .workflow_run.head_repository_id == $repo)] | max_by(.id) // error("missing SDK artifact")' <<<"$artifacts")" || { - echo "::error::No retained SDK archive matches the approved package identities. Run gh workflow run main.yaml --ref main and wait for package-openshell-sdk. Rerun CI, or update the PR against main if the approved package policy changed." + echo "::error::No retained SDK archive matches the approved identity. For a new SDK, wait for Candidate Upgrade Admission to publish its archive after approval, then rerun CI. For a trusted SDK, run gh workflow run main.yaml --ref main to restore its archive." exit 1 } run_id="$(jq -er '.workflow_run.id | select(type == "number" and . > 0 and . <= 9007199254740991)' <<<"$artifact")" artifact_id="$(jq -er '.id | select(type == "number" and . > 0 and . <= 9007199254740991)' <<<"$artifact")" - gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id" 2>/dev/null | jq -e --arg repo "$GITHUB_REPOSITORY" ' - (.path | split("@")[0]) == ".github/workflows/main.yaml" and .head_branch == "main" - and (.event == "push" or .event == "workflow_dispatch") + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id" 2>/dev/null | jq -e --arg repo "$GITHUB_REPOSITORY" --arg candidate "$candidate" --arg sha "$CANDIDATE_SHA" ' + (if $candidate == "true" then + (.path | split("@")[0]) == ".github/workflows/candidate-upgrade-admission.yaml" + and .status == "completed" and .conclusion == "success" + and ((.event == "pull_request_target" and .head_sha == $sha) or (.event == "issue_comment" and .head_branch == "main")) + else + (.path | split("@")[0]) == ".github/workflows/main.yaml" and .head_branch == "main" + and (.event == "push" or .event == "workflow_dispatch") + end) and .head_repository.full_name == $repo and .repository.full_name == $repo' >/dev/null printf 'artifact_id=%s\nrun_id=%s\nartifact_name=%s\n' "$artifact_id" "$run_id" "$artifact_name" >> "$GITHUB_OUTPUT" @@ -296,6 +324,7 @@ jobs: - name: Verify selected SDK archive against base policy and PR locks if: steps.locate.outputs.required == 'true' env: + GITHUB_TOKEN: ${{ github.token }} ARTIFACT_NAME: ${{ steps.locate.outputs.artifact_name }} NEMOCLAW_CI_NPM_PACKAGE_MODE: artifact NEMOCLAW_CI_TARGET_ROOT: ${{ github.workspace }} @@ -321,6 +350,7 @@ jobs: if: needs.changes.outputs.code == 'true' permissions: contents: read + pull-requests: read runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -348,6 +378,10 @@ jobs: scripts/audit-reviewed-npm-graph.mts scripts/check-dist-sourcemaps.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts @@ -398,6 +432,7 @@ jobs: permissions: actions: read contents: read + pull-requests: read runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -418,6 +453,10 @@ jobs: ci/reviewed-npm-audit.json scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts @@ -454,6 +493,7 @@ jobs: - name: Install dependencies run: bash .trusted-ci-actions/.github/actions/ci-install-dependencies.sh env: + GITHUB_TOKEN: ${{ github.token }} NPM_CONFIG_ALLOW_REMOTE: root - name: Run package-contract and type checks @@ -464,6 +504,7 @@ jobs: if: needs.changes.outputs.code == 'true' permissions: contents: read + pull-requests: read runs-on: ubuntu-latest timeout-minutes: 10 steps: @@ -484,6 +525,10 @@ jobs: ci/reviewed-npm-audit.json scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts @@ -564,6 +609,7 @@ jobs: permissions: actions: read contents: read + pull-requests: read runs-on: ubuntu-24.04 # Coverage startup plus the stable, duration-weighted roster can exceed # the former 15-minute cap before Vitest writes its shard artifacts. @@ -600,6 +646,10 @@ jobs: ci/reviewed-npm-audit.json scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts @@ -733,6 +783,10 @@ jobs: ci/reviewed-npm-audit.json scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts @@ -786,6 +840,10 @@ jobs: ci/reviewed-npm-audit.json scripts/audit-reviewed-npm-graph.mts scripts/checks/prepare-ci-npm-install.mts + scripts/lib/reviewed-ci-npm-install.mts + scripts/checks/candidate-openshell-sdk.mts + tools/e2e/candidate-upgrade-admission.mts + tools/e2e/base-image-publication.mts scripts/lib/openclaw-npm-remediation.mts scripts/lib/reviewed-npm-archive.mts scripts/lib/reviewed-npm-cache.mts diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index e2dd9ff4dc0..3518016a419 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -353,7 +353,7 @@ }, { "file": "test/automation/pull-requests/pr-workflow-contract.test.ts", - "test": "passes only the base-packaged SDK archive to pull request dependency jobs", + "test": "passes only an SDK archive admitted by the base-controlled verifier to dependency jobs", "category": "security" }, { diff --git a/scripts/checks/candidate-openshell-sdk.mts b/scripts/checks/candidate-openshell-sdk.mts new file mode 100644 index 00000000000..09f0ef8166c --- /dev/null +++ b/scripts/checks/candidate-openshell-sdk.mts @@ -0,0 +1,258 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { + closeSync, + constants, + fstatSync, + mkdtempSync, + mkdirSync, + openSync, + readFileSync, + writeFileSync, + rmSync, +} from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { isDeepStrictEqual } from "node:util"; +import { parseAuditConfig } from "../audit-reviewed-npm-graph.mts"; +import { resolvePathWithinRoot } from "../lib/repository-input-path.mts"; +import { stageReviewedArchiveWithNpm, type NpmCacheStager } from "../lib/reviewed-npm-cache.mts"; +import { + prepareCiNpmInstallWithReviewedConfig, + requiresCandidateSdkAdmission, +} from "../lib/reviewed-ci-npm-install.mts"; +import { + reviewedNpmDependencyLocations, + verifyReviewedNpmLockPackages, +} from "../lib/reviewed-npm-archive.mts"; +import { + readApprovedCandidateUpgrade, + readCandidateUpgradeSource, + type CandidateUpgradeIdentity, + type UpgradeRequest, +} from "../../tools/e2e/candidate-upgrade-admission.mts"; + +const SDK = "@nvidia/openshell-sdk"; +const CONFIG = "ci/reviewed-npm-audit.json"; +const MANIFESTS = ["package.json", "nemoclaw/package.json"] as const; +const LOCKS = ["package-lock.json", "nemoclaw/package-lock.json"] as const; +type Config = ReturnType; +type Sdk = Config["sourceRegistryPackage"]; + +function sdkIdentity(value: unknown): Sdk { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("Candidate SDK identity must be an object"); + } + const record = value as Record; + const version = + typeof record.packageSpec === "string" + ? /^@nvidia\/openshell-sdk@((?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*)\.(?:0|[1-9][0-9]*))$/u.exec( + record.packageSpec, + )?.[1] + : undefined; + if ( + !version || + record.artifactName !== `nvidia-openshell-sdk-${version}.tgz` || + typeof record.integrity !== "string" || + !/^sha512-[A-Za-z0-9+/]{86}==$/u.test(record.integrity) || + `sha512-${Buffer.from(record.integrity.slice(7), "base64").toString("base64")}` !== + record.integrity || + typeof record.tarballUrl !== "string" || + !record.tarballUrl.startsWith(`https://npm.pkg.github.com/download/${SDK}/${version}/`) || + !/^[a-f0-9]{40}$/u.test(record.tarballUrl.split("/").at(-1) ?? "") || + record.tarballUrl !== + `https://npm.pkg.github.com/download/${SDK}/${version}/${record.tarballUrl.split("/").at(-1)}` + ) { + throw new Error("Candidate SDK requires an immutable official archive identity"); + } + return { + artifactName: record.artifactName as string, + packageSpec: record.packageSpec as string, + integrity: record.integrity, + tarballUrl: record.tarballUrl, + label: `OpenShell TypeScript SDK ${version}`, + }; +} + +function manifestPin(source: string): string | undefined { + const manifest = JSON.parse(source); + const dependency = manifest.dependencies?.[SDK]; + const optional = manifest.optionalDependencies?.[SDK]; + if (dependency !== undefined && optional !== undefined && dependency !== optional) { + throw new Error("Candidate SDK dependency declarations disagree"); + } + const pin: unknown = optional ?? dependency; + if ( + pin !== undefined && + (typeof pin !== "string" || !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/u.test(pin)) + ) { + throw new Error("Candidate SDK manifests must use exact version pins"); + } + return pin as string | undefined; +} + +function selectPolicy(sources: Readonly>, trusted: Config): Config { + const candidate = JSON.parse(sources[CONFIG]!); + const identities = [candidate.sourceRegistryPackage, candidate.sourceRegistryPackageReplacement] + .filter((value) => value !== undefined) + .map(sdkIdentity); + const pins = MANIFESTS.map((path) => manifestPin(sources[path]!)); + const versions = new Set(pins.filter((pin) => pin !== undefined)); + if (versions.size !== 1) throw new Error("Candidate SDK manifests must select one identity"); + const version = [...versions][0]; + const selected = identities.filter((value) => value.packageSpec === `${SDK}@${version}`); + if (selected.length !== 1) throw new Error("Candidate SDK identity is missing or ambiguous"); + const reviewed = selected[0]!; + for (const prior of [trusted.sourceRegistryPackage, trusted.sourceRegistryPackageReplacement]) { + if ( + prior?.packageSpec === reviewed.packageSpec && + !isDeepStrictEqual(sdkIdentity(prior), reviewed) + ) { + throw new Error("Candidate SDK cannot replace an existing trusted artifact identity"); + } + } + // Candidate data selects the SDK only. npm, registry, audit and exception policy stay trusted. + const { sourceRegistryPackageReplacement: _replacement, ...policy } = trusted; + const config = { ...policy, sourceRegistryPackage: reviewed }; + const temporary = mkdtempSync(join(tmpdir(), "nemoclaw-approved-sdk-locks-")); + try { + mkdirSync(join(temporary, "nemoclaw")); + for (const [index, path] of LOCKS.entries()) { + const lock = JSON.parse(sources[path]!); + const lockedPin = manifestPin(JSON.stringify(lock.packages?.[""] ?? {})); + if (lockedPin !== pins[index]) throw new Error("Candidate SDK manifest and lock disagree"); + if (pins[index] !== undefined) { + const entry = lock.packages?.[`node_modules/${SDK}`]; + if ( + entry?.version !== version || + entry?.resolved !== reviewed.tarballUrl || + entry?.integrity !== reviewed.integrity + ) { + throw new Error("Candidate SDK lock must resolve the declared top-level identity"); + } + reviewedNpmDependencyLocations(lock.packages, SDK); + } + const lockfilePath = join(temporary, path); + writeFileSync(lockfilePath, sources[path]!, { flag: "wx", mode: 0o600 }); + const packages = verifyReviewedNpmLockPackages({ + lockfilePath, + allowedNestedShrinkwrapPackages: trusted.sourceNestedShrinkwrapPackages, + registryOrigin: trusted.registryOrigin, + reviewedPackagesWithoutIntegrity: trusted.sourceRegistryPackagesWithoutIntegrity, + reviewedRegistryPackages: [{ ...reviewed, expectedIntegrity: reviewed.integrity }], + }); + if ((pins[index] !== undefined) !== packages.includes(reviewed.packageSpec)) { + throw new Error("Candidate SDK lock does not contain its declared dependency"); + } + } + return config; + } finally { + rmSync(temporary, { recursive: true, force: true }); + } +} + +/** Acquire candidate SDK inputs under live admission, then apply the trusted package policy. */ +export async function readApprovedOpenShellSdkConfig( + identity: CandidateUpgradeIdentity, + request: UpgradeRequest, + trustedConfigSource: string, +) { + const trusted = parseAuditConfig(trustedConfigSource); + const admission = await readApprovedCandidateUpgrade( + identity, + [CONFIG, ...MANIFESTS, ...LOCKS], + request, + ); + return { + configSource: JSON.stringify(selectPolicy(admission.sources, trusted)), + sources: admission.sources, + reviewer: admission.reviewer, + commentId: admission.commentId, + }; +} + +function verifyCheckoutSources(targetRoot: string, sources: Readonly>) { + for (const path of [...MANIFESTS, ...LOCKS]) { + const file = resolvePathWithinRoot(targetRoot, path, "Candidate SDK input"); + const descriptor = openSync( + file, + constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK, + ); + try { + const stat = fstatSync(descriptor); + if (!stat.isFile() || stat.size > 1024 * 1024) { + throw new Error("Candidate SDK input must be a bounded regular file"); + } + if (readFileSync(descriptor, "utf8") !== sources[path]) { + throw new Error(`Candidate SDK checkout differs from admitted commit: ${path}`); + } + } finally { + closeSync(descriptor); + } + } +} + +function artifactDecision( + identity: CandidateUpgradeIdentity, + admitted: Awaited>, +) { + return { + required: true, + candidate: true, + artifactName: parseAuditConfig(admitted.configSource).sourceRegistryPackage.artifactName, + bundleName: `candidate-openshell-sdk-${identity.prNumber}-${identity.candidateSha}-${identity.baseSha}-${admitted.commentId}`, + } as const; +} + +export async function inspectApprovedCandidateOpenShellSdk( + targetRoot: string, + identity: CandidateUpgradeIdentity, + request: UpgradeRequest, + trustedSource: string, +) { + const admitted = await readApprovedOpenShellSdkConfig(identity, request, trustedSource); + verifyCheckoutSources(targetRoot, admitted.sources); + return artifactDecision(identity, admitted); +} + +/** The producer needs no new archive when the locks use an existing trusted SDK version. */ +export async function readCandidateSdkPackageDecision( + identity: CandidateUpgradeIdentity, + request: UpgradeRequest, + trustedSource: string, +) { + const locks = await Promise.all( + LOCKS.map((path) => readCandidateUpgradeSource(request, identity.candidateSha, path)), + ); + if (!requiresCandidateSdkAdmission(locks, trustedSource)) return { required: false } as const; + return artifactDecision( + identity, + await readApprovedOpenShellSdkConfig(identity, request, trustedSource), + ); +} + +/** Verify admitted sources and archive bytes before releasing them to the npm cache. */ +export async function prepareApprovedCandidateOpenShellSdk( + preparation: Parameters[0], + input: CandidateUpgradeIdentity, + request: UpgradeRequest, + trustedConfigSource: string, + stage: NpmCacheStager = stageReviewedArchiveWithNpm, +): Promise { + if (preparation.mode !== "artifact") + throw new Error("Candidate SDK installation requires artifact mode"); + const identity = Object.freeze({ ...input }); + const before = await readApprovedOpenShellSdkConfig(identity, request, trustedConfigSource); + verifyCheckoutSources(preparation.targetRoot, before.sources); + const verified: Parameters[0][] = []; + await prepareCiNpmInstallWithReviewedConfig(preparation, before.configSource, (archive) => { + verified.push(archive); + }); + const after = await readApprovedOpenShellSdkConfig(identity, request, trustedConfigSource); + if (!isDeepStrictEqual(before, after)) + throw new Error("Candidate SDK admission changed during verification"); + verifyCheckoutSources(preparation.targetRoot, after.sources); + // Staging receives only the bytes already checked, not a path that could be replaced. + for (const archive of verified) stage(archive); +} diff --git a/scripts/checks/package-openshell-sdk-for-pr.mts b/scripts/checks/package-openshell-sdk-for-pr.mts index 69e24e37a67..55ffaec009a 100755 --- a/scripts/checks/package-openshell-sdk-for-pr.mts +++ b/scripts/checks/package-openshell-sdk-for-pr.mts @@ -2,12 +2,20 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { copyFileSync, mkdirSync, readFileSync, rmSync } from "node:fs"; -import { dirname, join, resolve } from "node:path"; +import { copyFileSync, lstatSync, mkdirSync, readFileSync, rmSync } from "node:fs"; +import { dirname, isAbsolute, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; import { parseAuditConfig } from "../audit-reviewed-npm-graph.mts"; -import { packReviewedNpmArchive, removeReviewedNpmArchive } from "../lib/reviewed-npm-archive.mts"; +import { + packReviewedNpmArchive, + readReviewedNpmArchiveFile, + removeReviewedNpmArchive, +} from "../lib/reviewed-npm-archive.mts"; +import type { + CandidateUpgradeIdentity, + UpgradeRequest, +} from "../../tools/e2e/candidate-upgrade-admission.mts"; const TRUSTED_REPOSITORY_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); @@ -18,6 +26,7 @@ export function packageReviewedOpenShellSdk( pack?: typeof packReviewedNpmArchive; readAuditConfig?: () => string; remove?: typeof removeReviewedNpmArchive; + env?: NodeJS.ProcessEnv; }> = {}, ): string { if (!outputDirectory) { @@ -43,7 +52,7 @@ export function packageReviewedOpenShellSdk( mkdirSync(output, { recursive: true }); for (const reviewed of reviewedPackages) { const archive = pack({ - env: process.env, + env: dependencies.env ?? process.env, expectedIntegrity: reviewed.integrity, label: reviewed.label, packageSpec: reviewed.packageSpec, @@ -58,6 +67,82 @@ export function packageReviewedOpenShellSdk( } } +/** Package admitted SDK bytes with trusted code; revocation prevents publication of this output. */ +export async function packageApprovedCandidateOpenShellSdk( + outputDirectory: string, + input: CandidateUpgradeIdentity, + request: UpgradeRequest, + dependencies: Parameters[2] = {}, +): Promise { + const identity = Object.freeze({ ...input }); + if (!isAbsolute(outputDirectory) || lstatSync(outputDirectory, { throwIfNoEntry: false })) { + throw new Error("Candidate SDK output must be a new absolute directory"); + } + // The ordinary main producer uses a sparse checkout without candidate admission code. + const { readApprovedOpenShellSdkConfig } = await import("./candidate-openshell-sdk.mts"); + const trustedSource = + dependencies.readAuditConfig?.() ?? + readFileSync(join(TRUSTED_REPOSITORY_ROOT, "ci/reviewed-npm-audit.json"), "utf8"); + const before = await readApprovedOpenShellSdkConfig(identity, request, trustedSource); + const { GH_TOKEN: _gh, GITHUB_TOKEN: _github, ...environment } = dependencies.env ?? process.env; + try { + const artifact = packageReviewedOpenShellSdk(outputDirectory, "exclude", { + ...dependencies, + env: { ...environment, NPM_CONFIG_IGNORE_SCRIPTS: "true" }, + readAuditConfig: () => before.configSource, + }); + const sdk = parseAuditConfig(before.configSource).sourceRegistryPackage; + readReviewedNpmArchiveFile({ + archivePath: artifact, + expectedIntegrity: sdk.integrity, + label: sdk.label, + maximumBytes: 32 * 1024 * 1024, + }); + const after = await readApprovedOpenShellSdkConfig(identity, request, trustedSource); + if ( + before.configSource !== after.configSource || + JSON.stringify(before.sources) !== JSON.stringify(after.sources) || + before.commentId !== after.commentId || + before.reviewer !== after.reviewer + ) { + throw new Error("Candidate SDK admission changed during packaging"); + } + return artifact; + } catch (error) { + rmSync(outputDirectory, { recursive: true, force: true }); + throw error; + } +} + +export async function packageCandidateOpenShellSdkIfRequired( + outputDirectory: string, + identity: CandidateUpgradeIdentity, + request: UpgradeRequest, + dependencies: Parameters[2] = {}, +) { + const { readCandidateSdkPackageDecision } = await import("./candidate-openshell-sdk.mts"); + const source = + dependencies.readAuditConfig?.() ?? + readFileSync(join(TRUSTED_REPOSITORY_ROOT, "ci/reviewed-npm-audit.json"), "utf8"); + const before = await readCandidateSdkPackageDecision(identity, request, source); + if (!before.required) return before; + const artifact = await packageApprovedCandidateOpenShellSdk( + outputDirectory, + identity, + request, + dependencies, + ); + try { + const after = await readCandidateSdkPackageDecision(identity, request, source); + if (JSON.stringify(before) !== JSON.stringify(after)) + throw new Error("Candidate SDK publication identity changed"); + return { ...before, artifact }; + } catch (error) { + rmSync(outputDirectory, { recursive: true, force: true }); + throw error; + } +} + if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) { const outputDirectory = process.env.NEMOCLAW_OPEN_SHELL_SDK_OUTPUT_DIRECTORY; if (!outputDirectory) { @@ -80,13 +165,35 @@ if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1] process.exit(1); } try { + const candidateMode = process.env.NEMOCLAW_OPEN_SHELL_SDK_CANDIDATE; + if (candidateMode !== undefined && candidateMode !== "1") { + throw new Error("NEMOCLAW_OPEN_SHELL_SDK_CANDIDATE must be 1 when set"); + } + if (candidateMode === "1" && (includeReplacementValue || includeAvailableReplacementValue)) { + throw new Error("Candidate SDK packaging selects only the admitted lock identity"); + } const replacementMode = includeReplacementValue === "1" ? "require" : includeAvailableReplacementValue === "1" ? "if-present" : "exclude"; - process.stdout.write(`${packageReviewedOpenShellSdk(outputDirectory, replacementMode)}\n`); + const artifact = + candidateMode === "1" + ? await packageApprovedCandidateOpenShellSdk( + outputDirectory, + { + prNumber: Number(process.env.UPGRADE_PR_NUMBER), + candidateSha: process.env.CANDIDATE_SHA ?? "", + baseSha: process.env.UPGRADE_BASE_SHA ?? "", + }, + async (path) => { + const { githubRequest } = await import("../../tools/e2e/base-image-publication.mts"); + return githubRequest(path, process.env.GITHUB_TOKEN ?? ""); + }, + ) + : packageReviewedOpenShellSdk(outputDirectory, replacementMode); + process.stdout.write(`${artifact}\n`); } catch (error) { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); diff --git a/scripts/checks/prepare-ci-npm-install.mts b/scripts/checks/prepare-ci-npm-install.mts index 59f206c313f..42196e497be 100755 --- a/scripts/checks/prepare-ci-npm-install.mts +++ b/scripts/checks/prepare-ci-npm-install.mts @@ -2,245 +2,27 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs"; -import { dirname, isAbsolute, join, resolve } from "node:path"; +import { readFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; import { fileURLToPath, pathToFileURL } from "node:url"; - -import { parseAuditConfig } from "../audit-reviewed-npm-graph.mts"; import { - readReviewedNpmArchiveFile, - verifyReviewedNpmLockPackages, -} from "../lib/reviewed-npm-archive.mts"; - -import { stageReviewedArchiveWithNpm, type NpmCacheStager } from "../lib/reviewed-npm-cache.mts"; + inspectCiNpmInstall, + prepareCiNpmInstall, + requiresCandidateSdkAdmission, + type PreparationRequest, +} from "../lib/reviewed-ci-npm-install.mts"; + +export { + inspectCiNpmInstall, + prepareCiNpmInstall, + prepareCiNpmInstallWithReviewedConfig, + requiresCandidateSdkAdmission, + seedReviewedSourceRegistryArtifact, + type ReviewedSourceRegistryArtifactRequest, + type ReviewedSourceRegistryPackage, +} from "../lib/reviewed-ci-npm-install.mts"; const TRUSTED_REPOSITORY_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); -const MAXIMUM_ARCHIVE_BYTES = 32 * 1024 * 1024; - -type PreparationRequest = Readonly<{ - artifactDirectory?: string; - cacheDirectory: string; - mode: "artifact" | "registry"; - targetRoot: string; -}>; - -type AuditConfig = ReturnType; - -export type ReviewedSourceRegistryPackage = Readonly<{ - artifactName: string; - integrity: string; - label: string; - packageSpec: string; - tarballUrl: string; -}>; - -export type ReviewedSourceRegistryArtifactRequest = Readonly<{ - allowedNestedShrinkwrapPackages: readonly string[]; - artifactDirectory: string; - cacheDirectory: string; - lockfilePath: string; - otherReviewedPackages?: readonly ReviewedSourceRegistryPackage[]; - reviewed: ReviewedSourceRegistryPackage; - reviewedPackagesWithoutIntegrity: readonly Readonly<{ - label: string; - packageSpec: string; - tarballUrl: string; - }>[]; - registryOrigin: string; -}>; - -export async function seedReviewedSourceRegistryArtifact( - request: ReviewedSourceRegistryArtifactRequest, - stage: NpmCacheStager = stageReviewedArchiveWithNpm, -): Promise { - if (!isAbsolute(request.artifactDirectory)) { - throw new Error("reviewed OpenShell SDK artifact directory must be absolute"); - } - const artifactDirectory = resolve(request.artifactDirectory); - if (!existsSync(artifactDirectory)) { - throw new Error("reviewed OpenShell SDK artifact is required"); - } - const directoryEntry = lstatSync(artifactDirectory); - if (!directoryEntry.isDirectory() || directoryEntry.isSymbolicLink()) { - throw new Error("reviewed OpenShell SDK artifact path must be a non-symlink directory"); - } - const entries = readdirSync(artifactDirectory); - const otherReviewedPackages = request.otherReviewedPackages ?? []; - const allowedNames = new Set([ - request.reviewed.artifactName, - ...otherReviewedPackages.map(({ artifactName }) => artifactName), - ]); - if ( - !entries.includes(request.reviewed.artifactName) || - entries.some((entry) => !allowedNames.has(entry)) - ) { - throw new Error("reviewed OpenShell SDK artifact directory has unexpected contents"); - } - const archivePath = resolve(join(artifactDirectory, request.reviewed.artifactName)); - const reviewedRegistryPackage = { - expectedIntegrity: request.reviewed.integrity, - label: request.reviewed.label, - packageSpec: request.reviewed.packageSpec, - tarballUrl: request.reviewed.tarballUrl, - }; - const lockedPackages = verifyReviewedNpmLockPackages({ - allowedNestedShrinkwrapPackages: request.allowedNestedShrinkwrapPackages, - allowNestedShrinkwrap: false, - lockfilePath: request.lockfilePath, - registryOrigin: request.registryOrigin, - reviewedPackagesWithoutIntegrity: request.reviewedPackagesWithoutIntegrity, - reviewedRegistryPackages: [reviewedRegistryPackage], - }); - if (!lockedPackages.includes(request.reviewed.packageSpec)) { - throw new Error("reviewed OpenShell SDK artifact is not used by the selected lockfile"); - } - const cacheDirectory = resolve(request.cacheDirectory); - if ( - !isAbsolute(request.cacheDirectory) || - !existsSync(cacheDirectory) || - !lstatSync(cacheDirectory).isDirectory() - ) { - throw new Error("reviewed OpenShell SDK cache must be an existing absolute directory"); - } - const archive = readReviewedNpmArchiveFile({ - archivePath, - expectedIntegrity: request.reviewed.integrity, - label: request.reviewed.label, - maximumBytes: MAXIMUM_ARCHIVE_BYTES, - }); - // Verify every supplied reviewed archive before staging only the lock-selected SDK. - for (const other of otherReviewedPackages) { - if (!entries.includes(other.artifactName)) continue; - readReviewedNpmArchiveFile({ - archivePath: resolve(join(artifactDirectory, other.artifactName)), - expectedIntegrity: other.integrity, - label: other.label, - maximumBytes: MAXIMUM_ARCHIVE_BYTES, - }); - } - stage({ archive, artifactName: request.reviewed.artifactName, cacheDirectory }); -} - -function readTrustedAuditConfig(): AuditConfig { - return parseAuditConfig( - readFileSync(join(TRUSTED_REPOSITORY_ROOT, "ci/reviewed-npm-audit.json"), "utf8"), - ); -} - -function reviewedSourceRegistryPackages( - config: AuditConfig, -): readonly ReviewedSourceRegistryPackage[] { - return config.sourceRegistryPackageReplacement - ? [config.sourceRegistryPackage, config.sourceRegistryPackageReplacement] - : [config.sourceRegistryPackage]; -} - -function inspectReviewedLocks(targetRoot: string, config: AuditConfig) { - const reviewedPackages = reviewedSourceRegistryPackages(config); - const reviewedRegistryPackages = reviewedPackages.map((reviewed) => ({ - expectedIntegrity: reviewed.integrity, - label: reviewed.label, - packageSpec: reviewed.packageSpec, - tarballUrl: reviewed.tarballUrl, - })); - const lockfiles = ["package-lock.json", "nemoclaw/package-lock.json"].map((relativePath) => { - const lockfilePath = join(targetRoot, relativePath); - const packages = verifyReviewedNpmLockPackages({ - allowedNestedShrinkwrapPackages: config.sourceNestedShrinkwrapPackages, - lockfilePath, - registryOrigin: config.registryOrigin, - reviewedPackagesWithoutIntegrity: config.sourceRegistryPackagesWithoutIntegrity, - reviewedRegistryPackages, - }); - return { lockfilePath, packages }; - }); - const lockedReviewedSpecs = new Set( - lockfiles.flatMap(({ packages }) => - reviewedPackages - .map(({ packageSpec }) => packageSpec) - .filter((packageSpec) => packages.includes(packageSpec)), - ), - ); - if (lockedReviewedSpecs.size > 1) { - throw new Error("reviewed npm locks use conflicting OpenShell SDK identities"); - } - const selectedSpec = [...lockedReviewedSpecs][0]; - const reviewed = - reviewedPackages.find(({ packageSpec }) => packageSpec === selectedSpec) ?? - config.sourceRegistryPackage; - return { - config, - reviewed, - reviewedLockfilePath: lockfiles.find(({ packages }) => packages.includes(reviewed.packageSpec)) - ?.lockfilePath, - }; -} - -export function inspectCiNpmInstall(targetRoot: string) { - const inspected = inspectReviewedLocks(resolve(targetRoot), readTrustedAuditConfig()); - return { - artifactName: inspected.reviewed.artifactName, - required: inspected.reviewedLockfilePath !== undefined, - } as const; -} - -async function prepareCiNpmInstallWithConfig( - request: PreparationRequest, - config: AuditConfig, - stage?: NpmCacheStager, -): Promise { - const targetRoot = resolve(request.targetRoot); - const cacheDirectory = resolve(request.cacheDirectory); - const { reviewed, reviewedLockfilePath } = inspectReviewedLocks(targetRoot, config); - const sdkIsLocked = reviewedLockfilePath !== undefined; - - if (request.mode === "registry") return; - if (!request.artifactDirectory) { - if (sdkIsLocked) throw new Error("reviewed OpenShell SDK artifact is required"); - return; - } - if (!isAbsolute(request.artifactDirectory)) { - throw new Error("reviewed OpenShell SDK artifact directory must be absolute"); - } - const artifactDirectory = resolve(request.artifactDirectory); - if (!existsSync(artifactDirectory)) { - if (sdkIsLocked) throw new Error("reviewed OpenShell SDK artifact is required"); - return; - } - if (!reviewedLockfilePath) { - throw new Error("reviewed OpenShell SDK artifact is not used by either lockfile"); - } - await seedReviewedSourceRegistryArtifact( - { - allowedNestedShrinkwrapPackages: config.sourceNestedShrinkwrapPackages, - artifactDirectory, - cacheDirectory, - lockfilePath: reviewedLockfilePath, - otherReviewedPackages: reviewedSourceRegistryPackages(config).filter( - ({ packageSpec }) => packageSpec !== reviewed.packageSpec, - ), - registryOrigin: config.registryOrigin, - reviewed, - reviewedPackagesWithoutIntegrity: config.sourceRegistryPackagesWithoutIntegrity, - }, - stage, - ); -} - -export async function prepareCiNpmInstallWithReviewedConfig( - request: PreparationRequest, - reviewedConfigSource: string, - stage?: NpmCacheStager, -): Promise { - return prepareCiNpmInstallWithConfig(request, parseAuditConfig(reviewedConfigSource), stage); -} - -export async function prepareCiNpmInstall( - request: PreparationRequest, - stage?: NpmCacheStager, -): Promise { - return prepareCiNpmInstallWithConfig(request, readTrustedAuditConfig(), stage); -} function requestFromEnvironment(): PreparationRequest { const mode = process.env.NEMOCLAW_CI_NPM_PACKAGE_MODE; @@ -258,15 +40,63 @@ function requestFromEnvironment(): PreparationRequest { } if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) { - const mode = process.env.NEMOCLAW_CI_NPM_PACKAGE_MODE; - const targetRoot = process.env.NEMOCLAW_CI_TARGET_ROOT; - const task = - mode === "inspect" && targetRoot - ? Promise.resolve(inspectCiNpmInstall(targetRoot)).then((result) => - process.stdout.write(`${JSON.stringify(result)}\n`), - ) - : prepareCiNpmInstall(requestFromEnvironment()); - task.catch((error) => { + const main = async () => { + const candidate = process.env.NEMOCLAW_OPEN_SHELL_SDK_CANDIDATE; + if (candidate !== undefined && candidate !== "1") { + throw new Error("NEMOCLAW_OPEN_SHELL_SDK_CANDIDATE must be 1 when set"); + } + const mode = process.env.NEMOCLAW_CI_NPM_PACKAGE_MODE; + const targetRoot = process.env.NEMOCLAW_CI_TARGET_ROOT; + const trustedSource = readFileSync( + join(TRUSTED_REPOSITORY_ROOT, "ci/reviewed-npm-audit.json"), + "utf8", + ); + const candidateRequired = + candidate === "1" || + (process.env.GITHUB_EVENT_NAME === "pull_request" && + targetRoot !== undefined && + requiresCandidateSdkAdmission( + ["package-lock.json", "nemoclaw/package-lock.json"].map((path) => + readFileSync(join(targetRoot, path), "utf8"), + ), + trustedSource, + )); + if (candidateRequired) { + if (mode !== "artifact" && mode !== "inspect") + throw new Error("Candidate SDK installation requires artifact mode"); + const token = process.env.GITHUB_TOKEN ?? ""; + delete process.env.GITHUB_TOKEN; + delete process.env.GH_TOKEN; + const { prepareApprovedCandidateOpenShellSdk, inspectApprovedCandidateOpenShellSdk } = + await import("./candidate-openshell-sdk.mts"); + const { githubRequest } = await import("../../tools/e2e/base-image-publication.mts"); + const identity = { + prNumber: Number(process.env.UPGRADE_PR_NUMBER), + candidateSha: process.env.CANDIDATE_SHA ?? "", + baseSha: process.env.UPGRADE_BASE_SHA ?? "", + }; + const request = (path: string) => githubRequest(path, token); + if (mode === "inspect" && targetRoot) { + process.stdout.write( + `${JSON.stringify(await inspectApprovedCandidateOpenShellSdk(targetRoot, identity, request, trustedSource))}\n`, + ); + } else { + await prepareApprovedCandidateOpenShellSdk( + requestFromEnvironment(), + identity, + request, + trustedSource, + ); + } + return; + } + if (mode === "inspect" && targetRoot) { + process.stdout.write(`${JSON.stringify(inspectCiNpmInstall(targetRoot))}\n`); + } else { + await prepareCiNpmInstall(requestFromEnvironment()); + } + }; + main().catch((error) => { console.error(error instanceof Error ? error.message : String(error)); process.exit(1); }); diff --git a/scripts/lib/reviewed-ci-npm-install.mts b/scripts/lib/reviewed-ci-npm-install.mts new file mode 100644 index 00000000000..2088a00e3af --- /dev/null +++ b/scripts/lib/reviewed-ci-npm-install.mts @@ -0,0 +1,264 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { existsSync, lstatSync, readFileSync, readdirSync } from "node:fs"; +import { dirname, isAbsolute, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; + +import { parseAuditConfig } from "../audit-reviewed-npm-graph.mts"; +import { + readReviewedNpmArchiveFile, + verifyReviewedNpmLockPackages, +} from "./reviewed-npm-archive.mts"; + +import { stageReviewedArchiveWithNpm, type NpmCacheStager } from "./reviewed-npm-cache.mts"; + +const TRUSTED_REPOSITORY_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), "../.."); +const MAXIMUM_ARCHIVE_BYTES = 32 * 1024 * 1024; + +export type PreparationRequest = Readonly<{ + artifactDirectory?: string; + cacheDirectory: string; + mode: "artifact" | "registry"; + targetRoot: string; +}>; + +type AuditConfig = ReturnType; + +export type ReviewedSourceRegistryPackage = Readonly<{ + artifactName: string; + integrity: string; + label: string; + packageSpec: string; + tarballUrl: string; +}>; + +export type ReviewedSourceRegistryArtifactRequest = Readonly<{ + allowedNestedShrinkwrapPackages: readonly string[]; + artifactDirectory: string; + cacheDirectory: string; + lockfilePath: string; + otherReviewedPackages?: readonly ReviewedSourceRegistryPackage[]; + reviewed: ReviewedSourceRegistryPackage; + reviewedPackagesWithoutIntegrity: readonly Readonly<{ + label: string; + packageSpec: string; + tarballUrl: string; + }>[]; + registryOrigin: string; +}>; + +export async function seedReviewedSourceRegistryArtifact( + request: ReviewedSourceRegistryArtifactRequest, + stage: NpmCacheStager = stageReviewedArchiveWithNpm, +): Promise { + if (!isAbsolute(request.artifactDirectory)) { + throw new Error("reviewed OpenShell SDK artifact directory must be absolute"); + } + const artifactDirectory = resolve(request.artifactDirectory); + if (!existsSync(artifactDirectory)) { + throw new Error("reviewed OpenShell SDK artifact is required"); + } + const directoryEntry = lstatSync(artifactDirectory); + if (!directoryEntry.isDirectory() || directoryEntry.isSymbolicLink()) { + throw new Error("reviewed OpenShell SDK artifact path must be a non-symlink directory"); + } + const entries = readdirSync(artifactDirectory); + const otherReviewedPackages = request.otherReviewedPackages ?? []; + const allowedNames = new Set([ + request.reviewed.artifactName, + ...otherReviewedPackages.map(({ artifactName }) => artifactName), + ]); + if ( + !entries.includes(request.reviewed.artifactName) || + entries.some((entry) => !allowedNames.has(entry)) + ) { + throw new Error("reviewed OpenShell SDK artifact directory has unexpected contents"); + } + const archivePath = resolve(join(artifactDirectory, request.reviewed.artifactName)); + const reviewedRegistryPackage = { + expectedIntegrity: request.reviewed.integrity, + label: request.reviewed.label, + packageSpec: request.reviewed.packageSpec, + tarballUrl: request.reviewed.tarballUrl, + }; + const lockedPackages = verifyReviewedNpmLockPackages({ + allowedNestedShrinkwrapPackages: request.allowedNestedShrinkwrapPackages, + allowNestedShrinkwrap: false, + lockfilePath: request.lockfilePath, + registryOrigin: request.registryOrigin, + reviewedPackagesWithoutIntegrity: request.reviewedPackagesWithoutIntegrity, + reviewedRegistryPackages: [reviewedRegistryPackage], + }); + if (!lockedPackages.includes(request.reviewed.packageSpec)) { + throw new Error("reviewed OpenShell SDK artifact is not used by the selected lockfile"); + } + const cacheDirectory = resolve(request.cacheDirectory); + if ( + !isAbsolute(request.cacheDirectory) || + !existsSync(cacheDirectory) || + !lstatSync(cacheDirectory).isDirectory() + ) { + throw new Error("reviewed OpenShell SDK cache must be an existing absolute directory"); + } + const archive = readReviewedNpmArchiveFile({ + archivePath, + expectedIntegrity: request.reviewed.integrity, + label: request.reviewed.label, + maximumBytes: MAXIMUM_ARCHIVE_BYTES, + }); + // Verify every supplied reviewed archive before staging only the lock-selected SDK. + for (const other of otherReviewedPackages) { + if (!entries.includes(other.artifactName)) continue; + readReviewedNpmArchiveFile({ + archivePath: resolve(join(artifactDirectory, other.artifactName)), + expectedIntegrity: other.integrity, + label: other.label, + maximumBytes: MAXIMUM_ARCHIVE_BYTES, + }); + } + stage({ archive, artifactName: request.reviewed.artifactName, cacheDirectory }); +} + +function readTrustedAuditConfig(): AuditConfig { + return parseAuditConfig( + readFileSync(join(TRUSTED_REPOSITORY_ROOT, "ci/reviewed-npm-audit.json"), "utf8"), + ); +} + +function reviewedSourceRegistryPackages( + config: AuditConfig, +): readonly ReviewedSourceRegistryPackage[] { + return config.sourceRegistryPackageReplacement + ? [config.sourceRegistryPackage, config.sourceRegistryPackageReplacement] + : [config.sourceRegistryPackage]; +} + +function inspectReviewedLocks(targetRoot: string, config: AuditConfig) { + const reviewedPackages = reviewedSourceRegistryPackages(config); + const reviewedRegistryPackages = reviewedPackages.map((reviewed) => ({ + expectedIntegrity: reviewed.integrity, + label: reviewed.label, + packageSpec: reviewed.packageSpec, + tarballUrl: reviewed.tarballUrl, + })); + const lockfiles = ["package-lock.json", "nemoclaw/package-lock.json"].map((relativePath) => { + const lockfilePath = join(targetRoot, relativePath); + const packages = verifyReviewedNpmLockPackages({ + allowedNestedShrinkwrapPackages: config.sourceNestedShrinkwrapPackages, + lockfilePath, + registryOrigin: config.registryOrigin, + reviewedPackagesWithoutIntegrity: config.sourceRegistryPackagesWithoutIntegrity, + reviewedRegistryPackages, + }); + return { lockfilePath, packages }; + }); + const lockedReviewedSpecs = new Set( + lockfiles.flatMap(({ packages }) => + reviewedPackages + .map(({ packageSpec }) => packageSpec) + .filter((packageSpec) => packages.includes(packageSpec)), + ), + ); + if (lockedReviewedSpecs.size > 1) { + throw new Error("reviewed npm locks use conflicting OpenShell SDK identities"); + } + const selectedSpec = [...lockedReviewedSpecs][0]; + const reviewed = + reviewedPackages.find(({ packageSpec }) => packageSpec === selectedSpec) ?? + config.sourceRegistryPackage; + return { + config, + reviewed, + reviewedLockfilePath: lockfiles.find(({ packages }) => packages.includes(reviewed.packageSpec)) + ?.lockfilePath, + }; +} + +export function inspectCiNpmInstall(targetRoot: string) { + const inspected = inspectReviewedLocks(resolve(targetRoot), readTrustedAuditConfig()); + return { + artifactName: inspected.reviewed.artifactName, + required: inspected.reviewedLockfilePath !== undefined, + } as const; +} + +/** Only a new SDK version can enter admission; other lock failures remain ordinary denials. */ +export function requiresCandidateSdkAdmission( + lockSources: readonly string[], + configSource: string, +): boolean { + const config = parseAuditConfig(configSource); + const known = new Set( + reviewedSourceRegistryPackages(config).map(({ packageSpec }) => packageSpec), + ); + return lockSources.some((source) => { + const entry = JSON.parse(source).packages?.["node_modules/@nvidia/openshell-sdk"]; + if (entry === undefined) return false; + if ( + typeof entry?.version !== "string" || + !/^(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)\.(0|[1-9][0-9]*)$/u.test(entry.version) + ) { + throw new Error("Candidate SDK lock must use an exact version"); + } + return !known.has(`@nvidia/openshell-sdk@${entry.version}`); + }); +} + +async function prepareCiNpmInstallWithConfig( + request: PreparationRequest, + config: AuditConfig, + stage?: NpmCacheStager, +): Promise { + const targetRoot = resolve(request.targetRoot); + const cacheDirectory = resolve(request.cacheDirectory); + const { reviewed, reviewedLockfilePath } = inspectReviewedLocks(targetRoot, config); + const sdkIsLocked = reviewedLockfilePath !== undefined; + + if (request.mode === "registry") return; + if (!request.artifactDirectory) { + if (sdkIsLocked) throw new Error("reviewed OpenShell SDK artifact is required"); + return; + } + if (!isAbsolute(request.artifactDirectory)) { + throw new Error("reviewed OpenShell SDK artifact directory must be absolute"); + } + const artifactDirectory = resolve(request.artifactDirectory); + if (!existsSync(artifactDirectory)) { + if (sdkIsLocked) throw new Error("reviewed OpenShell SDK artifact is required"); + return; + } + if (!reviewedLockfilePath) { + throw new Error("reviewed OpenShell SDK artifact is not used by either lockfile"); + } + await seedReviewedSourceRegistryArtifact( + { + allowedNestedShrinkwrapPackages: config.sourceNestedShrinkwrapPackages, + artifactDirectory, + cacheDirectory, + lockfilePath: reviewedLockfilePath, + otherReviewedPackages: reviewedSourceRegistryPackages(config).filter( + ({ packageSpec }) => packageSpec !== reviewed.packageSpec, + ), + registryOrigin: config.registryOrigin, + reviewed, + reviewedPackagesWithoutIntegrity: config.sourceRegistryPackagesWithoutIntegrity, + }, + stage, + ); +} + +export async function prepareCiNpmInstallWithReviewedConfig( + request: PreparationRequest, + reviewedConfigSource: string, + stage?: NpmCacheStager, +): Promise { + return prepareCiNpmInstallWithConfig(request, parseAuditConfig(reviewedConfigSource), stage); +} + +export async function prepareCiNpmInstall( + request: PreparationRequest, + stage?: NpmCacheStager, +): Promise { + return prepareCiNpmInstallWithConfig(request, readTrustedAuditConfig(), stage); +} diff --git a/scripts/lib/reviewed-npm-cache.mts b/scripts/lib/reviewed-npm-cache.mts index da3700a1f93..681901d3833 100644 --- a/scripts/lib/reviewed-npm-cache.mts +++ b/scripts/lib/reviewed-npm-cache.mts @@ -52,6 +52,14 @@ function npmCacheFailureDiagnostic( } export function stageReviewedArchiveWithNpm(request: NpmCacheStageRequest): void { + const { + GITHUB_TOKEN: _github, + GH_TOKEN: _gh, + NODE_AUTH_TOKEN: _node, + NPM_TOKEN: _npm, + NPM_CONFIG__AUTH_TOKEN: _auth, + ...environment + } = process.env; const stagingRoot = mkdtempSync(join(tmpdir(), "nemoclaw-reviewed-npm-cache-add-")); try { const archivePath = join(stagingRoot, request.artifactName); @@ -69,7 +77,7 @@ export function stageReviewedArchiveWithNpm(request: NpmCacheStageRequest): void ], { encoding: "utf8", - env: { ...process.env, NPM_CONFIG_UPDATE_NOTIFIER: "false" }, + env: { ...environment, NPM_CONFIG_UPDATE_NOTIFIER: "false" }, maxBuffer: 16 * 1024 * 1024, timeout: 30_000, stdio: ["ignore", "pipe", "pipe"], diff --git a/test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts b/test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts index 72c047ee2f8..40dec070680 100644 --- a/test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts +++ b/test/automation/pull-requests/candidate-upgrade-admission-workflow.test.ts @@ -2,6 +2,7 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import { join } from "node:path"; import { readYaml, type WorkflowJob } from "../../helpers/e2e-workflow-contract"; const workflow = readYaml<{ jobs: Record }>( @@ -15,6 +16,43 @@ const AsyncFunction = Object.getPrototypeOf(async () => undefined).constructor; const head = "a".repeat(40); const base = "b".repeat(40); +function packagingFixture() { + const step = workflow.jobs["candidate-sdk-package"]!.steps!.find( + (item) => item.id === "package", + )!; + const script = step + .run!.split("\n") + .filter((line) => !line.startsWith("import ") && line !== "NODE" && !line.startsWith("node ")) + .join("\n"); + const append = vi.fn(); + const request = vi.fn(async () => ({ authenticated: true })); + const packageSdk = vi.fn( + async (_output: string, _identity: unknown, fetch: (path: string) => Promise) => { + await fetch("/repos/NVIDIA/NemoClaw/pulls/123"); + return { required: true, bundleName: "approved-bundle", artifactName: "sdk.tgz" }; + }, + ); + const run = () => + new AsyncFunction( + "appendFileSync", + "join", + "packageCandidateOpenShellSdkIfRequired", + "githubRequest", + "process", + script, + )(append, join, packageSdk, request, { + env: { + UPGRADE_PR_NUMBER: "123", + CANDIDATE_SHA: head, + UPGRADE_BASE_SHA: base, + RUNNER_TEMP: "/fixture-temp", + GITHUB_OUTPUT: "/fixture-output", + GITHUB_TOKEN: "synthetic-read-token", + }, + }); + return { append, request, packageSdk, run }; +} + function fixture() { const pr = { state: "open", @@ -62,6 +100,38 @@ function fixture() { } describe("candidate upgrade admission status", () => { + it("passes captured commits and the API credential to the trusted package producer", async () => { + const f = packagingFixture(); + await f.run(); + expect(f.packageSdk).toHaveBeenCalledExactlyOnceWith( + "/fixture-temp/candidate-sdk", + { prNumber: 123, candidateSha: head, baseSha: base }, + expect.any(Function), + ); + expect(f.request).toHaveBeenCalledExactlyOnceWith( + "/repos/NVIDIA/NemoClaw/pulls/123", + "synthetic-read-token", + ); + expect(f.append.mock.calls).toEqual([ + ["/fixture-output", "required=true\n"], + ["/fixture-output", "bundle_name=approved-bundle\nartifact_name=sdk.tgz\n"], + ]); + }); + + it("does not release upload outputs when the package producer rejects admission", async () => { + const f = packagingFixture(); + f.packageSdk.mockRejectedValueOnce(new Error("revoked admission")); + await expect(f.run()).rejects.toThrow("revoked admission"); + expect(f.append).not.toHaveBeenCalled(); + }); + + it("does not request a candidate upload for a trusted SDK", async () => { + const f = packagingFixture(); + f.packageSdk.mockResolvedValueOnce({ required: false, bundleName: "", artifactName: "" }); + await f.run(); + expect(f.append).toHaveBeenCalledExactlyOnceWith("/fixture-output", "required=false\n"); + }); + it("does not admit a PR closed during verification", async () => { const f = fixture(); await f.start(); diff --git a/test/automation/pull-requests/pr-workflow-contract.test.ts b/test/automation/pull-requests/pr-workflow-contract.test.ts index 996c3b0169f..0c1bfb6fb2a 100644 --- a/test/automation/pull-requests/pr-workflow-contract.test.ts +++ b/test/automation/pull-requests/pr-workflow-contract.test.ts @@ -321,6 +321,7 @@ function runSdkPackageLocator(fixture: SdkPackageLocatorFixture): Readonly<{ GITHUB_WORKSPACE: tempRoot, REPOSITORY_ID: "123", HEAD_REPOSITORY: fixture.headRepository ?? "NVIDIA/NemoClaw", + CANDIDATE_SHA: "a".repeat(40), PATH: `${fakeBin}:${process.env.PATH ?? ""}`, }, tempRoot, @@ -522,7 +523,7 @@ describe("pull request and main workflow contracts", () => { // source-shape-contract: security -- Pull request jobs must never receive the GitHub Packages credential it("does not grant package access to pull request jobs", () => { - expect(prWorkflow.permissions).toEqual({ contents: "read" }); + expect(prWorkflow.permissions).toEqual({ contents: "read", "pull-requests": "read" }); expect( Object.entries(prWorkflow.jobs).filter(([, job]) => job.permissions?.packages !== undefined), ).toEqual([]); @@ -581,6 +582,7 @@ describe("pull request and main workflow contracts", () => { expect(actions.map((action) => requiredStep(action, "Install dependencies").env)).toEqual( actions.map(() => ({ NODE_AUTH_TOKEN: "${{ github.event_name == 'push' && github.token || '' }}", + GITHUB_TOKEN: "${{ github.event_name == 'pull_request' && github.token || '' }}", })), ); expect(actions.map((action) => requiredStep(action, "Install dependencies").run)).toEqual([ @@ -862,10 +864,10 @@ printf '%s %s\\n' '6bf226944684f56c84dd014e8b979d27425c0148f61b3bd99bcc6f39e9dc expect(result.calls).toEqual([""]); }); - // source-shape-contract: security -- PR dependency jobs receive only the base-approved SDK archive after credential-free integrity verification - it("passes only the base-packaged SDK archive to pull request dependency jobs", () => { + // source-shape-contract: security -- The base-controlled verifier admits SDK archives before downstream candidate dependency execution + it("passes only an SDK archive admitted by the base-controlled verifier to dependency jobs", () => { const job = prWorkflow.jobs["openshell-sdk-package"]; - expect(job.permissions).toEqual({ actions: "read", contents: "read" }); + expect(job.permissions).toEqual({ actions: "read", contents: "read", "pull-requests": "read" }); expect(requiredWorkflowStep(job, "Checkout base package decision").with).toMatchObject({ ref: "${{ github.event.pull_request.base.sha }}", path: ".trusted-sdk-package-decision", @@ -963,14 +965,6 @@ printf '%s %s\\n' '6bf226944684f56c84dd014e8b979d27425c0148f61b3bd99bcc6f39e9dc expect(githubOutput).not.toContain("artifact_id="); }); - it("accepts a manually refreshed archive from trusted main", () => { - const { result } = runSdkPackageLocator({ - step: locateSdk, - run: { ...mainSdkRun, event: "workflow_dispatch" }, - }); - expect(result.status, result.stderr).toBe(0); - }); - it("reports artifact lookup failures without private API diagnostics", () => { const { result } = runSdkPackageLocator({ step: locateSdk, apiFailure: true }); expect(result.status).not.toBe(0); diff --git a/test/e2e/README.md b/test/e2e/README.md index 62d7cbd8eb2..54c4843cf75 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -242,8 +242,23 @@ An approval comment refreshes only the commit status. If the native hash check failed before approval, rerun that job after approval. An interrupted refresh remains pending or fails; it cannot reuse an earlier success. -This does not yet extend the protected runtime's source projection, approve a new -SDK dependency graph, qualify Pi, or add ARM64 candidate catalogs. A data-admission +For a new OpenShell TypeScript SDK version, the same approval also binds the root +and plugin manifests, lockfiles, and SDK archive identity in `ci/reviewed-npm-audit.json`. +The trusted producer accepts only official, integrity-pinned SDK archives. It keeps +the base registry, npm, audit, and exception policy; candidate policy cannot relax them. +The producer uses the base checkout, not candidate code, and disables npm scripts. +Its package credential is available only during the package step. + +PR CI uses the existing `main` bundle for SDK versions already trusted by the base. +A new version uses an artifact bound to the PR, candidate commit, base commit, and +approval record. The locator checks the producing workflow and event. Each trusted +installer then rechecks approval, local manifests and locks, and archive integrity. +The API credential is limited to trusted preparation and removed before npm runs. +If CI starts before the approved artifact exists, wait for the admission workflow's +SDK job, then rerun CI. Changed or revoked approval cannot reuse the older artifact. + +This does not yet extend the protected runtime's source projection, permit a new +SDK graph on protected E2E hosts, qualify Pi, or add ARM64 candidate catalogs. A data-admission comment is not permission to execute arbitrary candidate code on a protected host. Those boundaries require their own supported implementation and validation; passing the hash check is not full E2E qualification. diff --git a/test/repository/candidate-openshell-sdk-artifact.test.ts b/test/repository/candidate-openshell-sdk-artifact.test.ts new file mode 100644 index 00000000000..6067b88b43f --- /dev/null +++ b/test/repository/candidate-openshell-sdk-artifact.test.ts @@ -0,0 +1,108 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { candidateSdkLocatorFixture } from "../support/candidate-openshell-sdk.ts"; + +const roots: string[] = []; +function fixture(mode: "candidate" | "trusted" = "candidate") { + const root = mkdtempSync(join(tmpdir(), "nemoclaw-sdk-artifact-locator-")); + roots.push(root); + return candidateSdkLocatorFixture(root, mode); +} +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe("candidate SDK artifact provenance", () => { + it.each(["push", "workflow_dispatch"])( + "keeps the trusted SDK archive from main event %s", + (event) => { + const f = fixture("trusted"); + f.run.event = event; + const result = f.execute(); + expect(result.status, result.stderr).toBe(0); + expect(result.output).toContain( + `artifact_id=42\nrun_id=44\nartifact_name=${f.decision.artifactName}`, + ); + }, + ); + + it("does not use a candidate producer for an already trusted SDK", () => { + const f = fixture("trusted"); + f.run.path = ".github/workflows/candidate-upgrade-admission.yaml"; + f.run.event = "pull_request_target"; + const result = f.execute(); + expect(result.status).not.toBe(0); + expect(result.output).not.toContain("artifact_id="); + }); + + it("does not download any archive when neither lock uses the SDK", () => { + const f = fixture("trusted"); + f.decision.required = false; + const result = f.execute(); + expect(result.status, result.stderr).toBe(0); + expect(result.output).toBe("required=false\n"); + }); + + it("selects an archive from the trusted pull-request-target producer", () => { + const f = fixture(); + const result = f.execute(); + expect(result.status, result.stderr).toBe(0); + expect(result.output).toContain( + "artifact_id=42\nrun_id=44\nartifact_name=nvidia-openshell-sdk-9.8.7.tgz", + ); + }); + + it("selects an archive produced after an approval comment on main", () => { + const f = fixture(); + f.run.event = "issue_comment"; + f.run.head_branch = "main"; + f.run.head_sha = "d".repeat(40); + const result = f.execute(); + expect(result.status, result.stderr).toBe(0); + expect(result.output).toContain("artifact_id=42"); + }); + + it.each([ + ["path", ".github/workflows/pr.yaml"], + ["event", "pull_request"], + ["event", "workflow_dispatch"], + ["status", "in_progress"], + ["conclusion", "failure"], + ["head_sha", "f".repeat(40)], + ] as const)("rejects producer %s=%s", (key, value) => { + const f = fixture(); + f.run[key] = value; + const result = f.execute(); + expect(result.status).not.toBe(0); + expect(result.output).not.toContain("artifact_id="); + }); + + it.each(["repository", "head_repository"] as const)("rejects a different producer %s", (key) => { + const f = fixture(); + f.run[key].full_name = "attacker/NemoClaw"; + const result = f.execute(); + expect(result.status).not.toBe(0); + expect(result.output).not.toContain("artifact_id="); + }); + + it("rejects an archive for a superseded approval", () => { + const f = fixture(); + f.artifact.name = f.artifact.name.replace(/-50$/u, "-49"); + const result = f.execute(); + expect(result.status).not.toBe(0); + expect(result.output).not.toContain("artifact_id="); + }); + + it("rejects an expired archive", () => { + const f = fixture(); + f.artifact.expired = true; + const result = f.execute(); + expect(result.status).not.toBe(0); + expect(result.output).not.toContain("artifact_id="); + }); +}); diff --git a/test/repository/candidate-openshell-sdk-install.test.ts b/test/repository/candidate-openshell-sdk-install.test.ts new file mode 100644 index 00000000000..d43acb4eda3 --- /dev/null +++ b/test/repository/candidate-openshell-sdk-install.test.ts @@ -0,0 +1,162 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { prepareApprovedCandidateOpenShellSdk } from "../../scripts/checks/candidate-openshell-sdk.mts"; +import { + afterCandidateSdkRead, + candidateSdkCheckout, + candidateSdkFixture, + sdkCandidateIdentity, +} from "../support/candidate-openshell-sdk.ts"; + +const roots: string[] = []; +function fixture() { + const root = mkdtempSync(join(tmpdir(), "nemoclaw-candidate-sdk-install-")); + roots.push(root); + const f = candidateSdkFixture(); + return { ...f, preparation: candidateSdkCheckout(root, f), stage: vi.fn() }; +} +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe("admitted candidate SDK installation", () => { + it("stages verified bytes only after rechecking live admission", async () => { + const f = fixture(); + await prepareApprovedCandidateOpenShellSdk( + f.preparation, + sdkCandidateIdentity, + f.request, + f.trustedSource, + f.stage, + ); + expect(f.stage).toHaveBeenCalledExactlyOnceWith({ + archive: f.bytes, + artifactName: f.sdk.artifactName, + cacheDirectory: f.preparation.cacheDirectory, + }); + expect(f.request.mock.calls.filter(([route]) => route.includes("/contents/"))).toHaveLength(10); + }); + + it.each([ + "package.json", + "package-lock.json", + "nemoclaw/package.json", + "nemoclaw/package-lock.json", + ])("rejects a checkout that differs from the approved %s", async (path) => { + const f = fixture(); + writeFileSync(join(f.preparation.targetRoot, path), "{}"); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + sdkCandidateIdentity, + f.request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/checkout differs/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it("rejects a symbolic-link input before staging", async () => { + const f = fixture(); + const path = join(f.preparation.targetRoot, "package.json"); + rmSync(path); + symlinkSync("nemoclaw/package.json", path); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + sdkCandidateIdentity, + f.request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/symbolic-link/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it("rejects corrupt archive bytes before staging", async () => { + const f = fixture(); + writeFileSync(join(f.preparation.artifactDirectory, f.sdk.artifactName), "substituted"); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + sdkCandidateIdentity, + f.request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/integrity mismatch/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it("rejects a revoked approval before staging verified bytes", async () => { + const f = fixture(); + const request = afterCandidateSdkRead(f, () => { + f.records.length = 0; + }); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + sdkCandidateIdentity, + request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/independent maintainer/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it("rejects a replacement approval before staging verified bytes", async () => { + const f = fixture(); + const request = afterCandidateSdkRead(f, () => { + f.records[0]!.id = 51; + }); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + sdkCandidateIdentity, + request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/admission changed/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it("rechecks checkout inputs after acquiring the final approval", async () => { + const f = fixture(); + const request = afterCandidateSdkRead(f, () => { + writeFileSync(join(f.preparation.targetRoot, "nemoclaw/package-lock.json"), "{}"); + }); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + sdkCandidateIdentity, + request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/checkout differs/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it("rejects registry installation without consulting GitHub", async () => { + const f = fixture(); + await expect( + prepareApprovedCandidateOpenShellSdk( + { ...f.preparation, mode: "registry" }, + sdkCandidateIdentity, + f.request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/requires artifact mode/); + expect(f.request).not.toHaveBeenCalled(); + expect(f.stage).not.toHaveBeenCalled(); + }); +}); diff --git a/test/repository/candidate-openshell-sdk.test.ts b/test/repository/candidate-openshell-sdk.test.ts new file mode 100644 index 00000000000..c4a168594f2 --- /dev/null +++ b/test/repository/candidate-openshell-sdk.test.ts @@ -0,0 +1,296 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync, mkdirSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; +import { + readApprovedOpenShellSdkConfig, + readCandidateSdkPackageDecision, +} from "../../scripts/checks/candidate-openshell-sdk.mts"; +import { + packageApprovedCandidateOpenShellSdk, + packageCandidateOpenShellSdkIfRequired, +} from "../../scripts/checks/package-openshell-sdk-for-pr.mts"; +import { requiresCandidateSdkAdmission } from "../../scripts/checks/prepare-ci-npm-install.mts"; +import { candidateSdkFixture, sdkCandidateIdentity } from "../support/candidate-openshell-sdk.ts"; +import type { ReviewedNpmArchiveRequest } from "../../scripts/lib/reviewed-npm-archive.mts"; + +const roots: string[] = []; +afterEach(() => { + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe("admitted candidate SDK packages", () => { + it("packages a newly approved SDK with a commit-bound artifact name", async () => { + const f = candidateSdkFixture(); + const root = mkdtempSync(join(tmpdir(), "nemoclaw-candidate-sdk-publication-")); + roots.push(root); + const archivePath = join(root, "input.tgz"); + writeFileSync(archivePath, f.bytes); + const pack = vi.fn(() => ({ archivePath, rootDirectory: root })); + const result = await packageCandidateOpenShellSdkIfRequired( + join(root, "output"), + sdkCandidateIdentity, + f.request, + { + readAuditConfig: () => f.trustedSource, + pack, + remove: vi.fn(), + }, + ); + expect(result).toEqual({ + required: true, + candidate: true, + artifactName: f.sdk.artifactName, + artifact: join(root, "output", f.sdk.artifactName), + bundleName: `candidate-openshell-sdk-123-${sdkCandidateIdentity.candidateSha}-${sdkCandidateIdentity.baseSha}-50`, + }); + expect(readFileSync(join(root, "output", f.sdk.artifactName))).toEqual(f.bytes); + expect(pack).toHaveBeenCalledOnce(); + }); + + it("keeps a trusted SDK on the existing artifact path without approval or downloading", async () => { + const f = candidateSdkFixture(); + f.records.length = 0; + const trustedSource = JSON.stringify({ ...f.trusted, sourceRegistryPackage: f.sdk }); + const pack = vi.fn(); + await expect( + packageCandidateOpenShellSdkIfRequired("unused", sdkCandidateIdentity, f.request, { + readAuditConfig: () => trustedSource, + pack, + }), + ).resolves.toEqual({ required: false }); + expect(pack).not.toHaveBeenCalled(); + expect(f.request.mock.calls.map(([route]) => route)).toEqual([ + `/repos/NVIDIA/NemoClaw/contents/package-lock.json?ref=${sdkCandidateIdentity.candidateSha}`, + `/repos/NVIDIA/NemoClaw/contents/nemoclaw/package-lock.json?ref=${sdkCandidateIdentity.candidateSha}`, + ]); + }); + + it("binds a new SDK artifact to the candidate, base and current approval", async () => { + const f = candidateSdkFixture(); + await expect( + readCandidateSdkPackageDecision(sdkCandidateIdentity, f.request, f.trustedSource), + ).resolves.toEqual({ + required: true, + candidate: true, + artifactName: f.sdk.artifactName, + bundleName: `candidate-openshell-sdk-123-${sdkCandidateIdentity.candidateSha}-${sdkCandidateIdentity.baseSha}-50`, + }); + }); + + it.each(["latest", "file:../sdk", "9.8", null])( + "rejects malformed lock version %s before choosing admission", + (version) => { + const f = candidateSdkFixture(); + const lock = JSON.stringify({ + packages: { "node_modules/@nvidia/openshell-sdk": { version } }, + }); + expect(() => requiresCandidateSdkAdmission([lock], f.trustedSource)).toThrow(/exact version/); + }, + ); + + it("does not turn a changed integrity on a known version into a new admission", () => { + const f = candidateSdkFixture(); + f.change("package-lock.json", (value) => { + value.packages["node_modules/@nvidia/openshell-sdk"].integrity = "substituted"; + }); + expect( + requiresCandidateSdkAdmission( + [f.sources["package-lock.json"]!], + JSON.stringify({ ...f.trusted, sourceRegistryPackage: f.sdk }), + ), + ).toBe(false); + }); + + it("selects a new SDK and its graph without adopting candidate audit policy", async () => { + const f = candidateSdkFixture(); + f.change("ci/reviewed-npm-audit.json", (value) => { + value.severityThreshold = "critical"; + value.registryOrigin = "https://attacker.invalid"; + value.sourceRegistryPackagesWithoutIntegrity = []; + value.sourceNestedShrinkwrapPackages = ["sdk-helper@1.0.0"]; + value.exceptionFile = "candidate-exceptions.json"; + }); + const result = await readApprovedOpenShellSdkConfig( + sdkCandidateIdentity, + f.request, + f.trustedSource, + ); + const { sourceRegistryPackageReplacement: _old, ...expected } = f.trusted; + expect(JSON.parse(result.configSource)).toEqual({ ...expected, sourceRegistryPackage: f.sdk }); + expect(result.sources["package-lock.json"]).toBe(f.sources["package-lock.json"]); + expect(result.reviewer).toBe("reviewer"); + }); + + it.each([ + ["packageSpec", "@other/sdk@9.8.7"], + ["packageSpec", "@nvidia/openshell-sdk@latest"], + ["artifactName", "../sdk.tgz"], + ["integrity", "sha512-short"], + ["tarballUrl", "https://attacker.invalid/sdk.tgz"], + [ + "tarballUrl", + "https://npm.pkg.github.com/download/@nvidia/openshell-sdk/9.8.7/../" + "c".repeat(40), + ], + ])("rejects invalid SDK %s before packaging", async (key, value) => { + const f = candidateSdkFixture(); + f.change("ci/reviewed-npm-audit.json", (config) => { + config.sourceRegistryPackage[key!] = value; + }); + await expect( + readApprovedOpenShellSdkConfig(sdkCandidateIdentity, f.request, f.trustedSource), + ).rejects.toThrow(/immutable official/); + }); + + it.each(["package.json", "nemoclaw/package.json"])( + "rejects a conflicting pin in %s", + async (file) => { + const f = candidateSdkFixture(); + f.change(file, (value) => { + value.optionalDependencies["@nvidia/openshell-sdk"] = "9.8.8"; + }); + await expect( + readApprovedOpenShellSdkConfig(sdkCandidateIdentity, f.request, f.trustedSource), + ).rejects.toThrow(/one identity/); + }, + ); + + it.each(["package-lock.json", "nemoclaw/package-lock.json"])( + "validates SDK identity and transitive registry in %s", + async (file) => { + const f = candidateSdkFixture(); + f.change(file, (value) => { + value.packages["node_modules/sdk-helper"].resolved = "https://attacker.invalid/helper.tgz"; + }); + await expect( + readApprovedOpenShellSdkConfig(sdkCandidateIdentity, f.request, f.trustedSource), + ).rejects.toThrow(/reviewed registry/); + }, + ); + + it("rejects a missing SDK transitive dependency", async () => { + const f = candidateSdkFixture(); + f.change("package-lock.json", (value) => { + delete value.packages["node_modules/sdk-helper"]; + }); + await expect( + readApprovedOpenShellSdkConfig(sdkCandidateIdentity, f.request, f.trustedSource), + ).rejects.toThrow(/missing a production dependency/); + }); + + it("rejects substitution of a base-trusted SDK identity", async () => { + const f = candidateSdkFixture(); + const source = JSON.stringify({ + ...f.trusted, + sourceRegistryPackage: { + ...f.sdk, + integrity: "sha512-" + Buffer.alloc(64).toString("base64"), + }, + }); + await expect( + readApprovedOpenShellSdkConfig(sdkCandidateIdentity, f.request, source), + ).rejects.toThrow(/cannot replace/); + }); + + it("requires independent current admission before reading package inputs", async () => { + const f = candidateSdkFixture(); + f.records.length = 0; + await expect( + readApprovedOpenShellSdkConfig(sdkCandidateIdentity, f.request, f.trustedSource), + ).rejects.toThrow(/independent maintainer/); + expect(f.request.mock.calls.some(([route]) => route.includes("/contents/"))).toBe(false); + }); + + it.each(["success", "revoked", "corrupt", "reapproved", "head-moved", "pack-failed"])( + "packages with script execution disabled and handles %s", + async (result) => { + const f = candidateSdkFixture(); + const root = mkdtempSync(join(tmpdir(), "nemoclaw-candidate-sdk-package-")); + roots.push(root); + const archivePath = join(root, "sdk.tgz"); + writeFileSync(archivePath, result === "corrupt" ? "substituted" : f.bytes); + const outcomes = { + success: () => {}, + corrupt: () => {}, + revoked: () => { + f.records.length = 0; + }, + reapproved: () => { + f.records[0]!.id = 51; + }, + "head-moved": () => { + f.pr.head.sha = "d".repeat(40); + }, + "pack-failed": () => { + throw new Error("fixture package download failed"); + }, + }; + const pack = vi.fn((_request: ReviewedNpmArchiveRequest) => { + outcomes[result as keyof typeof outcomes](); + return { archivePath, rootDirectory: root }; + }); + const remove = vi.fn(); + const output = join(root, "output"); + const task = packageApprovedCandidateOpenShellSdk(output, sdkCandidateIdentity, f.request, { + pack, + remove, + readAuditConfig: () => f.trustedSource, + env: { + GITHUB_TOKEN: "fixture-read-token", + GH_TOKEN: "fixture-cli-token", + NODE_AUTH_TOKEN: "fixture-package-token", + }, + }); + const assertions = { + success: async () => { + const artifact = await task; + expect(readFileSync(artifact)).toEqual(f.bytes); + }, + revoked: async () => { + await expect(task).rejects.toThrow(/independent maintainer/); + expect(existsSync(output)).toBe(false); + }, + corrupt: async () => { + await expect(task).rejects.toThrow(/integrity mismatch/); + expect(existsSync(output)).toBe(false); + }, + reapproved: async () => { + await expect(task).rejects.toThrow(/admission changed/); + expect(existsSync(output)).toBe(false); + }, + "head-moved": async () => { + await expect(task).rejects.toThrow(/open upstream PR/); + expect(existsSync(output)).toBe(false); + }, + "pack-failed": async () => { + await expect(task).rejects.toThrow(/package download failed/); + expect(existsSync(output)).toBe(false); + }, + }; + await assertions[result as keyof typeof assertions](); + expect(pack).toHaveBeenCalledOnce(); + expect(pack.mock.calls[0]![0].env).toEqual({ + NODE_AUTH_TOKEN: "fixture-package-token", + NPM_CONFIG_IGNORE_SCRIPTS: "true", + }); + expect(remove).toHaveBeenCalledTimes(result === "pack-failed" ? 0 : 1); + }, + ); + + it("preserves an existing output directory without calling admission or npm", async () => { + const f = candidateSdkFixture(); + const root = mkdtempSync(join(tmpdir(), "nemoclaw-candidate-sdk-existing-")); + roots.push(root); + const output = join(root, "output"); + mkdirSync(output); + writeFileSync(join(output, "retained"), "preserve"); + await expect( + packageApprovedCandidateOpenShellSdk(output, sdkCandidateIdentity, f.request), + ).rejects.toThrow(/new absolute/); + expect(f.request).not.toHaveBeenCalled(); + expect(readFileSync(join(output, "retained"), "utf8")).toBe("preserve"); + }); +}); diff --git a/test/repository/ci-install-dependencies.test.ts b/test/repository/ci-install-dependencies.test.ts index 3da86d91a75..a1241f67456 100644 --- a/test/repository/ci-install-dependencies.test.ts +++ b/test/repository/ci-install-dependencies.test.ts @@ -63,6 +63,30 @@ afterEach(() => { }); describe("shared CI dependency installer", () => { + it("removes GitHub API credentials before running candidate dependency installation", () => { + const fixture = makeFixture(); + writeFileSync( + join(fixture.root, "bin", "npm"), + '#!/bin/sh\n[ -z "${GITHUB_TOKEN:-}" ] && [ -z "${GH_TOKEN:-}" ] || exit 42\nprintf \'%s\\n\' "$*" >> "$NPM_TRACE"\n', + ); + const result = spawnSync("bash", [installer, "none", "artifact"], { + cwd: fixture.root, + encoding: "utf8", + env: { + ...process.env, + GITHUB_TOKEN: "fixture-api-token", + GH_TOKEN: "fixture-cli-token", + NPM_TRACE: fixture.trace, + PATH: fixture.path, + RUNNER_TEMP: join(fixture.root, "runner-temp"), + }, + }); + expect(result.status, result.stderr).toBe(0); + expect(readFileSync(fixture.trace, "utf8")).toContain( + "ci --allow-remote=root --ignore-scripts", + ); + }); + it("installs from a composite-action path without lifecycle scripts", () => { const fixture = makeFixture(); const result = runInstaller(fixture); diff --git a/test/repository/package-openshell-sdk-for-pr.test.ts b/test/repository/package-openshell-sdk-for-pr.test.ts index 62dc3f46f53..6a2b6307d66 100644 --- a/test/repository/package-openshell-sdk-for-pr.test.ts +++ b/test/repository/package-openshell-sdk-for-pr.test.ts @@ -4,11 +4,13 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { spawnSync } from "node:child_process"; import { afterEach, describe, expect, it, vi } from "vitest"; import { packageReviewedOpenShellSdk } from "../../scripts/checks/package-openshell-sdk-for-pr.mts"; import type { ReviewedNpmArchiveRequest } from "../../scripts/lib/reviewed-npm-archive.mts"; +import { sparseSdkWorkflowCheckout } from "../support/candidate-openshell-sdk.ts"; const roots: string[] = []; @@ -34,6 +36,48 @@ function fixture() { } describe("reviewed OpenShell SDK transition packaging", () => { + it("loads the ordinary producer from the main workflow sparse checkout", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-main-sdk-sparse-")); + roots.push(root); + sparseSdkWorkflowCheckout(root, ".github/workflows/main.yaml", "package-openshell-sdk"); + const result = spawnSync( + process.execPath, + [ + "--input-type=module", + "-e", + "const producer = await import('./scripts/checks/package-openshell-sdk-for-pr.mts'); console.log(typeof producer.packageReviewedOpenShellSdk)", + ], + { + cwd: root, + encoding: "utf8", + timeout: 10_000, + }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("function"); + }); + + it("loads the ordinary consumer from the PR workflow sparse checkouts", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-sdk-sparse-")); + roots.push(root); + sparseSdkWorkflowCheckout(root, ".github/workflows/pr.yaml", "openshell-sdk-package"); + const result = spawnSync( + process.execPath, + [ + "--input-type=module", + "-e", + "const consumer = await import('./scripts/checks/prepare-ci-npm-install.mts'); console.log(typeof consumer.prepareCiNpmInstall)", + ], + { + cwd: root, + encoding: "utf8", + timeout: 10_000, + }, + ); + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("function"); + }); + it("fails closed when replacement packaging lacks replacement metadata", () => { const source = fixture(); const configPath = path.resolve("ci/reviewed-npm-audit.json"); diff --git a/test/repository/prepare-ci-npm-install.test.ts b/test/repository/prepare-ci-npm-install.test.ts index 0bc8955de86..8e16311ea96 100644 --- a/test/repository/prepare-ci-npm-install.test.ts +++ b/test/repository/prepare-ci-npm-install.test.ts @@ -206,6 +206,29 @@ afterEach(() => { }); describe("trusted OpenShell SDK archive preparation", () => { + it("does not pass API or package credentials to the offline cache process", async () => { + const source = fixture(); + const bin = join(source.root, "bin"); + mkdirSync(bin); + const trace = join(source.root, "environment.json"); + writeFileSync( + join(bin, "npm"), + `#!/usr/bin/env node\nrequire('node:fs').writeFileSync(${JSON.stringify(trace)}, JSON.stringify(process.env));\n`, + ); + chmodSync(join(bin, "npm"), 0o700); + vi.stubEnv("PATH", `${bin}:${process.env.PATH ?? ""}`); + vi.stubEnv("GITHUB_TOKEN", "fixture-credential-sentinel"); + vi.stubEnv("GH_TOKEN", "fixture-credential-sentinel"); + vi.stubEnv("NODE_AUTH_TOKEN", "fixture-credential-sentinel"); + vi.stubEnv("NPM_TOKEN", "fixture-credential-sentinel"); + vi.stubEnv("NPM_CONFIG__AUTH_TOKEN", "fixture-credential-sentinel"); + await seedReviewedSourceRegistryArtifact(request(source)); + const environment = JSON.parse(readFileSync(trace, "utf8")); + expect(environment.PATH).toBe(process.env.PATH); + expect(environment.NPM_CONFIG_UPDATE_NOTIFIER).toBe("false"); + expect(readFileSync(trace, "utf8")).not.toContain("fixture-credential-sentinel"); + }); + it("reports a bounded redacted npm cache-stage failure", async () => { const source = fixture(); const executableDirectory = join(source.root, "bin"); diff --git a/test/support/candidate-openshell-sdk.ts b/test/support/candidate-openshell-sdk.ts new file mode 100644 index 00000000000..1381bdb543d --- /dev/null +++ b/test/support/candidate-openshell-sdk.ts @@ -0,0 +1,239 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash } from "node:crypto"; +import { chmodSync, cpSync, existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs"; +import { spawnSync } from "node:child_process"; +import { dirname, join } from "node:path"; +import { vi } from "vitest"; +import YAML from "yaml"; + +export const sdkCandidateIdentity = { + prNumber: 123, + candidateSha: "a".repeat(40), + baseSha: "b".repeat(40), +}; + +export function candidateSdkFixture() { + const bytes = Buffer.from("inert candidate SDK archive fixture"); + const integrity = `sha512-${createHash("sha512").update(bytes).digest("base64")}`; + const trustedSource = readFileSync("ci/reviewed-npm-audit.json", "utf8"); + const trusted = JSON.parse(trustedSource); + const sdk = { + artifactName: "nvidia-openshell-sdk-9.8.7.tgz", + packageSpec: "@nvidia/openshell-sdk@9.8.7", + label: "OpenShell TypeScript SDK 9.8.7", + integrity, + tarballUrl: `https://npm.pkg.github.com/download/@nvidia/openshell-sdk/9.8.7/${"c".repeat(40)}`, + }; + const manifest = { optionalDependencies: { "@nvidia/openshell-sdk": "9.8.7" } }; + const lock = { + lockfileVersion: 3, + packages: { + "": manifest, + "node_modules/@nvidia/openshell-sdk": { + version: "9.8.7", + resolved: sdk.tarballUrl, + integrity, + dependencies: { "sdk-helper": "1.0.0" }, + }, + "node_modules/sdk-helper": { + version: "1.0.0", + resolved: "https://registry.npmjs.org/sdk-helper/-/sdk-helper-1.0.0.tgz", + integrity, + }, + }, + }; + const config = { ...trusted, sourceRegistryPackage: sdk }; + delete config.sourceRegistryPackageReplacement; + const sources: Record = { + "ci/reviewed-npm-audit.json": JSON.stringify(config), + "package.json": JSON.stringify(manifest), + "nemoclaw/package.json": JSON.stringify(manifest), + "package-lock.json": JSON.stringify(lock), + "nemoclaw/package-lock.json": JSON.stringify(lock), + }; + const repository = { full_name: "NVIDIA/NemoClaw" }; + const pr = { + number: 123, + state: "open", + user: { login: "author" }, + head: { sha: sdkCandidateIdentity.candidateSha, repo: repository }, + base: { sha: sdkCandidateIdentity.baseSha, ref: "main", repo: repository }, + }; + const approval = { + id: 50, + user: { login: "reviewer", type: "User" }, + created_at: "2026-10-14T00:00:00Z", + updated_at: "2026-10-14T00:00:00Z", + body: `NemoClaw-Upgrade-E2E: approve ${sdkCandidateIdentity.candidateSha} ${sdkCandidateIdentity.baseSha}`, + }; + const records = [approval]; + const permission = { role_name: "maintain" }; + const request = vi.fn(async (route: string): Promise => { + if (route.endsWith("/pulls/123")) return pr; + if (route.endsWith("/permission")) return permission; + if (route.includes("/comments?")) return records; + const match = /^\/repos\/NVIDIA\/NemoClaw\/contents\/(.+)\?ref=([a-f0-9]{40})$/u.exec(route); + if (!match || match[2] !== sdkCandidateIdentity.candidateSha || !sources[match[1]!]) { + throw new Error("Unexpected SDK fixture request"); + } + const source = sources[match[1]!]!; + return { + type: "file", + path: match[1], + encoding: "base64", + size: Buffer.byteLength(source), + content: Buffer.from(source).toString("base64"), + }; + }); + const change = (file: string, mutate: (value: any) => void) => { + const value = JSON.parse(sources[file]!); + mutate(value); + sources[file] = JSON.stringify(value); + }; + return { bytes, trusted, trustedSource, sdk, sources, pr, records, permission, request, change }; +} + +export function candidateSdkCheckout( + root: string, + fixture: ReturnType, +) { + for (const [file, source] of Object.entries(fixture.sources)) { + mkdirSync(dirname(join(root, file)), { recursive: true }); + writeFileSync(join(root, file), source); + } + const artifactDirectory = join(root, "artifacts"); + const cacheDirectory = join(root, "cache"); + mkdirSync(artifactDirectory); + mkdirSync(cacheDirectory); + writeFileSync(join(artifactDirectory, fixture.sdk.artifactName), fixture.bytes); + return { mode: "artifact" as const, artifactDirectory, cacheDirectory, targetRoot: root }; +} + +export function afterCandidateSdkRead( + fixture: ReturnType, + change: () => void, +) { + let pullReads = 0; + return async (route: string) => { + if (route.endsWith("/pulls/123")) pullReads += 1; + if (pullReads === 3 && route.endsWith("/pulls/123")) change(); + return fixture.request(route); + }; +} + +export function sparseSdkWorkflowCheckout(root: string, workflowPath: string, job: string) { + const workflow = YAML.parse(readFileSync(workflowPath, "utf8")); + const checkouts = workflow.jobs[job].steps.filter( + (step: { with?: Record }) => step.with?.["sparse-checkout"], + ); + for (const checkout of checkouts) { + for (const entry of checkout.with["sparse-checkout"].trim().split(/\s+/u)) { + mkdirSync(dirname(join(root, entry)), { recursive: true }); + cpSync(entry, join(root, entry), { recursive: true }); + } + } +} + +export function candidateSdkLocatorFixture( + root: string, + mode: "candidate" | "trusted" = "candidate", +) { + const f = candidateSdkFixture(); + const trustedIdentities = [ + f.trusted.sourceRegistryPackage, + f.trusted.sourceRegistryPackageReplacement, + ] + .filter(Boolean) + .map((identity) => + Object.fromEntries(Object.entries(identity).sort(([a], [b]) => a.localeCompare(b))), + ); + const bundleName = + mode === "candidate" + ? `candidate-openshell-sdk-123-${sdkCandidateIdentity.candidateSha}-${sdkCandidateIdentity.baseSha}-50` + : `reviewed-openshell-sdk-${createHash("sha256") + .update(`${JSON.stringify(trustedIdentities)}\n`) + .digest("hex")}`; + const decision = { + required: true, + candidate: mode === "candidate" ? true : undefined, + artifactName: + mode === "candidate" ? f.sdk.artifactName : f.trusted.sourceRegistryPackage.artifactName, + bundleName, + }; + const artifact = { + name: bundleName, + id: 42, + expired: false, + workflow_run: { + id: 44, + head_branch: mode === "candidate" ? "upgrade" : "main", + head_repository_id: 888, + }, + }; + const run = { + path: + mode === "candidate" + ? ".github/workflows/candidate-upgrade-admission.yaml" + : ".github/workflows/main.yaml", + head_sha: sdkCandidateIdentity.candidateSha, + head_branch: mode === "candidate" ? "upgrade" : "main", + event: mode === "candidate" ? "pull_request_target" : "push", + status: "completed", + conclusion: "success", + repository: { full_name: "NVIDIA/NemoClaw" }, + head_repository: { full_name: "NVIDIA/NemoClaw" }, + }; + const bin = join(root, "bin"); + const trusted = join(root, ".trusted-sdk-package-decision"); + mkdirSync(bin); + mkdirSync(join(trusted, "scripts/checks"), { recursive: true }); + mkdirSync(join(trusted, "ci")); + writeFileSync(join(trusted, "ci/reviewed-npm-audit.json"), f.trustedSource); + writeFileSync( + join(trusted, "scripts/checks/prepare-ci-npm-install.mts"), + "process.stdout.write(process.env.SDK_LOCATOR_DECISION);\n", + ); + writeFileSync( + join(bin, "gh"), + `#!/usr/bin/env node +const route = process.argv.find(value => value.startsWith('repos/')); +if (route?.includes('/actions/artifacts?')) process.stdout.write(process.env.SDK_LOCATOR_ARTIFACTS); +else if (route?.endsWith('/actions/runs/44')) process.stdout.write(process.env.SDK_LOCATOR_RUN); +else process.exit(97); +`, + ); + chmodSync(join(bin, "gh"), 0o700); + const workflow = YAML.parse(readFileSync(".github/workflows/pr.yaml", "utf8")); + const script = workflow.jobs["openshell-sdk-package"].steps.find( + (step: { id?: string }) => step.id === "locate", + ).run; + const output = join(root, "outputs"); + return { + artifact, + run, + decision, + execute: () => { + const result = spawnSync("bash", ["-c", script], { + cwd: root, + encoding: "utf8", + timeout: 10_000, + env: { + ...process.env, + PATH: `${bin}:${process.env.PATH}`, + GITHUB_WORKSPACE: root, + GITHUB_OUTPUT: output, + GITHUB_REPOSITORY: "NVIDIA/NemoClaw", + HEAD_REPOSITORY: "NVIDIA/NemoClaw", + REPOSITORY_ID: "888", + CANDIDATE_SHA: sdkCandidateIdentity.candidateSha, + SDK_LOCATOR_DECISION: JSON.stringify(decision), + SDK_LOCATOR_ARTIFACTS: JSON.stringify([{ artifacts: [artifact] }]), + SDK_LOCATOR_RUN: JSON.stringify(run), + }, + }); + return { ...result, output: existsSync(output) ? readFileSync(output, "utf8") : "" }; + }, + }; +} From d8ae235ed577277bdcbc5c7002a54d2ba6aa09bd Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 14:16:14 -0700 Subject: [PATCH 05/11] fix(ci): bind SDK producer to exact PR association Signed-off-by: Prekshi Vyas --- .github/workflows/pr.yaml | 6 ++++-- .../pull-requests/pr-workflow-contract.test.ts | 2 ++ .../candidate-openshell-sdk-artifact.test.ts | 14 ++++++++++++++ test/support/candidate-openshell-sdk.ts | 9 +++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pr.yaml b/.github/workflows/pr.yaml index 0eb79c17651..fac8d27467f 100644 --- a/.github/workflows/pr.yaml +++ b/.github/workflows/pr.yaml @@ -288,11 +288,13 @@ jobs: } run_id="$(jq -er '.workflow_run.id | select(type == "number" and . > 0 and . <= 9007199254740991)' <<<"$artifact")" artifact_id="$(jq -er '.id | select(type == "number" and . > 0 and . <= 9007199254740991)' <<<"$artifact")" - gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id" 2>/dev/null | jq -e --arg repo "$GITHUB_REPOSITORY" --arg candidate "$candidate" --arg sha "$CANDIDATE_SHA" ' + gh api "repos/$GITHUB_REPOSITORY/actions/runs/$run_id" 2>/dev/null | jq -e --arg repo "$GITHUB_REPOSITORY" --arg candidate "$candidate" --arg sha "$CANDIDATE_SHA" --arg base "$UPGRADE_BASE_SHA" --argjson pr "$UPGRADE_PR_NUMBER" ' (if $candidate == "true" then (.path | split("@")[0]) == ".github/workflows/candidate-upgrade-admission.yaml" and .status == "completed" and .conclusion == "success" - and ((.event == "pull_request_target" and .head_sha == $sha) or (.event == "issue_comment" and .head_branch == "main")) + and ((.event == "pull_request_target" and .head_sha == $sha + and any(.pull_requests[]?; .number == $pr and .head.sha == $sha and .base.sha == $base)) + or (.event == "issue_comment" and .head_branch == "main")) else (.path | split("@")[0]) == ".github/workflows/main.yaml" and .head_branch == "main" and (.event == "push" or .event == "workflow_dispatch") diff --git a/test/automation/pull-requests/pr-workflow-contract.test.ts b/test/automation/pull-requests/pr-workflow-contract.test.ts index 0c1bfb6fb2a..82d6ff51c68 100644 --- a/test/automation/pull-requests/pr-workflow-contract.test.ts +++ b/test/automation/pull-requests/pr-workflow-contract.test.ts @@ -322,6 +322,8 @@ function runSdkPackageLocator(fixture: SdkPackageLocatorFixture): Readonly<{ REPOSITORY_ID: "123", HEAD_REPOSITORY: fixture.headRepository ?? "NVIDIA/NemoClaw", CANDIDATE_SHA: "a".repeat(40), + UPGRADE_BASE_SHA: "b".repeat(40), + UPGRADE_PR_NUMBER: "123", PATH: `${fakeBin}:${process.env.PATH ?? ""}`, }, tempRoot, diff --git a/test/repository/candidate-openshell-sdk-artifact.test.ts b/test/repository/candidate-openshell-sdk-artifact.test.ts index 6067b88b43f..3678a959975 100644 --- a/test/repository/candidate-openshell-sdk-artifact.test.ts +++ b/test/repository/candidate-openshell-sdk-artifact.test.ts @@ -74,6 +74,7 @@ describe("candidate SDK artifact provenance", () => { ["status", "in_progress"], ["conclusion", "failure"], ["head_sha", "f".repeat(40)], + ["head_sha", "b".repeat(40)], ] as const)("rejects producer %s=%s", (key, value) => { const f = fixture(); f.run[key] = value; @@ -90,6 +91,19 @@ describe("candidate SDK artifact provenance", () => { expect(result.output).not.toContain("artifact_id="); }); + it.each([ + [], + [{ number: 124, head: { sha: "a".repeat(40) }, base: { sha: "b".repeat(40) } }], + [{ number: 123, head: { sha: "f".repeat(40) }, base: { sha: "b".repeat(40) } }], + [{ number: 123, head: { sha: "a".repeat(40) }, base: { sha: "f".repeat(40) } }], + ])("rejects a target producer without the exact PR association: %j", (...associations) => { + const f = fixture(); + f.run.pull_requests = associations; + const result = f.execute(); + expect(result.status).not.toBe(0); + expect(result.output).not.toContain("artifact_id="); + }); + it("rejects an archive for a superseded approval", () => { const f = fixture(); f.artifact.name = f.artifact.name.replace(/-50$/u, "-49"); diff --git a/test/support/candidate-openshell-sdk.ts b/test/support/candidate-openshell-sdk.ts index 1381bdb543d..0c87dbc1069 100644 --- a/test/support/candidate-openshell-sdk.ts +++ b/test/support/candidate-openshell-sdk.ts @@ -179,6 +179,13 @@ export function candidateSdkLocatorFixture( : ".github/workflows/main.yaml", head_sha: sdkCandidateIdentity.candidateSha, head_branch: mode === "candidate" ? "upgrade" : "main", + pull_requests: [ + { + number: sdkCandidateIdentity.prNumber, + head: { sha: sdkCandidateIdentity.candidateSha }, + base: { sha: sdkCandidateIdentity.baseSha }, + }, + ], event: mode === "candidate" ? "pull_request_target" : "push", status: "completed", conclusion: "success", @@ -228,6 +235,8 @@ else process.exit(97); HEAD_REPOSITORY: "NVIDIA/NemoClaw", REPOSITORY_ID: "888", CANDIDATE_SHA: sdkCandidateIdentity.candidateSha, + UPGRADE_BASE_SHA: sdkCandidateIdentity.baseSha, + UPGRADE_PR_NUMBER: String(sdkCandidateIdentity.prNumber), SDK_LOCATOR_DECISION: JSON.stringify(decision), SDK_LOCATOR_ARTIFACTS: JSON.stringify([{ artifacts: [artifact] }]), SDK_LOCATOR_RUN: JSON.stringify(run), From 5b6297ac11d456923bf299ada09c2c12f8cde39b Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 15:06:19 -0700 Subject: [PATCH 06/11] fix(ci): admit reviewed SDK inputs from exact PR merges Signed-off-by: Prekshi Vyas --- scripts/checks/candidate-openshell-sdk.mts | 27 ++++- scripts/checks/prepare-ci-npm-install.mts | 2 + test/e2e/README.md | 7 ++ .../candidate-upgrade-admission.test.ts | 80 ++++++++++++++ .../candidate-openshell-sdk-install.test.ts | 101 ++++++++++++++++++ .../package-openshell-sdk-for-pr.test.ts | 69 +++++++++++- test/support/candidate-openshell-sdk.ts | 49 +++++++++ tools/e2e/candidate-upgrade-admission.mts | 34 +++++- 8 files changed, 359 insertions(+), 10 deletions(-) diff --git a/scripts/checks/candidate-openshell-sdk.mts b/scripts/checks/candidate-openshell-sdk.mts index 09f0ef8166c..59d1805460e 100644 --- a/scripts/checks/candidate-openshell-sdk.mts +++ b/scripts/checks/candidate-openshell-sdk.mts @@ -39,6 +39,7 @@ const MANIFESTS = ["package.json", "nemoclaw/package.json"] as const; const LOCKS = ["package-lock.json", "nemoclaw/package-lock.json"] as const; type Config = ReturnType; type Sdk = Config["sourceRegistryPackage"]; +type SdkInputIdentity = CandidateUpgradeIdentity & { mergeSha?: string }; function sdkIdentity(value: unknown): Sdk { if (!value || typeof value !== "object" || Array.isArray(value)) { @@ -154,7 +155,7 @@ function selectPolicy(sources: Readonly>, trusted: Config /** Acquire candidate SDK inputs under live admission, then apply the trusted package policy. */ export async function readApprovedOpenShellSdkConfig( - identity: CandidateUpgradeIdentity, + identity: SdkInputIdentity, request: UpgradeRequest, trustedConfigSource: string, ) { @@ -164,9 +165,25 @@ export async function readApprovedOpenShellSdkConfig( [CONFIG, ...MANIFESTS, ...LOCKS], request, ); + const policy = selectPolicy(admission.sources, trusted); + let sources = admission.sources; + if (identity.mergeSha !== undefined) { + const merged = await readApprovedCandidateUpgrade( + identity, + [...MANIFESTS, ...LOCKS], + request, + identity.mergeSha, + ); + if (merged.commentId !== admission.commentId || merged.reviewer !== admission.reviewer) + throw new Error("Candidate SDK admission changed during merge verification"); + sources = { ...sources, ...merged.sources }; + // The merge can update other dependencies, but cannot select a different SDK or audit policy. + if (!isDeepStrictEqual(selectPolicy(sources, trusted), policy)) + throw new Error("Candidate SDK identity changed in the merge commit"); + } return { - configSource: JSON.stringify(selectPolicy(admission.sources, trusted)), - sources: admission.sources, + configSource: JSON.stringify(policy), + sources, reviewer: admission.reviewer, commentId: admission.commentId, }; @@ -207,7 +224,7 @@ function artifactDecision( export async function inspectApprovedCandidateOpenShellSdk( targetRoot: string, - identity: CandidateUpgradeIdentity, + identity: SdkInputIdentity, request: UpgradeRequest, trustedSource: string, ) { @@ -235,7 +252,7 @@ export async function readCandidateSdkPackageDecision( /** Verify admitted sources and archive bytes before releasing them to the npm cache. */ export async function prepareApprovedCandidateOpenShellSdk( preparation: Parameters[0], - input: CandidateUpgradeIdentity, + input: SdkInputIdentity, request: UpgradeRequest, trustedConfigSource: string, stage: NpmCacheStager = stageReviewedArchiveWithNpm, diff --git a/scripts/checks/prepare-ci-npm-install.mts b/scripts/checks/prepare-ci-npm-install.mts index 42196e497be..b83849eb0d0 100755 --- a/scripts/checks/prepare-ci-npm-install.mts +++ b/scripts/checks/prepare-ci-npm-install.mts @@ -74,6 +74,8 @@ if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.m prNumber: Number(process.env.UPGRADE_PR_NUMBER), candidateSha: process.env.CANDIDATE_SHA ?? "", baseSha: process.env.UPGRADE_BASE_SHA ?? "", + mergeSha: + process.env.GITHUB_EVENT_NAME === "pull_request" ? process.env.GITHUB_SHA : undefined, }; const request = (path: string) => githubRequest(path, token); if (mode === "inspect" && targetRoot) { diff --git a/test/e2e/README.md b/test/e2e/README.md index 54c4843cf75..1e061d84beb 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -253,6 +253,13 @@ PR CI uses the existing `main` bundle for SDK versions already trusted by the ba A new version uses an artifact bound to the PR, candidate commit, base commit, and approval record. The locator checks the producing workflow and event. Each trusted installer then rechecks approval, local manifests and locks, and archive integrity. +For merge-based PR CI, GitHub must identify the checkout as the PR's current merge +commit, with the approved base and candidate as its two parents. The verifier reads +that commit's manifests and locks and compares them with the local files. The merged +dependency graph must retain the approved SDK identity and pass the trusted package +policy. Direct candidate E2E continues to require the approved candidate's file bytes. +If the merge uses a newer base, synchronize the PR and refresh its commit-bound +approval before rerunning candidate SDK CI. The API credential is limited to trusted preparation and removed before npm runs. If CI starts before the approved artifact exists, wait for the admission workflow's SDK job, then rerun CI. Changed or revoked approval cannot reuse the older artifact. diff --git a/test/e2e/support/candidate-upgrade-admission.test.ts b/test/e2e/support/candidate-upgrade-admission.test.ts index e91958a61ea..a3903f60dc1 100644 --- a/test/e2e/support/candidate-upgrade-admission.test.ts +++ b/test/e2e/support/candidate-upgrade-admission.test.ts @@ -42,6 +42,24 @@ function fixture() { return { pr, approval, records, permission, source, blob, request, routes }; } +function mergeFixture() { + const f = fixture(); + const mergeSha = "c".repeat(40); + const pr = Object.assign(f.pr, { merge_commit_sha: mergeSha }); + const commit = { + sha: mergeSha, + parents: [{ sha: identity.baseSha }, { sha: identity.candidateSha }], + }; + f.routes.set(`/repos/NVIDIA/NemoClaw/git/commits/${mergeSha}`, commit); + const mergeSource = '{"version":"9.8.7","merged":true}'; + f.routes.set(`/repos/NVIDIA/NemoClaw/contents/${sourcePath}?ref=${mergeSha}`, { + ...f.blob, + size: Buffer.byteLength(mergeSource), + content: Buffer.from(mergeSource).toString("base64"), + }); + return { ...f, pr, commit, mergeSha, mergeSource }; +} + describe("candidate upgrade admission", () => { it("reads reviewed commit data and rechecks both PR identity and current maintainer authority", async () => { const f = fixture(); @@ -217,4 +235,66 @@ describe("candidate upgrade admission", () => { "API denied", ); }); + + it("reads the GitHub merge sources when both parents match the approved commits", async () => { + const f = mergeFixture(); + await expect( + readApprovedCandidateUpgrade(identity, [sourcePath], f.request, f.mergeSha), + ).resolves.toMatchObject({ sources: { [sourcePath]: f.mergeSource } }); + }); + + it.each(["unrelated", "wrong-base", "wrong-head", "extra-parent", "wrong-sha", "mutable-ref"])( + "rejects the %s merge before reading its sources", + async (kind) => { + const f = mergeFixture(); + const mutations = { + unrelated: () => { + f.pr.merge_commit_sha = "d".repeat(40); + }, + "wrong-base": () => { + f.commit.parents[0]!.sha = "d".repeat(40); + }, + "wrong-head": () => { + f.commit.parents[1]!.sha = "d".repeat(40); + }, + "extra-parent": () => { + f.commit.parents.push({ sha: "d".repeat(40) }); + }, + "wrong-sha": () => { + f.commit.sha = "d".repeat(40); + }, + "mutable-ref": () => { + f.mergeSha = "main"; + }, + }; + mutations[kind as keyof typeof mutations](); + await expect( + readApprovedCandidateUpgrade(identity, [sourcePath], f.request, f.mergeSha), + ).rejects.toThrow(/merge/); + expect(f.request.mock.calls.some(([path]) => path.includes("/contents/"))).toBe(false); + }, + ); + + it.each(["replaced", "revoked"])( + "rejects %s authority during merge source acquisition", + async (kind) => { + const f = mergeFixture(); + const mutations = { + replaced: () => { + f.pr.merge_commit_sha = "d".repeat(40); + }, + revoked: () => { + f.records.length = 0; + }, + }; + const request = async (path: string) => { + const value = await f.request(path); + path.includes("/contents/") && mutations[kind as keyof typeof mutations](); + return value; + }; + await expect( + readApprovedCandidateUpgrade(identity, [sourcePath], request, f.mergeSha), + ).rejects.toThrow(/merge|independent maintainer/); + }, + ); }); diff --git a/test/repository/candidate-openshell-sdk-install.test.ts b/test/repository/candidate-openshell-sdk-install.test.ts index d43acb4eda3..f9873895cc4 100644 --- a/test/repository/candidate-openshell-sdk-install.test.ts +++ b/test/repository/candidate-openshell-sdk-install.test.ts @@ -10,6 +10,7 @@ import { afterCandidateSdkRead, candidateSdkCheckout, candidateSdkFixture, + candidateSdkMergeFixture, sdkCandidateIdentity, } from "../support/candidate-openshell-sdk.ts"; @@ -20,11 +21,111 @@ function fixture() { const f = candidateSdkFixture(); return { ...f, preparation: candidateSdkCheckout(root, f), stage: vi.fn() }; } +function mergeFixture() { + const root = mkdtempSync(join(tmpdir(), "nemoclaw-candidate-sdk-merge-")); + roots.push(root); + return candidateSdkMergeFixture(root); +} afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); describe("admitted candidate SDK installation", () => { + it("accepts merged dependency inputs that retain the approved SDK and trusted graph policy", async () => { + const f = mergeFixture(); + await prepareApprovedCandidateOpenShellSdk( + f.preparation, + f.identity, + f.request, + f.trustedSource, + f.stage, + ); + expect(f.stage).toHaveBeenCalledOnce(); + }); + + it("rejects a merge selecting another SDK listed in the candidate metadata", async () => { + const f = mergeFixture(); + f.change("ci/reviewed-npm-audit.json", (value) => { + value.sourceRegistryPackageReplacement = JSON.parse( + JSON.stringify(f.sdk).replaceAll("9.8.7", "9.8.8"), + ); + }); + f.writeMerged("package.json", f.sources["package.json"]!.replaceAll("9.8.7", "9.8.8")); + f.writeMerged( + "nemoclaw/package.json", + f.sources["nemoclaw/package.json"]!.replaceAll("9.8.7", "9.8.8"), + ); + f.writeMerged( + "package-lock.json", + f.sources["package-lock.json"]!.replaceAll("9.8.7", "9.8.8"), + ); + f.writeMerged( + "nemoclaw/package-lock.json", + f.sources["nemoclaw/package-lock.json"]!.replaceAll("9.8.7", "9.8.8"), + ); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + f.identity, + f.request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/identity changed in the merge/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it("rejects a replacement approval between candidate and merge source reads", async () => { + const f = mergeFixture(); + const request = afterCandidateSdkRead(f, () => { + f.records[0]!.id = 51; + }); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + f.identity, + request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/admission changed during merge/); + expect(f.stage).not.toHaveBeenCalled(); + }); + + it.each(["different-sdk", "untrusted-registry", "local-drift"])( + "rejects merged dependency inputs with %s before staging", + async (kind) => { + const f = mergeFixture(); + const mutations = { + "different-sdk": () => + f.writeMerged( + "package.json", + JSON.stringify({ optionalDependencies: { "@nvidia/openshell-sdk": "9.8.8" } }), + ), + "untrusted-registry": () => + f.writeMerged( + "package-lock.json", + f.sources["package-lock.json"]!.replace( + "https://registry.npmjs.org/", + "https://attacker.invalid/", + ), + ), + "local-drift": () => writeFileSync(join(f.preparation.targetRoot, "package.json"), "{}"), + }; + mutations[kind as keyof typeof mutations](); + await expect( + prepareApprovedCandidateOpenShellSdk( + f.preparation, + f.identity, + f.request, + f.trustedSource, + f.stage, + ), + ).rejects.toThrow(/one identity|reviewed registry|checkout differs/); + expect(f.stage).not.toHaveBeenCalled(); + }, + ); + it("stages verified bytes only after rechecking live admission", async () => { const f = fixture(); await prepareApprovedCandidateOpenShellSdk( diff --git a/test/repository/package-openshell-sdk-for-pr.test.ts b/test/repository/package-openshell-sdk-for-pr.test.ts index 6a2b6307d66..133740dafcc 100644 --- a/test/repository/package-openshell-sdk-for-pr.test.ts +++ b/test/repository/package-openshell-sdk-for-pr.test.ts @@ -10,7 +10,10 @@ import { afterEach, describe, expect, it, vi } from "vitest"; import { packageReviewedOpenShellSdk } from "../../scripts/checks/package-openshell-sdk-for-pr.mts"; import type { ReviewedNpmArchiveRequest } from "../../scripts/lib/reviewed-npm-archive.mts"; -import { sparseSdkWorkflowCheckout } from "../support/candidate-openshell-sdk.ts"; +import { + candidateSdkMergeFixture, + sparseSdkWorkflowCheckout, +} from "../support/candidate-openshell-sdk.ts"; const roots: string[] = []; @@ -36,6 +39,70 @@ function fixture() { } describe("reviewed OpenShell SDK transition packaging", () => { + it.each([ + ["pull_request", 0, /candidate-openshell-sdk/], + ["workflow_dispatch", 1, /checkout differs/], + ] as const)( + "uses merge identity only for the %s CLI entrypoint", + async (event, status, diagnostic) => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-sdk-merge-cli-")); + roots.push(root); + const f = candidateSdkMergeFixture(path.join(root, "candidate")); + sparseSdkWorkflowCheckout(root, ".github/workflows/pr.yaml", "openshell-sdk-package"); + const prefix = "/repos/NVIDIA/NemoClaw"; + const routes = [ + `${prefix}/pulls/123`, + `${prefix}/issues/123/comments?per_page=100&page=1`, + `${prefix}/collaborators/reviewer/permission`, + `${prefix}/git/commits/${f.identity.mergeSha}`, + ...Object.keys(f.sources).flatMap((file) => [ + `${prefix}/contents/${file}?ref=${f.identity.candidateSha}`, + `${prefix}/contents/${file}?ref=${f.identity.mergeSha}`, + ]), + ]; + const responses = Object.fromEntries( + await Promise.all(routes.map(async (route) => [route, await f.request(route)])), + ); + const result = spawnSync( + process.execPath, + [ + "--input-type=module", + "-e", + ` + const responses = ${JSON.stringify(responses)}; + globalThis.fetch = async (url) => { + const parsed = new URL(url); + const key = parsed.pathname + parsed.search; + return new Response(JSON.stringify(responses[key] ?? {}), { status: key in responses ? 200 : 404 }); + }; + process.argv[1] = ${JSON.stringify(path.join(root, "scripts/checks/prepare-ci-npm-install.mts"))}; + await import('./scripts/checks/prepare-ci-npm-install.mts'); + `, + ], + { + cwd: root, + encoding: "utf8", + timeout: 10_000, + env: { + ...process.env, + GITHUB_EVENT_NAME: event, + GITHUB_SHA: f.identity.mergeSha, + CANDIDATE_SHA: f.identity.candidateSha, + UPGRADE_BASE_SHA: f.identity.baseSha, + UPGRADE_PR_NUMBER: "123", + NEMOCLAW_OPEN_SHELL_SDK_CANDIDATE: "1", + NEMOCLAW_CI_NPM_PACKAGE_MODE: "inspect", + NEMOCLAW_CI_TARGET_ROOT: f.preparation.targetRoot, + GITHUB_TOKEN: "fixture-token", + }, + }, + ); + expect(result.status, result.stderr).toBe(status); + expect(result.stdout + result.stderr).toMatch(diagnostic); + expect(result.stdout + result.stderr).not.toContain("fixture-token"); + }, + ); + it("loads the ordinary producer from the main workflow sparse checkout", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-main-sdk-sparse-")); roots.push(root); diff --git a/test/support/candidate-openshell-sdk.ts b/test/support/candidate-openshell-sdk.ts index 0c87dbc1069..c8f99476cb4 100644 --- a/test/support/candidate-openshell-sdk.ts +++ b/test/support/candidate-openshell-sdk.ts @@ -123,6 +123,55 @@ export function afterCandidateSdkRead( }; } +export function candidateSdkMergeFixture(root: string) { + const f = candidateSdkFixture(); + const mergeSha = "c".repeat(40); + const pr = Object.assign(f.pr, { merge_commit_sha: mergeSha }); + const sources = Object.fromEntries( + Object.entries(f.sources).map(([path, source]) => [ + path, + path === "ci/reviewed-npm-audit.json" + ? source + : JSON.stringify({ ...JSON.parse(source), description: "A change from the approved base" }), + ]), + ); + const preparation = candidateSdkCheckout(root, { ...f, sources }); + const commit = { + sha: mergeSha, + parents: [{ sha: sdkCandidateIdentity.baseSha }, { sha: sdkCandidateIdentity.candidateSha }], + }; + const request = async (route: string): Promise => { + if (route.endsWith(`/git/commits/${mergeSha}`)) return commit; + if (route.endsWith(`?ref=${mergeSha}`)) { + const path = route.split("/contents/")[1]!.split("?")[0]!; + const source = sources[path]!; + return { + type: "file", + path, + encoding: "base64", + size: Buffer.byteLength(source), + content: Buffer.from(source).toString("base64"), + }; + } + return f.request(route); + }; + const writeMerged = (path: string, source: string) => { + sources[path] = source; + writeFileSync(join(root, path), source); + }; + return { + ...f, + pr, + preparation, + sources, + request: vi.fn(request), + commit, + identity: { ...sdkCandidateIdentity, mergeSha }, + writeMerged, + stage: vi.fn(), + }; +} + export function sparseSdkWorkflowCheckout(root: string, workflowPath: string, job: string) { const workflow = YAML.parse(readFileSync(workflowPath, "utf8")); const checkouts = workflow.jobs[job].steps.filter( diff --git a/tools/e2e/candidate-upgrade-admission.mts b/tools/e2e/candidate-upgrade-admission.mts index 501aa2d03c6..2b075ac6f18 100644 --- a/tools/e2e/candidate-upgrade-admission.mts +++ b/tools/e2e/candidate-upgrade-admission.mts @@ -34,11 +34,17 @@ function assertIdentity(identity: CandidateUpgradeIdentity): void { throw new Error("Upgrade admission requires a PR number and immutable candidate/base commits"); } -function assertPullRequest(value: unknown, identity: CandidateUpgradeIdentity): string { +function assertPullRequest( + value: unknown, + identity: CandidateUpgradeIdentity, + mergeSha?: string, +): string { const pr = record(value); const head = record(pr.head); const base = record(pr.base); const author = record(pr.user); + if (mergeSha !== undefined && pr.merge_commit_sha !== mergeSha) + throw new Error("Upgrade admission no longer matches the GitHub merge commit"); if ( pr.number !== identity.prNumber || pr.state !== "open" || @@ -170,10 +176,13 @@ export async function readApprovedCandidateUpgrade( input: CandidateUpgradeIdentity, paths: readonly string[], request: UpgradeRequest, + mergeSha?: string, ): Promise<{ sources: Readonly>; reviewer: string; commentId: number }> { const identity = Object.freeze({ ...input }); const selection = [...paths]; assertIdentity(identity); + if (mergeSha !== undefined && !SHA.test(mergeSha)) + throw new Error("Upgrade admission requires an immutable merge commit"); if ( selection.length === 0 || selection.length > 32 || @@ -182,12 +191,29 @@ export async function readApprovedCandidateUpgrade( throw new Error("Upgrade admission requires a bounded, unique source selection"); } const prPath = `${PREFIX}/pulls/${identity.prNumber}`; - const author = assertPullRequest(await request(prPath), identity); + const author = assertPullRequest(await request(prPath), identity, mergeSha); const before = await currentDecision(request, identity, author); + if (mergeSha !== undefined) { + const merge = record(await request(`${PREFIX}/git/commits/${mergeSha}`)); + if ( + merge.sha !== mergeSha || + !Array.isArray(merge.parents) || + merge.parents.length !== 2 || + record(merge.parents[0]).sha !== identity.baseSha || + record(merge.parents[1]).sha !== identity.candidateSha + ) + throw new Error( + "Upgrade admission merge parents differ from the approved base and candidate; synchronize the PR and refresh its commit-bound approval", + ); + } const sources: Record = Object.create(null); for (const path of selection) - sources[path] = await readCandidateUpgradeSource(request, identity.candidateSha, path); - if (assertPullRequest(await request(prPath), identity) !== author) { + sources[path] = await readCandidateUpgradeSource( + request, + mergeSha ?? identity.candidateSha, + path, + ); + if (assertPullRequest(await request(prPath), identity, mergeSha) !== author) { throw new Error("Upgrade admission PR author changed during source acquisition"); } const after = await currentDecision(request, identity, author); From fe02e57e89c856c3bb6f2893873d7012fb7c4ca5 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 15:54:40 -0700 Subject: [PATCH 07/11] ci(images): qualify PR managed images on native ARM64 Signed-off-by: Prekshi Vyas --- .github/workflows/managed-images.yaml | 49 +-- scripts/checks/resolve-managed-pr-base.sh | 19 +- test/e2e/README.md | 12 +- .../pr-managed-image-publication.test.ts | 315 +++++++++++------- ...anaged-image-publication-workflow-types.ts | 2 +- .../managed-image-pr-base-resolution.test.ts | 302 ++++++++++++----- ...managed-image-publication-workflow.test.ts | 139 ++------ tools/e2e/pr-managed-image-publication.mts | 45 ++- 8 files changed, 526 insertions(+), 357 deletions(-) diff --git a/.github/workflows/managed-images.yaml b/.github/workflows/managed-images.yaml index 7a17e76c6cd..5053445fa8c 100644 --- a/.github/workflows/managed-images.yaml +++ b/.github/workflows/managed-images.yaml @@ -426,7 +426,7 @@ jobs: fi pr-build-and-entrypoint: - name: PR build and direct managed startup (${{ matrix.display_name }}) + name: PR build and direct managed startup (${{ matrix.display_name }}, ${{ matrix.arch }}) # External contributor PRs retain the local build/direct-startup lane after # GitHub's maintainer workflow approval. Exact digest publication is limited # to branches in NVIDIA/NemoClaw; fork jobs never log in or push. @@ -434,16 +434,19 @@ jobs: - pr-reviewed-npm-audit - publication-identity if: github.event_name == 'pull_request' - runs-on: ubuntu-24.04 + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} timeout-minutes: 90 permissions: contents: read packages: write env: CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} + PLATFORM: linux/${{ matrix.arch }} strategy: fail-fast: false matrix: + agent: [openclaw, hermes, langchain-deepagents-code] + arch: [amd64, arm64] include: - agent: openclaw display_name: OpenClaw @@ -624,7 +627,7 @@ jobs: shell: bash run: scripts/check-production-build-args.sh -f agents/langchain-deepagents-code/Dockerfile.base - - name: Resolve digest-pinned linux/amd64 PR base + - name: Resolve digest-pinned native PR base id: base shell: bash env: @@ -636,7 +639,6 @@ jobs: CANDIDATE_SHA: ${{ github.event.pull_request.head.sha }} DISPLAY_NAME: ${{ matrix.display_name }} LOCAL_BASE_REFERENCE: nemoclaw-managed-pr/${{ matrix.agent }}-base:${{ github.event.pull_request.head.sha }} - PLATFORM: linux/amd64 run: scripts/checks/resolve-managed-pr-base.sh - name: Validate PR managed-image build args @@ -693,7 +695,7 @@ jobs: ) fi docker build \ - --platform linux/amd64 \ + --platform "$PLATFORM" \ --file "$DOCKERFILE" \ --tag "$IMAGE_REFERENCE" \ --label "org.opencontainers.image.source=https://github.com/${GITHUB_REPOSITORY}" \ @@ -701,7 +703,7 @@ jobs: --label "org.opencontainers.image.version=${RELEASE}" \ --label "io.nvidia.nemoclaw.agent=${{ matrix.agent }}" \ --label "io.nvidia.nemoclaw.managed-image.contract=1" \ - --label "io.nvidia.nemoclaw.managed-image.platform=linux/amd64" \ + --label "io.nvidia.nemoclaw.managed-image.platform=${PLATFORM}" \ --label "io.nvidia.nemoclaw.managed-image.startup-profile=1" \ --label "io.nvidia.nemoclaw.managed-image.capabilities=1" \ --label "io.nvidia.nemoclaw.managed-image.cohort=${PUBLICATION_COHORT}" \ @@ -718,7 +720,7 @@ jobs: with: context: . file: ${{ matrix.dockerfile }} - platforms: linux/amd64 + platforms: linux/${{ matrix.arch }} load: true push: false tags: ${{ matrix.image }}:${{ github.event.pull_request.head.sha }} @@ -728,7 +730,7 @@ jobs: org.opencontainers.image.version=${{ steps.release.outputs.value }} io.nvidia.nemoclaw.agent=${{ matrix.agent }} io.nvidia.nemoclaw.managed-image.contract=1 - io.nvidia.nemoclaw.managed-image.platform=linux/amd64 + io.nvidia.nemoclaw.managed-image.platform=linux/${{ matrix.arch }} io.nvidia.nemoclaw.managed-image.startup-profile=1 io.nvidia.nemoclaw.managed-image.capabilities=1 io.nvidia.nemoclaw.managed-image.cohort=${{ needs.publication-identity.outputs.cohort }} @@ -744,7 +746,7 @@ jobs: ${{ matrix.agent == 'openclaw' && format('nemoclaw-mcporter-audit-receipt={0}', steps.mcporter-audit.outputs.receipt) || '' }} ${{ matrix.agent == 'openclaw' && format('nemoclaw-mcporter-audit-raw-report={0}', steps.mcporter-audit.outputs.raw) || '' }} ${{ matrix.agent == 'openclaw' && format('nemoclaw-mcporter-audit-policy-result={0}', steps.mcporter-audit.outputs.policy) || '' }} - cache-from: type=registry,ref=ghcr.io/nvidia/nemoclaw/${{ matrix.agent }}-sandbox:buildcache-linux-amd64 + cache-from: type=registry,ref=ghcr.io/nvidia/nemoclaw/${{ matrix.agent }}-sandbox:buildcache-linux-${{ matrix.arch }} provenance: false sbom: false @@ -754,7 +756,6 @@ jobs: env: AGENT: ${{ matrix.agent }} IMAGE_REFERENCE: ${{ matrix.image }}:${{ github.event.pull_request.head.sha }} - PLATFORM: linux/amd64 PUBLICATION_COHORT: ${{ needs.publication-identity.outputs.cohort }} RELEASE: ${{ steps.release.outputs.value }} RESOLUTION_KEY: ${{ steps.base.outputs.resolution_key }} @@ -938,7 +939,7 @@ jobs: scripts/checks/run-managed-image-direct-e2e.ts \ --agent "$AGENT" \ --image "$IMAGE_REFERENCE" \ - --platform linux/amd64 + --platform "$PLATFORM" - name: Log in to GHCR for exact same-repository PR digest if: github.event.pull_request.head.repo.full_name == github.repository @@ -958,7 +959,7 @@ jobs: builder: ${{ steps.buildx.outputs.name }} context: . file: ${{ matrix.dockerfile }} - platforms: linux/amd64 + platforms: linux/${{ matrix.arch }} build-contexts: ${{ steps.base.outputs.local == 'true' && format('nemoclaw-pr-base=oci-layout://{0}', steps.base.outputs.oci) || '' }} outputs: type=image,name=${{ matrix.repository }},push-by-digest=true,name-canonical=true,push=true labels: | @@ -967,7 +968,7 @@ jobs: org.opencontainers.image.version=${{ steps.release.outputs.value }} io.nvidia.nemoclaw.agent=${{ matrix.agent }} io.nvidia.nemoclaw.managed-image.contract=1 - io.nvidia.nemoclaw.managed-image.platform=linux/amd64 + io.nvidia.nemoclaw.managed-image.platform=linux/${{ matrix.arch }} io.nvidia.nemoclaw.managed-image.startup-profile=1 io.nvidia.nemoclaw.managed-image.capabilities=1 io.nvidia.nemoclaw.managed-image.cohort=${{ needs.publication-identity.outputs.cohort }} @@ -983,7 +984,7 @@ jobs: ${{ matrix.agent == 'openclaw' && format('nemoclaw-mcporter-audit-receipt={0}', steps.mcporter-audit.outputs.receipt) || '' }} ${{ matrix.agent == 'openclaw' && format('nemoclaw-mcporter-audit-raw-report={0}', steps.mcporter-audit.outputs.raw) || '' }} ${{ matrix.agent == 'openclaw' && format('nemoclaw-mcporter-audit-policy-result={0}', steps.mcporter-audit.outputs.policy) || '' }} - cache-from: type=registry,ref=ghcr.io/nvidia/nemoclaw/${{ matrix.agent }}-sandbox:buildcache-linux-amd64 + cache-from: type=registry,ref=ghcr.io/nvidia/nemoclaw/${{ matrix.agent }}-sandbox:buildcache-linux-${{ matrix.arch }} provenance: false sbom: false @@ -1015,7 +1016,7 @@ jobs: } reference="${IMAGE}@${DIGEST}" raw="$RUNNER_TEMP/${AGENT}-published-manifest.raw" - scripts/checks/pull-public-exact-digest.sh "$reference" linux/amd64 + scripts/checks/pull-public-exact-digest.sh "$reference" "$PLATFORM" if [ "$AGENT" = "hermes" ]; then published_layer_count="$(docker image inspect --format '{{len .RootFS.Layers}}' "$reference")" if [ "$published_layer_count" -gt 125 ]; then @@ -1051,12 +1052,13 @@ jobs: --arg digest "$DIGEST" \ --arg image "$IMAGE" \ --arg reference "$reference" \ + --arg platform "$PLATFORM" \ --arg release "$RELEASE" \ --arg revision "$CANDIDATE_SHA" \ '{ contractVersion: 1, agent: $agent, - platform: "linux/amd64", + platform: $platform, image: $image, digest: $digest, reference: $reference, @@ -1074,17 +1076,21 @@ jobs: if: github.event.pull_request.head.repo.full_name == github.repository uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: managed-pr-contract-${{ github.run_id }}-${{ matrix.agent }} + name: managed-pr-contract-${{ matrix.arch == 'arm64' && 'arm64-' || '' }}${{ github.run_id }}-${{ matrix.agent }} path: ${{ runner.temp }}/managed-pr-contract/contract.json if-no-files-found: error overwrite: true retention-days: 1 pr-managed-activation: - name: PR exact all-agent managed runtime activation + name: PR exact all-agent managed runtime activation (${{ matrix.arch }}) needs: [pr-build-and-entrypoint, publication-identity] if: github.event_name == 'pull_request' && github.event.pull_request.head.repo.full_name == github.repository - runs-on: ubuntu-24.04 + runs-on: ${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }} + strategy: + fail-fast: false + matrix: + arch: [amd64, arm64] timeout-minutes: 90 permissions: contents: read @@ -1097,6 +1103,7 @@ jobs: NEMOCLAW_E2E_EXPECTED_SHA: ${{ github.event.pull_request.head.sha }} NEMOCLAW_E2E_SHARD: default NEMOCLAW_MANAGED_ACTIVATION_CATALOG: ${{ github.workspace }}/managed-pr-catalog.json + MANAGED_IMAGE_PLATFORM: linux/${{ matrix.arch }} NEMOCLAW_NON_INTERACTIVE: "1" NEMOCLAW_RUN_LIVE_E2E: "1" OPENSHELL_GATEWAY: nemoclaw @@ -1128,7 +1135,7 @@ jobs: - name: Download exact published all-agent contracts uses: actions/download-artifact@3e5f45b2cfb9172054b4087a40e8e0b5a5461e7c # v8.0.1 with: - pattern: managed-pr-contract-${{ github.run_id }}-* + pattern: managed-pr-contract-${{ matrix.arch == 'arm64' && 'arm64-' || '' }}${{ github.run_id }}-* path: ${{ runner.temp }}/managed-pr-contracts merge-multiple: false @@ -1195,7 +1202,7 @@ jobs: if: always() uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1 with: - name: managed-image-activation-${{ github.run_id }}-${{ github.run_attempt }} + name: managed-image-activation-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.arch }} path: e2e-artifacts/live/managed-image-activation/ if-no-files-found: error retention-days: 1 diff --git a/scripts/checks/resolve-managed-pr-base.sh b/scripts/checks/resolve-managed-pr-base.sh index f7132395f88..46dc671433e 100755 --- a/scripts/checks/resolve-managed-pr-base.sh +++ b/scripts/checks/resolve-managed-pr-base.sh @@ -3,6 +3,13 @@ # SPDX-License-Identifier: Apache-2.0 set -euo pipefail +case "${PLATFORM:-}" in + linux/amd64 | linux/arm64) ;; + *) + echo "ERROR: PR base resolution requires a supported Linux platform (linux/amd64 or linux/arm64)." >&2 + exit 1 + ;; +esac write_dcode_resolution() { [ "$AGENT" = "langchain-deepagents-code" ] || return 0 local identity_ref="$1" inspect_ref="$2" expected_revision="$3" @@ -56,7 +63,7 @@ build_local_base() { local local_base_oci_archive="$RUNNER_TEMP/pr-base.oci.tar" local local_base_oci="$RUNNER_TEMP/pr-base.oci" docker buildx build \ - --platform linux/amd64 \ + --platform "$PLATFORM" \ --provenance=false \ --sbom=false \ --file "$BASE_DOCKERFILE" \ @@ -179,7 +186,7 @@ alias_raw="$RUNNER_TEMP/pr-base-alias.raw" exact_raw="$RUNNER_TEMP/pr-base-exact.raw" docker buildx imagetools inspect "$BASE_ALIAS" --raw >"$alias_raw" if ! digest="$( - jq -er ' + jq -er --arg architecture "${PLATFORM#linux/}" ' if ( .mediaType == "application/vnd.oci.image.index.v1+json" or .mediaType == "application/vnd.docker.distribution.manifest.list.v2+json" @@ -188,20 +195,20 @@ if ! digest="$( .manifests[] | select( .platform.os == "linux" and - .platform.architecture == "amd64" + .platform.architecture == $architecture ) ] - | if length == 1 then .[0].digest else error("not one linux/amd64 image") end + | if length == 1 then .[0].digest else error("not one requested platform image") end else error("base alias is not a platform index") end ' "$alias_raw" )"; then - echo "ERROR: PR base alias does not contain exactly one linux/amd64 image." >&2 + echo "ERROR: PR base alias does not contain exactly one ${PLATFORM} image." >&2 exit 1 fi if [[ ! "$digest" =~ ^sha256:[0-9a-f]{64}$ ]]; then - echo "ERROR: PR base alias returned an invalid linux/amd64 digest." >&2 + echo "ERROR: PR base alias returned an invalid ${PLATFORM} digest." >&2 exit 1 fi reference="${BASE_REPOSITORY}@${digest}" diff --git a/test/e2e/README.md b/test/e2e/README.md index 1e061d84beb..758dbe5725d 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -191,6 +191,14 @@ 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. +PR image publication builds each shipped agent on native AMD64 and ARM64 runners. +Each platform retains its own digest contract and runs the direct startup checks. +Docker activation selects the matching platform catalog and runs the existing all-agent lifecycle test. +Rootless Podman activation remains AMD64. The catalog reader accepts only one platform per catalog; +it rejects missing agents, mixed platforms, revisions, releases, and cohorts. +AMD64 artifact names remain unchanged. ARM64 artifacts use the `managed-pr-contract-arm64-` prefix. +`MANAGED_IMAGE_PLATFORM=linux/arm64` selects them in the trusted catalog resolver and assembly command. + 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, @@ -265,7 +273,7 @@ If CI starts before the approved artifact exists, wait for the admission workflo SDK job, then rerun CI. Changed or revoked approval cannot reuse the older artifact. This does not yet extend the protected runtime's source projection, permit a new -SDK graph on protected E2E hosts, qualify Pi, or add ARM64 candidate catalogs. A data-admission +SDK graph on protected E2E hosts, qualify Pi, or pass candidate catalogs to the Jetson operator. A data-admission comment is not permission to execute arbitrary candidate code on a protected host. Those boundaries require their own supported implementation and validation; passing the hash check is not full E2E qualification. @@ -274,7 +282,7 @@ Unchanged runs pass the selected base revision and complete cohort receipt to ev Changed-input runs pass the authenticated candidate catalog separately to those consumers. The candidate CLI artifact cannot contain the catalog. The GitHub token remains available only to the trusted planner and is not included in the candidate CLI artifact. -The candidate catalog qualifies `linux/amd64` only, so a changed-input manual PR run does not dispatch the Jetson target. +The manual E2E planner still selects the AMD64 candidate catalog and does not dispatch changed-input PR runs to Jetson. The trusted publication job reports this exclusion before the Jetson job is skipped. The same-repository `Images / Build, Test, and Publish Managed Images` PR workflow also runs the diff --git a/test/e2e/support/pr-managed-image-publication.test.ts b/test/e2e/support/pr-managed-image-publication.test.ts index 338393ec6d1..48d0f9201a2 100644 --- a/test/e2e/support/pr-managed-image-publication.test.ts +++ b/test/e2e/support/pr-managed-image-publication.test.ts @@ -17,6 +17,7 @@ import { SHIPPED_MANAGED_IMAGE_AGENTS, type ManagedImageAgent, type ManagedImageContractV1, + type ManagedImagePlatform, } from "../../../src/lib/onboard/managed-image/contract"; import { githubRequest } from "../../../tools/e2e/base-image-publication.mts"; import { @@ -24,7 +25,6 @@ import { main, resolvePrManagedImageCatalog, selectManagedImagePublicationRun, - writeManagedImageCatalog, } from "../../../tools/e2e/pr-managed-image-publication.mts"; import { artifactZip } from "../../helpers/artifact-zip"; @@ -52,13 +52,14 @@ function contractForCohort( agent: ManagedImageAgent, index: number, cohort: ManagedImageContractV1["source"]["cohort"], + platform: ManagedImagePlatform = "linux/amd64", ): ManagedImageContractV1 { const image = MANAGED_IMAGE_REPOSITORIES[agent]; const digest = `sha256:${String(index + 1).repeat(64)}` as const; return { contractVersion: MANAGED_IMAGE_CONTRACT_VERSION, agent, - platform: "linux/amd64", + platform, image, digest, reference: `${image}@${digest}`, @@ -73,13 +74,21 @@ function contractForCohort( }; } -function contract(agent: ManagedImageAgent, index: number): ManagedImageContractV1 { - return contractForCohort(agent, index, `ghrun-${RUN_ID}-1`); +function contract( + agent: ManagedImageAgent, + index: number, + platform: ManagedImagePlatform = "linux/amd64", +): ManagedImageContractV1 { + return contractForCohort(agent, index, `ghrun-${RUN_ID}-1`, platform); } -function contractArchive(agent: ManagedImageAgent, index: number): Buffer { +function contractArchive( + agent: ManagedImageAgent, + index: number, + platform: ManagedImagePlatform = "linux/amd64", +): Buffer { return artifactZip([ - { name: "contract.json", contents: `${JSON.stringify(contract(agent, index))}\n` }, + { name: "contract.json", contents: `${JSON.stringify(contract(agent, index, platform))}\n` }, ]); } @@ -118,6 +127,7 @@ function candidateRequest(options: { readonly artifactHeadSha?: string; readonly artifactRunId?: number; readonly missingAgent?: ManagedImageAgent; + readonly platform?: ManagedImagePlatform; }) { const candidateRepository = options.candidateRepository ?? CANONICAL_REPOSITORY; const changedPath = options.changedPath ?? "Dockerfile.base"; @@ -171,8 +181,8 @@ function candidateRequest(options: { responses.set(`${runsPath}&page=${index + 1}`, page); } for (const [index, agent] of SHIPPED_MANAGED_IMAGE_AGENTS.entries()) { - const name = `managed-pr-contract-${artifactRunId}-${agent}`; - const archive = contractArchive(agent, index); + const name = `managed-pr-contract-${options.platform === "linux/arm64" ? "arm64-" : ""}${artifactRunId}-${agent}`; + const archive = contractArchive(agent, index, options.platform); const id = index + 100; responses.set( `/repos/${CANONICAL_REPOSITORY}/actions/runs/${artifactRunId}/artifacts?name=${encodeURIComponent(name)}&per_page=100`, @@ -226,7 +236,14 @@ function downloadContract( artifactZip([ { name: "contract.json", - contents: `${JSON.stringify(contractForCohort(agent, index, cohort))}\n`, + contents: `${JSON.stringify( + contractForCohort( + agent, + index, + cohort, + identity.name.startsWith("managed-pr-contract-arm64-") ? "linux/arm64" : "linux/amd64", + ), + )}\n`, }, ]), ); @@ -325,82 +342,118 @@ describe("exact PR managed-image publication", () => { expect(fs.existsSync(input.outputPath)).toBe(false); }); - it("writes one exact candidate catalog after an immutable image-input change", async () => { - const input = resolverInput(); + it.each(["linux/amd64", "linux/arm64"] as const)( + "writes an exact %s catalog after an image-input change", + async (platform) => { + const input = { ...resolverInput(), platform }; - await expect( - resolvePrManagedImageCatalog( - input, - candidateRequest({ imageChanged: true }), - downloadContract, - ), - ).resolves.toBe("candidate-catalog"); - expect(JSON.parse(fs.readFileSync(input.outputPath, "utf8"))).toEqual( - Object.fromEntries( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [agent, contract(agent, index)]), - ), - ); - expect(fs.statSync(input.outputPath).mode & 0o777).toBe(0o600); - }); + await expect( + resolvePrManagedImageCatalog( + input, + candidateRequest({ imageChanged: true, platform }), + downloadContract, + ), + ).resolves.toBe("candidate-catalog"); + expect(JSON.parse(fs.readFileSync(input.outputPath, "utf8"))).toEqual( + Object.fromEntries( + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [ + agent, + contract(agent, index, platform), + ]), + ), + ); + expect(fs.statSync(input.outputPath).mode & 0o777).toBe(0o600); + }, + ); - it("keeps artifact download evidence out of the machine-readable selection", async () => { - const input = resolverInput(); - const apiRequest = candidateRequest({ imageChanged: true }); - const artifactResponses = new Map( - SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { - const archive = contractArchive(agent, index); - return [ - `/repos/${CANONICAL_REPOSITORY}/actions/artifacts/${index + 100}/zip`, - new Response(new Uint8Array(archive), { - status: 200, - headers: { "content-length": String(archive.length) }, - }), - ] as const; - }), - ); - let standardOutput = ""; - let standardError = ""; - vi.spyOn(process.stdout, "write").mockImplementation(((chunk: string | Uint8Array) => { - standardOutput += chunk.toString(); - return true; - }) as typeof process.stdout.write); - vi.spyOn(console, "log").mockImplementation((...values: unknown[]) => { - standardOutput += `${values.map(String).join(" ")}\n`; - }); - vi.spyOn(process.stderr, "write").mockImplementation(((chunk: string | Uint8Array) => { - standardError += chunk.toString(); - return true; - }) as typeof process.stderr.write); - vi.spyOn(console, "error").mockImplementation((...values: unknown[]) => { - standardError += `${values.map(String).join(" ")}\n`; - }); - vi.stubGlobal( - "fetch", - vi.fn(async (request: string | URL | Request) => { - const url = new URL(String(request)); - return ( - artifactResponses.get(url.pathname) ?? - Response.json(await apiRequest(`${url.pathname}${url.search}`)) - ); - }), - ); + it.each(["linux/amd64", "linux/arm64"] as const)( + "keeps %s download evidence out of the machine-readable selection", + async (platform) => { + const input = resolverInput(); + const apiRequest = candidateRequest({ imageChanged: true, platform }); + const artifactResponses = new Map( + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { + const archive = contractArchive(agent, index, platform); + return [ + `/repos/${CANONICAL_REPOSITORY}/actions/artifacts/${index + 100}/zip`, + new Response(new Uint8Array(archive), { + status: 200, + headers: { "content-length": String(archive.length) }, + }), + ] as const; + }), + ); + let standardOutput = ""; + let standardError = ""; + vi.spyOn(process.stdout, "write").mockImplementation(((chunk: string | Uint8Array) => { + standardOutput += chunk.toString(); + return true; + }) as typeof process.stdout.write); + vi.spyOn(console, "log").mockImplementation((...values: unknown[]) => { + standardOutput += `${values.map(String).join(" ")}\n`; + }); + vi.spyOn(process.stderr, "write").mockImplementation(((chunk: string | Uint8Array) => { + standardError += chunk.toString(); + return true; + }) as typeof process.stderr.write); + vi.spyOn(console, "error").mockImplementation((...values: unknown[]) => { + standardError += `${values.map(String).join(" ")}\n`; + }); + vi.stubGlobal( + "fetch", + vi.fn(async (request: string | URL | Request) => { + const url = new URL(String(request)); + return ( + artifactResponses.get(url.pathname) ?? + Response.json(await apiRequest(`${url.pathname}${url.search}`)) + ); + }), + ); - await main([input.outputPath], { - BASE_SHA, - CANDIDATE_REPOSITORY: CANONICAL_REPOSITORY, - CANDIDATE_SHA, - GITHUB_TOKEN: "test-token", - PR_NUMBER: String(PR_NUMBER), - }); - - const artifactEvidence = Array.from( - { length: SHIPPED_MANAGED_IMAGE_AGENTS.length }, - () => "artifact-content-read attempt=1 outcome=passed-first-attempt\n", - ).join(""); - expect(standardOutput).toBe("candidate-catalog\n"); - expect(standardOutput).not.toContain("artifact-content-read"); - expect(standardError).toBe(artifactEvidence); - }); + await main([input.outputPath], { + BASE_SHA, + CANDIDATE_REPOSITORY: CANONICAL_REPOSITORY, + CANDIDATE_SHA, + GITHUB_TOKEN: "test-token", + MANAGED_IMAGE_PLATFORM: platform, + PR_NUMBER: String(PR_NUMBER), + }); + + const artifactEvidence = Array.from( + { length: SHIPPED_MANAGED_IMAGE_AGENTS.length }, + () => "artifact-content-read attempt=1 outcome=passed-first-attempt\n", + ).join(""); + expect(standardOutput).toBe("candidate-catalog\n"); + expect(standardOutput).not.toContain("artifact-content-read"); + expect(standardError).toBe(artifactEvidence); + expect(JSON.parse(fs.readFileSync(input.outputPath, "utf8"))).toEqual( + Object.fromEntries( + SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => [ + agent, + contract(agent, index, platform), + ]), + ), + ); + }, + ); + + it.each(["", "linux/s390x", "windows/amd64"])( + "rejects CLI platform %s before reading contracts or fetching artifacts", + async (platform) => { + const fetch = vi.fn(); + vi.stubGlobal("fetch", fetch); + const input = resolverInput(); + const env = { MANAGED_IMAGE_PLATFORM: platform }; + await expect(main([input.outputPath], env)).rejects.toThrow( + "unsupported managed-image platform", + ); + await expect( + main(["assemble", CANDIDATE_SHA, input.outputPath, "missing-contract.json"], env), + ).rejects.toThrow("unsupported managed-image platform"); + expect(fetch).not.toHaveBeenCalled(); + expect(fs.existsSync(input.outputPath)).toBe(false); + }, + ); it("selects a candidate catalog when only managed-image onboarding runtime changes", async () => { const input = resolverInput(); @@ -418,31 +471,35 @@ describe("exact PR managed-image publication", () => { expect(fs.existsSync(input.outputPath)).toBe(true); }); - it("uses one serialization contract for assembled and resolved candidate catalogs", async () => { - const input = resolverInput(); - await resolvePrManagedImageCatalog( - input, - candidateRequest({ imageChanged: true }), - downloadContract, - ); + it.each(["linux/amd64", "linux/arm64"] as const)( + "serializes the same %s catalog through CLI assembly and resolution", + async (platform) => { + const input = { ...resolverInput(), platform }; + await resolvePrManagedImageCatalog( + input, + candidateRequest({ imageChanged: true, platform }), + downloadContract, + ); - const assemblyRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-assembly-")); - temporaryDirectories.push(assemblyRoot); - const contractPaths = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { - const contractPath = path.join(assemblyRoot, `${agent}.json`); - fs.writeFileSync(contractPath, JSON.stringify(contract(agent, index)), "utf8"); - return contractPath; - }); - const assembledPath = path.join(assemblyRoot, "assembled", "catalog.json"); - writeManagedImageCatalog(contractPaths, CANDIDATE_SHA, assembledPath, { - id: RUN_ID, - attempt: 1, - }); - - expect(fs.readFileSync(assembledPath)).toEqual(fs.readFileSync(input.outputPath)); - expect(fs.statSync(assembledPath).mode & 0o777).toBe(0o600); - expect(fs.statSync(input.outputPath).mode & 0o777).toBe(0o600); - }); + const assemblyRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-catalog-assembly-")); + temporaryDirectories.push(assemblyRoot); + const contractPaths = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => { + const contractPath = path.join(assemblyRoot, `${agent}.json`); + fs.writeFileSync(contractPath, JSON.stringify(contract(agent, index, platform)), "utf8"); + return contractPath; + }); + const assembledPath = path.join(assemblyRoot, "assembled", "catalog.json"); + await main(["assemble", CANDIDATE_SHA, assembledPath, ...contractPaths], { + GITHUB_RUN_ID: String(RUN_ID), + GITHUB_RUN_ATTEMPT: "1", + MANAGED_IMAGE_PLATFORM: platform, + }); + + expect(fs.readFileSync(assembledPath)).toEqual(fs.readFileSync(input.outputPath)); + expect(fs.statSync(assembledPath).mode & 0o777).toBe(0o600); + expect(fs.statSync(input.outputPath).mode & 0o777).toBe(0o600); + }, + ); it("rejects an image-changing fork before any artifact download", async () => { const candidateRepository = "external-contributor/NemoClaw"; @@ -609,18 +666,21 @@ describe("exact PR managed-image publication", () => { expect(download).not.toHaveBeenCalled(); }); - it("rejects an incomplete exact-candidate artifact set", async () => { - const download = vi.fn(downloadContract); + it.each(["linux/amd64", "linux/arm64"] as const)( + "rejects an incomplete %s candidate artifact set", + async (platform) => { + const download = vi.fn(downloadContract); - await expect( - resolvePrManagedImageCatalog( - resolverInput(), - candidateRequest({ imageChanged: true, missingAgent: "hermes" }), - download, - ), - ).rejects.toThrow("exact artifact identity is missing or ambiguous"); - expect(download).toHaveBeenCalledTimes(1); - }); + await expect( + resolvePrManagedImageCatalog( + { ...resolverInput(), platform }, + candidateRequest({ imageChanged: true, missingAgent: "hermes", platform }), + download, + ), + ).rejects.toThrow("exact artifact identity is missing or ambiguous"); + expect(download).toHaveBeenCalledTimes(1); + }, + ); it.each([ [ @@ -660,7 +720,7 @@ describe("exact PR managed-image publication", () => { }); it("rejects mixed candidate revisions in an all-agent catalog", () => { - const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map(contract); + const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => contract(agent, index)); const substituted = { ...contracts[0], source: { ...contracts[0]!.source, revision: "f".repeat(40) }, @@ -688,6 +748,25 @@ describe("exact PR managed-image publication", () => { }); describe("PR managed-image contract reruns", () => { + it.each(["linux/amd64", "linux/arm64"] as const)( + "assembles only the requested %s cohort", + (platform) => { + const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => + contract(agent, index, platform), + ); + const run = { id: RUN_ID, attempt: 1 }; + expect(assembleManagedImageCatalog(contracts, CANDIDATE_SHA, run, platform)).toEqual( + Object.fromEntries(contracts.map((value) => [value.agent, value])), + ); + const foreign = { + ...contracts[0], + platform: platform === "linux/amd64" ? "linux/arm64" : "linux/amd64", + }; + expect(() => + assembleManagedImageCatalog([foreign, ...contracts.slice(1)], CANDIDATE_SHA, run, platform), + ).toThrow(/platform/); + }, + ); it("accepts one producer-owned cohort after a partial producer rerun", () => { const contracts = SHIPPED_MANAGED_IMAGE_AGENTS.map((agent, index) => contractForCohort(agent, index, `ghrun-${RUN_ID}-1`), diff --git a/test/helpers/managed-image-publication-workflow-types.ts b/test/helpers/managed-image-publication-workflow-types.ts index 72958afb3b3..fd4f553eed0 100644 --- a/test/helpers/managed-image-publication-workflow-types.ts +++ b/test/helpers/managed-image-publication-workflow-types.ts @@ -45,7 +45,7 @@ export type Job = { steps?: Step[]; strategy?: { "fail-fast"?: boolean; - matrix?: { include?: MatrixEntry[]; pass?: number[] }; + matrix?: { include?: MatrixEntry[]; pass?: number[]; agent?: string[]; arch?: string[] }; }; "timeout-minutes"?: number; uses?: string; 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 991dde3b1b0..45879c5cec5 100644 --- a/test/inference/managed/managed-image-pr-base-resolution.test.ts +++ b/test/inference/managed/managed-image-pr-base-resolution.test.ts @@ -12,35 +12,158 @@ import { expect, it } from "vitest"; const repoRoot = path.resolve(import.meta.dirname, "../../.."); const resolver = path.join(repoRoot, "scripts/checks/resolve-managed-pr-base.sh"); -it("builds a changed PR base locally and fails closed on comparison errors", () => { - const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-local-pr-base-")); - const fakeBin = path.join(temporaryRoot, "bin"); - const output = path.join(temporaryRoot, "output"); - const summary = path.join(temporaryRoot, "summary"); - const dockerLog = path.join(temporaryRoot, "docker.log"); - fs.mkdirSync(fakeBin); - const runGit = (...args: string[]) => { - const result = spawnSync("git", args, { cwd: temporaryRoot, encoding: "utf8" }); - expect(result.status, result.stderr).toBe(0); - return result.stdout.trim(); - }; - runGit("init", "--quiet"); - runGit("config", "user.name", "NemoClaw Test"); - runGit("config", "user.email", "nemoclaw-test@example.invalid"); - fs.writeFileSync(path.join(temporaryRoot, "Dockerfile.base"), "FROM scratch\n"); - runGit("add", "Dockerfile.base"); - runGit("commit", "--quiet", "-m", "test: add base"); - const baseSha = runGit("rev-parse", "HEAD"); - fs.writeFileSync( - path.join(temporaryRoot, "Dockerfile.base"), - "FROM scratch\nLABEL test=changed\n", - ); - runGit("add", "Dockerfile.base"); - runGit("commit", "--quiet", "-m", "test: change base"); - const candidateSha = runGit("rev-parse", "HEAD"); - fs.writeFileSync( - path.join(fakeBin, "docker"), - `#!/bin/bash +it.each(["amd64", "arm64"])( + "pins one %s PR base descriptor and rejects torn index evidence", + (architecture) => { + const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-base-")); + const fakeBin = path.join(temporaryRoot, "bin"); + const aliasRaw = path.join(temporaryRoot, "alias.raw"); + const exactRaw = path.join(temporaryRoot, "exact.raw"); + const output = path.join(temporaryRoot, "output"); + const summary = path.join(temporaryRoot, "summary"); + fs.mkdirSync(fakeBin); + const exactBody = JSON.stringify({ + schemaVersion: 2, + mediaType: "application/vnd.oci.image.manifest.v1+json", + config: { digest: `sha256:${"a".repeat(64)}`, size: 1 }, + layers: [], + }); + const digest = `sha256:${createHash("sha256").update(exactBody).digest("hex")}`; + const descriptor = { + mediaType: "application/vnd.oci.image.manifest.v1+json", + digest, + size: exactBody.length, + platform: { os: "linux", architecture }, + }; + const writeAlias = (manifests: unknown[]) => { + fs.writeFileSync( + aliasRaw, + JSON.stringify({ + schemaVersion: 2, + mediaType: "application/vnd.oci.image.index.v1+json", + manifests, + }), + ); + }; + const otherPlatform = { + ...descriptor, + digest: `sha256:${"f".repeat(64)}`, + platform: { + os: "linux", + architecture: architecture === "amd64" ? "arm64" : "amd64", + }, + }; + writeAlias([otherPlatform, descriptor]); + fs.writeFileSync(exactRaw, exactBody); + fs.writeFileSync( + path.join(fakeBin, "docker"), + `#!/bin/bash +set -euo pipefail +if [ "\${1:-} \${2:-} \${3:-}" = "buildx imagetools inspect" ]; then +if [[ "\${4:-}" == *":latest" ]]; then + cat "$ALIAS_RAW" +else + cat "$EXACT_RAW" +fi +elif [ "$*" = "pull --platform $PLATFORM $EXACT_REFERENCE" ]; then +exit 0 +elif [ "$*" = "image inspect $EXACT_REFERENCE" ]; then +printf '[{"Config":{"Labels":{"org.opencontainers.image.revision":"%s"}}}]' "$CANDIDATE_SHA" +else +exit 90 +fi +`, + { mode: 0o755 }, + ); + const runResolver = () => + spawnSync(resolver, [], { + encoding: "utf8", + env: { + ...process.env, + AGENT: "openclaw", + ALIAS_RAW: aliasRaw, + BASE_ALIAS: "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", + BASE_DOCKERFILE: "Dockerfile.base", + BASE_REPOSITORY: "ghcr.io/nvidia/nemoclaw/sandbox-base", + BASE_SHA: spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim(), + CANDIDATE_SHA: spawnSync("git", ["rev-parse", "HEAD"], { + encoding: "utf8", + }).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/${architecture}`, + RUNNER_TEMP: temporaryRoot, + }, + }); + + try { + const accepted = runResolver(); + expect(accepted.status, accepted.stderr).toBe(0); + expect(fs.readFileSync(output, "utf8")).toContain( + `ref=ghcr.io/nvidia/nemoclaw/sandbox-base@${digest}`, + ); + + writeAlias([descriptor, descriptor]); + const duplicate = runResolver(); + expect(duplicate.status).not.toBe(0); + expect(duplicate.stderr).toContain( + `does not contain exactly one linux/${architecture} image`, + ); + + writeAlias([otherPlatform]); + const missing = runResolver(); + expect(missing.status).not.toBe(0); + expect(missing.stderr).toContain(`does not contain exactly one linux/${architecture} image`); + + writeAlias([descriptor]); + fs.appendFileSync(exactRaw, " "); + const wrongBody = runResolver(); + expect(wrongBody.status).not.toBe(0); + expect(wrongBody.stderr).toContain( + "exact PR base bytes do not match the selected descriptor digest", + ); + } finally { + fs.rmSync(temporaryRoot, { recursive: true, force: true }); + } + }, +); + +it.each(["amd64", "arm64"])( + "builds a changed %s PR base locally and rejects comparison errors", + (architecture) => { + const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-local-pr-base-")); + const fakeBin = path.join(temporaryRoot, "bin"); + const output = path.join(temporaryRoot, "output"); + const summary = path.join(temporaryRoot, "summary"); + const dockerLog = path.join(temporaryRoot, "docker.log"); + fs.mkdirSync(fakeBin); + const runGit = (...args: string[]) => { + const result = spawnSync("git", args, { cwd: temporaryRoot, encoding: "utf8" }); + expect(result.status, result.stderr).toBe(0); + return result.stdout.trim(); + }; + runGit("init", "--quiet"); + runGit("config", "user.name", "NemoClaw Test"); + runGit("config", "user.email", "nemoclaw-test@example.invalid"); + fs.writeFileSync(path.join(temporaryRoot, "Dockerfile.base"), "FROM scratch\n"); + runGit("add", "Dockerfile.base"); + runGit("commit", "--quiet", "-m", "test: add base"); + const baseSha = runGit("rev-parse", "HEAD"); + fs.writeFileSync( + path.join(temporaryRoot, "Dockerfile.base"), + "FROM scratch\nLABEL test=changed\n", + ); + runGit("add", "Dockerfile.base"); + runGit("commit", "--quiet", "-m", "test: change base"); + const candidateSha = runGit("rev-parse", "HEAD"); + fs.writeFileSync( + path.join(fakeBin, "docker"), + `#!/bin/bash set -euo pipefail printf '%s\\n' "$*" >> "$DOCKER_LOG" if [ "\${1:-} \${2:-}" = "buildx build" ]; then @@ -66,54 +189,69 @@ if [ "\${1:-} \${2:-}" = "load --input" ]; then fi exit 90 `, - { mode: 0o755 }, - ); - const environment = { - ...process.env, - AGENT: "openclaw", - BASE_ALIAS: "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", - BASE_DOCKERFILE: "Dockerfile.base", - BASE_REPOSITORY: "ghcr.io/nvidia/nemoclaw/sandbox-base", - BASE_SHA: baseSha, - CANDIDATE_SHA: candidateSha, - DISPLAY_NAME: "OpenClaw", - DOCKER_LOG: dockerLog, - GITHUB_OUTPUT: output, - GITHUB_STEP_SUMMARY: summary, - LOCAL_BASE_REFERENCE: "nemoclaw-managed-pr/openclaw-base:test", - PATH: `${fakeBin}:${process.env.PATH ?? ""}`, - RUNNER_TEMP: temporaryRoot, - }; - - try { - const result = spawnSync(resolver, [], { - cwd: temporaryRoot, - encoding: "utf8", - env: environment, - }); - expect(result.status, result.stderr).toBe(0); - expect(fs.readFileSync(output, "utf8")).toBe( - `ref=nemoclaw-managed-pr/openclaw-base:test\nlocal=true\noci=${temporaryRoot}/pr-base.oci@sha256:0000000000000000000000000000000000000000000000000000000000000000\n`, - ); - const dockerCommands = fs.readFileSync(dockerLog, "utf8"); - expect(dockerCommands).toContain("buildx build"); - expect(dockerCommands).toContain(`load --input ${temporaryRoot}/pr-base.docker.tar`); - expect(dockerCommands).not.toContain("imagetools inspect"); - expect(fs.readFileSync(summary, "utf8")).toContain( - `Locally built from \`Dockerfile.base\` at \`${candidateSha}\`.`, + { mode: 0o755 }, ); + const environment = { + ...process.env, + AGENT: "openclaw", + BASE_ALIAS: "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", + BASE_DOCKERFILE: "Dockerfile.base", + BASE_REPOSITORY: "ghcr.io/nvidia/nemoclaw/sandbox-base", + BASE_SHA: baseSha, + CANDIDATE_SHA: candidateSha, + DISPLAY_NAME: "OpenClaw", + DOCKER_LOG: dockerLog, + GITHUB_OUTPUT: output, + GITHUB_STEP_SUMMARY: summary, + LOCAL_BASE_REFERENCE: "nemoclaw-managed-pr/openclaw-base:test", + PATH: `${fakeBin}:${process.env.PATH ?? ""}`, + PLATFORM: `linux/${architecture}`, + RUNNER_TEMP: temporaryRoot, + }; - const invalidRevision = spawnSync(resolver, [], { - cwd: temporaryRoot, + try { + const result = spawnSync(resolver, [], { + cwd: temporaryRoot, + encoding: "utf8", + env: environment, + }); + expect(result.status, result.stderr).toBe(0); + expect(fs.readFileSync(output, "utf8")).toBe( + `ref=nemoclaw-managed-pr/openclaw-base:test\nlocal=true\noci=${temporaryRoot}/pr-base.oci@sha256:0000000000000000000000000000000000000000000000000000000000000000\n`, + ); + const dockerCommands = fs.readFileSync(dockerLog, "utf8"); + expect(dockerCommands).toContain(`buildx build --platform linux/${architecture}`); + expect(dockerCommands).toContain(`load --input ${temporaryRoot}/pr-base.docker.tar`); + expect(dockerCommands).not.toContain("imagetools inspect"); + expect(fs.readFileSync(summary, "utf8")).toContain( + `Locally built from \`Dockerfile.base\` at \`${candidateSha}\`.`, + ); + + const invalidRevision = spawnSync(resolver, [], { + cwd: temporaryRoot, + encoding: "utf8", + env: { ...environment, CANDIDATE_SHA: "f".repeat(40) }, + }); + expect(invalidRevision.status).not.toBe(0); + expect(invalidRevision.stderr).toContain("PR base Dockerfile comparison failed"); + } finally { + fs.rmSync(temporaryRoot, { recursive: true, force: true }); + } + }, +); + +it.each([undefined, "", "linux/s390x", "windows/amd64"])( + "rejects unsupported platform %s before inspecting or building a base", + (platform) => { + const result = spawnSync(resolver, [], { encoding: "utf8", - env: { ...environment, CANDIDATE_SHA: "f".repeat(40) }, + env: { PATH: process.env.PATH, PLATFORM: platform }, }); - expect(invalidRevision.status).not.toBe(0); - expect(invalidRevision.stderr).toContain("PR base Dockerfile comparison failed"); - } finally { - fs.rmSync(temporaryRoot, { recursive: true, force: true }); - } -}); + expect(result.status).toBe(1); + expect(result.stderr).toContain("supported Linux platform"); + expect(result.stdout).toBe(""); + }, +); const publishedBaseCases = [ { @@ -194,9 +332,11 @@ const publishedBaseCases = [ 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 })), + ["openclaw", "hermes", "langchain-deepagents-code"].flatMap((agent) => + ["amd64", "arm64"].map((architecture) => ({ ...testCase, agent, architecture })), + ), ), -)("$agent: $title", (testCase) => { +)("$agent ($architecture): $title", (testCase) => { const { candidateContents, candidatePath, expectedLocal, failPublishedPull, rejectCopyParsing } = testCase; const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-pr-base-")); @@ -209,7 +349,7 @@ it.each( const digest = `sha256:${createHash("sha256").update(exactRaw).digest("hex")}`; const baseRepository = "ghcr.io/nvidia/nemoclaw/langchain-deepagents-code-sandbox-base"; const aliasRaw = JSON.stringify({ - manifests: [{ digest, platform: { architecture: "amd64", os: "linux" } }], + manifests: [{ digest, platform: { architecture: testCase.architecture, os: "linux" } }], mediaType: "application/vnd.oci.image.index.v1+json", }); fs.mkdirSync(fakeBin); @@ -302,8 +442,8 @@ if [ "\${1:-} \${2:-}" = "image inspect" ]; then if [ "\${3:-}" = "$LOCAL_BASE_REFERENCE" ]; then source_revision="$CANDIDATE_SHA" fi - printf '[{"Config":{"Labels":{"org.opencontainers.image.revision":"%s"}},"Id":"sha256:%s","Os":"linux","Architecture":"amd64"}]\\n' \ - "$source_revision" "$(printf 'b%.0s' {1..64})" + printf '[{"Config":{"Labels":{"org.opencontainers.image.revision":"%s"}},"Id":"sha256:%s","Os":"linux","Architecture":"%s"}]\\n' \ + "$source_revision" "$(printf 'b%.0s' {1..64})" "\${PLATFORM#linux/}" exit 0 fi if [ "\${1:-}" = run ]; then @@ -332,7 +472,7 @@ exit 90 LOCAL_BASE_REFERENCE: "nemoclaw-managed-pr/langchain-deepagents-code-base:test", PATH: `${fakeBin}:${process.env.PATH ?? ""}`, PARSER_SIDE_EFFECT: parserSideEffect, - PLATFORM: "linux/amd64", + PLATFORM: `linux/${testCase.architecture}`, PUBLISHED_SOURCE_SHA: publishedSourceSha, RUNNER_TEMP: temporaryRoot, }; @@ -347,7 +487,9 @@ exit 90 const resolverOutput = fs.readFileSync(output, "utf8"); expect(resolverOutput).toContain(`local=${String(expectedLocal)}\n`); const dockerCommands = fs.readFileSync(dockerLog, "utf8"); - expect(dockerCommands.includes("buildx build")).toBe(expectedLocal); + expect(dockerCommands.includes(`buildx build --platform ${environment.PLATFORM}`)).toBe( + expectedLocal, + ); expect(dockerCommands).not.toContain("validate-dcode-runtime-contract.py"); expect(fs.existsSync(parserSideEffect)).toBe(false); const summaryContents = fs.readFileSync(summary, "utf8"); diff --git a/test/inference/managed/managed-image-publication-workflow.test.ts b/test/inference/managed/managed-image-publication-workflow.test.ts index 579297f5cdf..7cea273b29c 100644 --- a/test/inference/managed/managed-image-publication-workflow.test.ts +++ b/test/inference/managed/managed-image-publication-workflow.test.ts @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; -import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -505,7 +504,12 @@ describe("complete managed-image publication workflow", () => { expect(prBuilder.needs).toEqual(["pr-reviewed-npm-audit", "publication-identity"]); expect(publicationIdentity.if).toBeUndefined(); expect(prBuilder.if).toBe("github.event_name == 'pull_request'"); - expect(prBuilder["runs-on"]).toBe("ubuntu-24.04"); + expect(prBuilder["runs-on"]).toBe( + "${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }}", + ); + expect(prBuilder.strategy?.matrix?.arch).toEqual(["amd64", "arm64"]); + expect(prBuilder.strategy?.matrix?.agent).toEqual(matrix.map(({ agent }) => agent)); + expect(prBuilder.env?.PLATFORM).toBe("linux/${{ matrix.arch }}"); expect(prBuilder["timeout-minutes"]).toBe(90); expect(prBuilder.permissions).toEqual({ contents: "read", packages: "write" }); expect(step(prBuilder, "Checkout").with?.["persist-credentials"]).toBe(false); @@ -550,20 +554,20 @@ describe("complete managed-image publication workflow", () => { expect(action.uses, action.name).toMatch(fullShaAction); } - expect(step(prBuilder, "Resolve digest-pinned linux/amd64 PR base").run).toBe( + expect(step(prBuilder, "Resolve digest-pinned native PR base").run).toBe( "scripts/checks/resolve-managed-pr-base.sh", ); expect(registryBaseBuild.if).toBe("steps.base.outputs.local != 'true'"); const localBuild = required(localBaseBuild.run, "PR managed image local build is missing"); expect(localBuild).toContain("docker build"); - expect(localBuild).toContain("--platform linux/amd64"); + expect(localBuild).toContain('--platform "$PLATFORM"'); expect(localBuild).toContain('--build-arg "BASE_IMAGE=${BASE_IMAGE}"'); expect(localBuild).toContain('--tag "$IMAGE_REFERENCE"'); expect(localBuild).toContain('--label "org.opencontainers.image.version=${RELEASE}"'); expect(localBaseBuild.env?.RELEASE).toBe("${{ steps.release.outputs.value }}"); expect(localBuild).not.toContain("docker buildx build"); expect(registryBaseBuild.with).toMatchObject({ - platforms: "linux/amd64", + platforms: "linux/${{ matrix.arch }}", load: true, push: false, }); @@ -578,13 +582,15 @@ describe("complete managed-image publication workflow", () => { ); expect(publishedContract.env?.COHORT).toBe("${{ needs.publication-identity.outputs.cohort }}"); expect(contractUpload.with).toMatchObject({ - name: "managed-pr-contract-${{ github.run_id }}-${{ matrix.agent }}", + name: "managed-pr-contract-${{ matrix.arch == 'arm64' && 'arm64-' || '' }}${{ github.run_id }}-${{ matrix.agent }}", overwrite: true, }); expect( step(managedPrActivation(workflow), "Download exact published all-agent contracts").with ?.pattern, - ).toBe("managed-pr-contract-${{ github.run_id }}-*"); + ).toBe( + "managed-pr-contract-${{ matrix.arch == 'arm64' && 'arm64-' || '' }}${{ github.run_id }}-*", + ); expect( step(managedPrPodmanActivation(workflow), "Download exact published all-agent contracts").with ?.pattern, @@ -727,7 +733,7 @@ describe("complete managed-image publication workflow", () => { expect(publish.if).toBe(sameRepository); expect(publish.with).toMatchObject({ builder: "${{ steps.buildx.outputs.name }}", - platforms: "linux/amd64", + platforms: "linux/${{ matrix.arch }}", "build-contexts": "${{ steps.base.outputs.local == 'true' && format('nemoclaw-pr-base=oci-layout://{0}', steps.base.outputs.oci) || '' }}", outputs: @@ -801,6 +807,11 @@ describe("complete managed-image publication workflow", () => { "github.event.pull_request.head.repo.full_name == github.repository", ); expect(activation.permissions).toEqual({ contents: "read" }); + expect(activation.strategy?.matrix?.arch).toEqual(["amd64", "arm64"]); + expect(activation["runs-on"]).toBe( + "${{ matrix.arch == 'arm64' && 'ubuntu-24.04-arm' || 'ubuntu-24.04' }}", + ); + expect(activation.env?.MANAGED_IMAGE_PLATFORM).toBe("linux/${{ matrix.arch }}"); expect(activation.env?.CANDIDATE_SHA).toBe("${{ github.event.pull_request.head.sha }}"); expect(activation.env?.NEMOCLAW_MANAGED_ACTIVATION_CATALOG).toBe( "${{ github.workspace }}/managed-pr-catalog.json", @@ -819,6 +830,10 @@ describe("complete managed-image publication workflow", () => { expect(run).toContain('[[ "$(git rev-parse --verify HEAD)" == "$CANDIDATE_SHA" ]]'); expect(run).toContain("test/e2e/live/managed-image-activation-e2e.test.ts"); expect(steps.map(({ name }) => name)).toContain("Upload managed runtime activation evidence"); + expect(step(activation, "Upload managed runtime activation evidence").with).toMatchObject({ + name: "managed-image-activation-${{ github.run_id }}-${{ github.run_attempt }}-${{ matrix.arch }}", + "if-no-files-found": "error", + }); }); it("leaves MCP qualification to the normal E2E workflow (#11828)", () => { const workflow = readWorkflow("managed-images.yaml"); @@ -841,114 +856,6 @@ describe("complete managed-image publication workflow", () => { ); }); - it("pins a single linux/amd64 PR base descriptor and fails closed on torn index evidence", () => { - const workflow = readWorkflow("managed-images.yaml"); - const resolver = required( - step(managedPrBuilder(workflow), "Resolve digest-pinned linux/amd64 PR base").run, - "PR base resolver script is missing", - ); - const temporaryRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-pr-base-")); - const fakeBin = path.join(temporaryRoot, "bin"); - const aliasRaw = path.join(temporaryRoot, "alias.raw"); - const exactRaw = path.join(temporaryRoot, "exact.raw"); - const output = path.join(temporaryRoot, "output"); - const summary = path.join(temporaryRoot, "summary"); - fs.mkdirSync(fakeBin); - const exactBody = JSON.stringify({ - schemaVersion: 2, - mediaType: "application/vnd.oci.image.manifest.v1+json", - config: { digest: `sha256:${"a".repeat(64)}`, size: 1 }, - layers: [], - }); - const digest = `sha256:${createHash("sha256").update(exactBody).digest("hex")}`; - const descriptor = { - mediaType: "application/vnd.oci.image.manifest.v1+json", - digest, - size: exactBody.length, - platform: { os: "linux", architecture: "amd64" }, - }; - const writeAlias = (manifests: unknown[]) => { - fs.writeFileSync( - aliasRaw, - JSON.stringify({ - schemaVersion: 2, - mediaType: "application/vnd.oci.image.index.v1+json", - manifests, - }), - ); - }; - writeAlias([descriptor]); - fs.writeFileSync(exactRaw, exactBody); - fs.writeFileSync( - path.join(fakeBin, "docker"), - `#!/bin/bash -set -euo pipefail -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 - exit 90 -fi -`, - { mode: 0o755 }, - ); - const runResolver = () => - spawnSync("bash", ["-c", resolver], { - encoding: "utf8", - env: { - ...process.env, - AGENT: "openclaw", - ALIAS_RAW: aliasRaw, - BASE_ALIAS: "ghcr.io/nvidia/nemoclaw/sandbox-base:latest", - BASE_DOCKERFILE: "Dockerfile.base", - BASE_REPOSITORY: "ghcr.io/nvidia/nemoclaw/sandbox-base", - BASE_SHA: spawnSync("git", ["rev-parse", "HEAD"], { encoding: "utf8" }).stdout.trim(), - CANDIDATE_SHA: spawnSync("git", ["rev-parse", "HEAD"], { - encoding: "utf8", - }).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, - }, - }); - - try { - const accepted = runResolver(); - expect(accepted.status, accepted.stderr).toBe(0); - expect(fs.readFileSync(output, "utf8")).toContain( - `ref=ghcr.io/nvidia/nemoclaw/sandbox-base@${digest}`, - ); - - writeAlias([descriptor, descriptor]); - const duplicate = runResolver(); - expect(duplicate.status).not.toBe(0); - expect(duplicate.stderr).toContain("does not contain exactly one linux/amd64 image"); - - writeAlias([descriptor]); - fs.appendFileSync(exactRaw, " "); - const wrongBody = runResolver(); - expect(wrongBody.status).not.toBe(0); - expect(wrongBody.stderr).toContain( - "exact PR base bytes do not match the selected descriptor digest", - ); - } finally { - fs.rmSync(temporaryRoot, { recursive: true, force: true }); - } - }); - it("publishes an exact native amd64 and arm64 lane for every shipped agent (#7744)", () => { const workflow = readWorkflow("managed-images.yaml"); const builder = managedBuilder(workflow); diff --git a/tools/e2e/pr-managed-image-publication.mts b/tools/e2e/pr-managed-image-publication.mts index 54e759f79c0..a41f110e630 100644 --- a/tools/e2e/pr-managed-image-publication.mts +++ b/tools/e2e/pr-managed-image-publication.mts @@ -7,10 +7,12 @@ import path from "node:path"; import { fileURLToPath } from "node:url"; import { + isManagedImagePlatform, parseManagedImageContractV1, SHIPPED_MANAGED_IMAGE_AGENTS, type ManagedImageContractCatalog, type ManagedImageContractV1, + type ManagedImagePlatform, } from "../../src/lib/onboard/managed-image/contract.ts"; import { baseImageInputsChanged, @@ -75,6 +77,7 @@ export function assembleManagedImageCatalog( values: readonly unknown[], candidateSha: string, consumerRun: WorkflowRun, + platform: ManagedImagePlatform = "linux/amd64", ): ManagedImageContractCatalog { if (!SHA_PATTERN.test(candidateSha)) throw new Error("candidate SHA is invalid"); if (values.length !== SHIPPED_MANAGED_IMAGE_AGENTS.length) { @@ -82,9 +85,7 @@ export function assembleManagedImageCatalog( `exact PR managed-image publication requires ${SHIPPED_MANAGED_IMAGE_AGENTS.length} contracts`, ); } - const contracts = values.map((value) => - parseManagedImageContractV1(value, undefined, "linux/amd64"), - ); + const contracts = values.map((value) => parseManagedImageContractV1(value, undefined, platform)); const byAgent = new Map(contracts.map((contract) => [contract.agent, contract])); if ( byAgent.size !== SHIPPED_MANAGED_IMAGE_AGENTS.length || @@ -123,11 +124,12 @@ export function writeManagedImageCatalog( candidateSha: string, outputPath: string, consumerRun: WorkflowRun, + platform: ManagedImagePlatform = "linux/amd64", ): void { const contracts = contractPaths.map( (contractPath) => JSON.parse(fs.readFileSync(contractPath, "utf8")) as unknown, ); - const catalog = assembleManagedImageCatalog(contracts, candidateSha, consumerRun); + const catalog = assembleManagedImageCatalog(contracts, candidateSha, consumerRun, platform); writeValidatedManagedImageCatalog(catalog, outputPath); } @@ -350,6 +352,7 @@ export async function resolvePrManagedImageCatalog( readonly candidateSha: string; readonly managedImageSha?: string; readonly outputPath: string; + readonly platform?: ManagedImagePlatform; readonly prNumber: number; readonly token: string; readonly workflowSource: string; @@ -361,6 +364,8 @@ export async function resolvePrManagedImageCatalog( downloadArtifact: (identity: BoundArtifactIdentity) => Promise = (identity) => downloadBoundArtifact(identity, input.token, { log: console.error }), ): Promise { + const platform = input.platform ?? "linux/amd64"; + if (!isManagedImagePlatform(platform)) throw new Error("unsupported managed-image platform"); if (!SHA_PATTERN.test(input.baseSha) || !SHA_PATTERN.test(input.candidateSha)) { throw new Error("PR base and candidate SHAs are required"); } @@ -397,7 +402,7 @@ export async function resolvePrManagedImageCatalog( try { const contracts: ManagedImageContractV1[] = []; for (const agent of SHIPPED_MANAGED_IMAGE_AGENTS) { - const name = `managed-pr-contract-${run.id}-${agent}`; + const name = `managed-pr-contract-${platform === "linux/arm64" ? "arm64-" : ""}${run.id}-${agent}`; const metadata = await request( `/repos/${REPOSITORY}/actions/runs/${run.id}/artifacts?name=${encodeURIComponent(name)}&per_page=100`, ); @@ -415,10 +420,15 @@ export async function resolvePrManagedImageCatalog( JSON.parse(fs.readFileSync(contractPath, "utf8")) as unknown as ManagedImageContractV1, ); } - const catalog = assembleManagedImageCatalog(contracts, managedImageSha, { - id: run.id, - attempt: run.attempt, - }); + const catalog = assembleManagedImageCatalog( + contracts, + managedImageSha, + { + id: run.id, + attempt: run.attempt, + }, + platform, + ); writeValidatedManagedImageCatalog(catalog, input.outputPath); return "candidate-catalog"; } finally { @@ -432,14 +442,22 @@ function requiredInteger(value: string | undefined, label: string): number { } export async function main(argv = process.argv.slice(2), env = process.env): Promise { + const platform = env.MANAGED_IMAGE_PLATFORM ?? "linux/amd64"; + if (!isManagedImagePlatform(platform)) throw new Error("unsupported managed-image platform"); if (argv[0] === "assemble") { if (argv.length < 4) { throw new Error("expected candidate SHA, output path, and managed-image contract paths"); } - writeManagedImageCatalog(argv.slice(3), argv[1], argv[2], { - id: requiredInteger(env.GITHUB_RUN_ID, "GITHUB_RUN_ID"), - attempt: requiredInteger(env.GITHUB_RUN_ATTEMPT, "GITHUB_RUN_ATTEMPT"), - }); + writeManagedImageCatalog( + argv.slice(3), + argv[1], + argv[2], + { + id: requiredInteger(env.GITHUB_RUN_ID, "GITHUB_RUN_ID"), + attempt: requiredInteger(env.GITHUB_RUN_ATTEMPT, "GITHUB_RUN_ATTEMPT"), + }, + platform, + ); console.log("pr-managed-image-catalog outcome=assembled"); return; } @@ -450,6 +468,7 @@ export async function main(argv = process.argv.slice(2), env = process.env): Pro candidateSha: env.CANDIDATE_SHA ?? "", managedImageSha: env.MANAGED_IMAGE_SHA || undefined, outputPath: argv[0], + platform, prNumber: requiredInteger(env.PR_NUMBER, "PR_NUMBER"), token: env.GITHUB_TOKEN ?? "", workflowSource: fs.readFileSync(BASE_IMAGE_WORKFLOW_PATH, "utf8"), From de84da982977c6bb780bce2c48f8a3f930dccdc6 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 18:15:27 -0700 Subject: [PATCH 08/11] feat(e2e): collect authenticated Pi qualification receipts Signed-off-by: Prekshi Vyas --- test/e2e/README.md | 18 + .../pi-qualification-collection.test.ts | 424 ++++++++++++++++++ .../collect-pi-qualification.mts | 226 ++++++++++ 3 files changed, 668 insertions(+) create mode 100644 test/e2e/support/pi-qualification-collection.test.ts create mode 100644 tools/managed-images/collect-pi-qualification.mts diff --git a/test/e2e/README.md b/test/e2e/README.md index 758dbe5725d..4b061d7ff06 100644 --- a/test/e2e/README.md +++ b/test/e2e/README.md @@ -382,6 +382,24 @@ Keep a Pi upgrade in one PR with two publication steps: 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. +Use `tools/managed-images/collect-pi-qualification.mts` from a reviewed tooling checkout to prepare +the receipt commit. Run it with the upgrade checkout as the working directory. Supply a GitHub API +token through `GITHUB_TOKEN`; do not put credentials in the command or patch. The collector reads +Git objects without passing that token to Git and does not execute the upgrade checkout's code. + +```bash +node /path/to/reviewed-checkout/tools/managed-images/collect-pi-qualification.mts PR_NUMBER RUN_ID > /path/to/pi-refresh.patch +git apply --check /path/to/pi-refresh.patch +git apply /path/to/pi-refresh.patch +``` + +The selected managed-images run must have succeeded for the current open upstream PR commit. +The collector verifies both artifact archive digests, platforms, source revision, release and +publication attempt. It rechecks the PR and run before printing a three-file patch: both receipts +and their authority hashes. It does not apply the patch, publish changes or certify full lifecycle +qualification. Review the patch and run the existing receipt refresh check before committing it. +Do not apply a partial patch after a collection error. + 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. diff --git a/test/e2e/support/pi-qualification-collection.test.ts b/test/e2e/support/pi-qualification-collection.test.ts new file mode 100644 index 00000000000..4405bf23fa4 --- /dev/null +++ b/test/e2e/support/pi-qualification-collection.test.ts @@ -0,0 +1,424 @@ +// 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 fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; + +import { describe, expect, it, vi } from "vitest"; + +import { + collectPiQualification, + piQualificationPatch, +} from "../../../tools/managed-images/collect-pi-qualification.mts"; +import { artifactZip } from "../../helpers/artifact-zip"; + +const SHA = "a".repeat(40); +const REPOSITORY = "NVIDIA/NemoClaw"; +const AUTHORITY = "src/lib/agent/candidate-authority.ts"; +const receiptPath = (arch: string) => `ci/pi-agent-qualification-v1-linux-${arch}.json`; +const hash = (value: string | Buffer) => createHash("sha256").update(value).digest("hex"); + +function fixture() { + const pr = { + number: 12, + state: "open", + head: { sha: SHA, repo: { full_name: REPOSITORY } }, + base: { repo: { full_name: REPOSITORY } }, + }; + const run = { + id: 20, + run_attempt: 1, + workflow_id: 30, + name: "Images / Build, Test, and Publish Managed Images", + path: ".github/workflows/managed-images.yaml", + event: "pull_request", + head_sha: SHA, + status: "completed", + conclusion: "success", + repository: { full_name: REPOSITORY }, + head_repository: { full_name: REPOSITORY }, + pull_requests: [{ number: 12 }], + }; + const contracts = ["amd64", "arm64"].map((arch, index) => { + const digest = `sha256:${String(index + 1).repeat(64)}`; + return { + contractVersion: 1, + agent: "pi", + platform: `linux/${arch}`, + image: "ghcr.io/nvidia/nemoclaw/pi-sandbox", + digest, + reference: `ghcr.io/nvidia/nemoclaw/pi-sandbox@${digest}`, + source: { repository: REPOSITORY, revision: SHA, cohort: "ghrun-20-1", release: "v0.1.0" }, + startupProfileContractVersion: 1, + capabilityContractVersion: 1, + }; + }); + const archives = () => + contracts.map((contract) => + artifactZip([{ name: "contract.json", contents: `${JSON.stringify(contract, null, 2)}\n` }]), + ); + const responses = new Map unknown>([ + [`/repos/${REPOSITORY}/pulls/12`, () => structuredClone(pr)], + [ + `/repos/${REPOSITORY}/actions/workflows/managed-images.yaml`, + () => ({ id: 30, path: run.path, state: "active" }), + ], + [`/repos/${REPOSITORY}/actions/runs/20`, () => structuredClone(run)], + ]); + ["amd64", "arm64"].forEach((arch, index) => { + responses.set( + `/repos/${REPOSITORY}/actions/runs/20/artifacts?name=managed-candidate-contract-20-1-pi-${arch}&per_page=100`, + () => { + const archive = archives()[index]!; + return { + total_count: 1, + artifacts: [ + { + id: index + 40, + name: `managed-candidate-contract-20-1-pi-${arch}`, + expired: false, + size_in_bytes: archive.length, + digest: `sha256:${hash(archive)}`, + archive_download_url: `https://api.github.com/repos/${REPOSITORY}/actions/artifacts/${index + 40}/zip`, + workflow_run: { id: 20, head_sha: run.head_sha }, + }, + ], + }; + }, + ); + }); + const request = vi.fn(async (apiPath: string): Promise => responses.get(apiPath)!()); + const download = vi.fn(async (identity: { id: number }) => archives()[identity.id - 40]!); + const collect = () => + collectPiQualification({ candidateSha: SHA, prNumber: 12, runId: 20 }, request, download); + return { pr, run, contracts, request, download, collect, responses }; +} + +type Fixture = ReturnType; + +describe("Pi qualification collection", () => { + it("preserves authenticated receipt bytes and calculates both authority hashes", async () => { + const input = fixture(); + const result = await input.collect(); + expect(result.digests).toEqual( + ["amd64", "arm64"].map((arch) => hash(result.receipts[receiptPath(arch)]!)), + ); + expect(JSON.parse(result.receipts[receiptPath("arm64")]!)).toEqual(input.contracts[1]); + expect(input.request.mock.calls.filter(([url]) => url.endsWith("/pulls/12"))).toHaveLength(2); + expect(input.download).toHaveBeenCalledTimes(2); + }); + + it.each(["pending", "failure", "cancelled", "skipped"])( + "rejects %s publication before downloading receipts", + async (conclusion) => { + const input = fixture(); + input.run.conclusion = conclusion; + await expect(input.collect()).rejects.toThrow("must complete successfully"); + expect(input.download).not.toHaveBeenCalled(); + }, + ); + + it.each([ + [ + "fork", + (input: Fixture) => { + input.pr.head.repo.full_name = "someone/NemoClaw"; + }, + ], + [ + "closed", + (input: Fixture) => { + input.pr.state = "closed"; + }, + ], + [ + "stale", + (input: Fixture) => { + input.pr.head.sha = "b".repeat(40); + }, + ], + ] as const)("rejects a %s PR", async (_state, mutate) => { + const input = fixture(); + mutate(input); + await expect(input.collect()).rejects.toThrow("current open upstream PR commit"); + expect(input.download).not.toHaveBeenCalled(); + }); + + it.each([ + [ + "revision", + (input: Fixture) => { + input.contracts[1]!.source.revision = "b".repeat(40); + }, + ], + [ + "cohort", + (input: Fixture) => { + input.contracts[1]!.source.cohort = "ghrun-20-2"; + }, + ], + [ + "release", + (input: Fixture) => { + input.contracts[1]!.source.release = "v0.2.0"; + }, + ], + [ + "platform", + (input: Fixture) => { + input.contracts[1]!.platform = "linux/amd64"; + }, + ], + ] as const)("rejects a mismatched ARM64 %s", async (_field, mutate) => { + const input = fixture(); + mutate(input); + await expect(input.collect()).rejects.toThrow(); + }); + + it("rejects substituted archive bytes", async () => { + const input = fixture(); + input.download.mockResolvedValue(Buffer.from("substituted")); + await expect(input.collect()).rejects.toThrow("authenticated identity"); + }); + + it.each([ + ["missing", { total_count: 0, artifacts: [] }], + ["duplicate", { total_count: 2, artifacts: [{ name: "irrelevant" }, { name: "irrelevant" }] }], + [ + "expired", + { + total_count: 1, + artifacts: [{ name: "managed-candidate-contract-20-1-pi-amd64", expired: true }], + }, + ], + [ + "wrong-commit", + { + total_count: 1, + artifacts: [ + { + name: "managed-candidate-contract-20-1-pi-amd64", + workflow_run: { id: 20, head_sha: "b".repeat(40) }, + }, + ], + }, + ], + ])("rejects %s artifact metadata", async (_kind, overrides) => { + const input = fixture(); + const url = `/repos/${REPOSITORY}/actions/runs/20/artifacts?name=managed-candidate-contract-20-1-pi-amd64&per_page=100`; + const listing = (await input.request(url)) as { + total_count: number; + artifacts: Record[]; + }; + input.responses.set(url, () => ({ + ...overrides, + artifacts: overrides.artifacts.map((artifact) => ({ ...listing.artifacts[0], ...artifact })), + })); + await expect(input.collect()).rejects.toThrow(); + expect(input.download).not.toHaveBeenCalled(); + }); + + it.each([ + [ + "workflow", + (input: Fixture) => { + input.run.workflow_id = 31; + }, + ], + [ + "event", + (input: Fixture) => { + input.run.event = "workflow_dispatch"; + }, + ], + [ + "PR", + (input: Fixture) => { + input.run.pull_requests[0]!.number = 13; + }, + ], + ] as const)("rejects publication from another %s", async (_kind, mutate) => { + const input = fixture(); + mutate(input); + await expect(input.collect()).rejects.toThrow(); + expect(input.download).not.toHaveBeenCalled(); + }); + + it.each([ + [ + "PR", + (input: Fixture) => { + input.pr.head.sha = "b".repeat(40); + }, + "current open upstream PR commit", + ], + [ + "attempt", + (input: Fixture) => { + input.run.run_attempt = 2; + }, + "attempt changed", + ], + ] as const)( + "rejects a changed %s after artifact acquisition", + async (_changed, mutate, message) => { + const input = fixture(); + const original = input.download.getMockImplementation()!; + input.download.mockImplementationOnce(original).mockImplementationOnce(async (identity) => { + const bytes = await original(identity); + mutate(input); + return bytes; + }); + await expect(input.collect()).rejects.toThrow(message); + }, + ); + + it("generates a three-file patch that Git applies without changing other authority", async () => { + const collected = await fixture().collect(); + const originals = { + [receiptPath("amd64")]: "{}\n", + [receiptPath("arm64")]: "{}", + [AUTHORITY]: `export const authority = {\n pi: Object.freeze([\n "${"c".repeat(64)}",\n "${"d".repeat(64)}",\n ]),\n untouched: true,\n};\n`, + }; + const patch = piQualificationPatch(collected, originals); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-qualification-patch-")); + try { + execFileSync("git", ["init", "-q", root]); + Object.entries(originals).forEach(([file, contents]) => { + fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + fs.writeFileSync(path.join(root, file), contents); + }); + execFileSync("git", ["apply", "--check", "-"], { cwd: root, input: patch }); + execFileSync("git", ["apply", "-"], { cwd: root, input: patch }); + expect( + Object.fromEntries( + Object.keys(collected.receipts).map((file) => [ + file, + fs.readFileSync(path.join(root, file), "utf8"), + ]), + ), + ).toEqual(collected.receipts); + const evaluated = execFileSync( + process.execPath, + [ + "--input-type=module", + "-e", + "const { authority } = await import(process.argv[1]); console.log(JSON.stringify(authority));", + pathToFileURL(path.join(root, AUTHORITY)).href, + ], + { encoding: "utf8" }, + ); + expect(JSON.parse(evaluated)).toEqual({ pi: collected.digests, untouched: true }); + expect(patch.match(/^diff --git /gmu)).toHaveLength(3); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("rejects an unrecognized authority layout without producing a partial patch", async () => { + const collected = await fixture().collect(); + expect(() => piQualificationPatch(collected, { [AUTHORITY]: "export const pi = [];" })).toThrow( + "two-receipt declaration", + ); + }); + + it("prints a CLI patch without mutating the checkout or passing the API token to Git", async () => { + const input = fixture(); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-qualification-cli-")); + const git = (...args: string[]) => + execFileSync("/usr/bin/git", args, { cwd: root, encoding: "utf8" }); + try { + git("init", "-q"); + const originals = { + [receiptPath("amd64")]: "{}\n", + [receiptPath("arm64")]: "{}\n", + [AUTHORITY]: `const authority = { pi: Object.freeze(["${"c".repeat(64)}", "${"d".repeat(64)}"]) };\n`, + }; + Object.entries(originals).forEach(([file, contents]) => { + fs.mkdirSync(path.dirname(path.join(root, file)), { recursive: true }); + fs.writeFileSync(path.join(root, file), contents); + }); + git("add", "."); + git( + "-c", + "user.name=Fixture", + "-c", + "user.email=fixture@example.invalid", + "-c", + "commit.gpgsign=false", + "commit", + "-qm", + "fixture", + ); + const sha = git("rev-parse", "HEAD").trim(); + input.pr.head.sha = sha; + input.run.head_sha = sha; + input.contracts.forEach((contract) => { + contract.source.revision = sha; + }); + const responseEntries = await Promise.all( + [ + "pulls/12", + "actions/workflows/managed-images.yaml", + "actions/runs/20", + ...["amd64", "arm64"].map( + (arch) => + `actions/runs/20/artifacts?name=managed-candidate-contract-20-1-pi-${arch}&per_page=100`, + ), + ].map(async (suffix) => { + const apiPath = `/repos/${REPOSITORY}/${suffix}`; + const json = await input.request(apiPath); + return [`https://api.github.com${apiPath}`, { json }]; + }), + ); + const archiveEntries = await Promise.all( + [40, 41].map(async (id) => [ + `https://api.github.com/repos/${REPOSITORY}/actions/artifacts/${id}/zip`, + { bytes: (await input.download({ id })).toString("base64") }, + ]), + ); + const responses = Object.fromEntries([...responseEntries, ...archiveEntries]); + const hook = `const responses = ${JSON.stringify(responses)}; + globalThis.fetch = async (url, init) => { + if (init.headers.Authorization !== "Bearer test-token") throw new Error("missing API token"); + const value = responses[String(url)]; + if (!value) throw new Error("unexpected network request"); + return new Response(value.bytes ? Buffer.from(value.bytes, "base64") : JSON.stringify(value.json)); + };`; + const shim = path.join(root, ".git", "token-free-bin"); + fs.mkdirSync(shim); + fs.writeFileSync( + path.join(shim, "git"), + '#!/bin/sh\n[ -z "${GITHUB_TOKEN+x}" ] || exit 87\nexec /usr/bin/git "$@"\n', + { mode: 0o700 }, + ); + const patch = execFileSync( + process.execPath, + [ + "--import", + `data:text/javascript,${encodeURIComponent(hook)}`, + fileURLToPath( + new URL("../../../tools/managed-images/collect-pi-qualification.mts", import.meta.url), + ), + "12", + "20", + ], + { + cwd: root, + encoding: "utf8", + env: { PATH: `${shim}:${process.env.PATH}`, GITHUB_TOKEN: "test-token" }, + }, + ); + expect(git("status", "--porcelain")).toBe(""); + expect(patch).not.toContain("test-token"); + expect(patch.match(/^diff --git /gmu)).toHaveLength(3); + execFileSync("/usr/bin/git", ["apply", "--check", "-"], { cwd: root, input: patch }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); +}); diff --git a/tools/managed-images/collect-pi-qualification.mts b/tools/managed-images/collect-pi-qualification.mts new file mode 100644 index 00000000000..c304b382d19 --- /dev/null +++ b/tools/managed-images/collect-pi-qualification.mts @@ -0,0 +1,226 @@ +// 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 path from "node:path"; +import { fileURLToPath } from "node:url"; + +import { readValidatedArtifactZipEntries } from "../../scripts/lib/read-artifact-zip.mts"; +import { githubRequest } from "../e2e/base-image-publication.mts"; +import { + bindNamedExactArtifact, + downloadBoundArtifact, + type BoundArtifactIdentity, +} from "../e2e/exact-artifact-download.mts"; +import { selectManagedImagePublicationRun } from "../e2e/pr-managed-image-publication.mts"; +import { validateCandidateContract } from "./validate-candidate-contract.mts"; + +const REPOSITORY = "NVIDIA/NemoClaw"; +const WORKFLOW = ".github/workflows/managed-images.yaml"; +const AUTHORITY = "src/lib/agent/candidate-authority.ts"; +const ARCHITECTURES = ["amd64", "arm64"] as const; +const receiptPath = (architecture: string) => + `ci/pi-agent-qualification-v1-linux-${architecture}.json`; + +type Request = (apiPath: string) => Promise; +type Expectation = { prNumber: number; runId: number; candidateSha: string }; +type RecordValue = Record; + +function record(value: unknown): RecordValue { + if (!value || typeof value !== "object" || Array.isArray(value)) { + throw new Error("Pi publication metadata must be an object"); + } + return value as RecordValue; +} + +function positiveInteger(value: unknown): number { + if (!Number.isSafeInteger(value) || Number(value) < 1) { + throw new Error("PR, run and workflow identifiers must be positive safe integers"); + } + return Number(value); +} + +function requireCurrentPr(value: unknown, expected: Expectation): void { + const pr = record(value); + const source = record(pr.head); + const base = record(pr.base); + if ( + pr.number !== expected.prNumber || + pr.state !== "open" || + source.sha !== expected.candidateSha || + record(source.repo).full_name !== REPOSITORY || + record(base.repo).full_name !== REPOSITORY + ) { + throw new Error("Pi receipt collection requires the current open upstream PR commit"); + } +} + +/** Collect both immutable receipts without changing checkout files or granting runtime authority. */ +export async function collectPiQualification( + expected: Expectation, + request: Request, + download: (identity: BoundArtifactIdentity) => Promise, +): Promise<{ receipts: Record; digests: string[] }> { + positiveInteger(expected.prNumber); + positiveInteger(expected.runId); + if (!/^[0-9a-f]{40}$/u.test(expected.candidateSha)) throw new Error("Invalid candidate SHA"); + const prPath = `/repos/${REPOSITORY}/pulls/${expected.prNumber}`; + requireCurrentPr(await request(prPath), expected); + const workflow = record( + await request(`/repos/${REPOSITORY}/actions/workflows/managed-images.yaml`), + ); + if (workflow.path !== WORKFLOW || workflow.state !== "active") { + throw new Error("Pi publication workflow identity is invalid"); + } + const runPath = `/repos/${REPOSITORY}/actions/runs/${expected.runId}`; + const readRun = async () => { + const payload = record(await request(runPath)); + const run = selectManagedImagePublicationRun( + { total_count: 1, workflow_runs: [payload] }, + { + headSha: expected.candidateSha, + prNumber: expected.prNumber, + workflowId: positiveInteger(workflow.id), + }, + ); + if (run.id !== expected.runId) throw new Error("Pi publication run identity changed"); + return run; + }; + const run = await readRun(); + const receipts: Record = {}; + const digests: string[] = []; + const releases = new Set(); + for (const architecture of ARCHITECTURES) { + const name = `managed-candidate-contract-${run.id}-${run.attempt}-pi-${architecture}`; + const identity = bindNamedExactArtifact( + await request(`${runPath}/artifacts?name=${name}&per_page=100`), + { headSha: run.headSha, runId: run.id, runAttempt: run.attempt }, + name, + ); + const archive = await download(identity); + if ( + archive.length !== identity.size || + `sha256:${createHash("sha256").update(archive).digest("hex")}` !== identity.digest + ) { + throw new Error("Pi publication archive does not match its authenticated identity"); + } + const entries = readValidatedArtifactZipEntries(archive, { + maxEntries: 1, + maxTotalUncompressedBytes: 64 * 1024, + }); + if (entries?.length !== 1 || entries[0]?.name !== "contract.json") { + throw new Error("Pi publication archive must contain only contract.json"); + } + const bytes = entries[0].bytes; + const contents = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); + const contract = validateCandidateContract(JSON.parse(contents), `linux/${architecture}`); + if ( + contract.agent !== "pi" || + contract.source.revision !== expected.candidateSha || + contract.source.cohort !== `ghrun-${run.id}-${run.attempt}` + ) { + throw new Error("Pi receipt does not match the publication commit and attempt"); + } + releases.add(contract.source.release); + receipts[receiptPath(architecture)] = contents; + digests.push(createHash("sha256").update(bytes).digest("hex")); + } + if (releases.size !== 1) throw new Error("Pi receipts must identify one release"); + if ((await readRun()).attempt !== run.attempt) throw new Error("Pi publication attempt changed"); + requireCurrentPr(await request(prPath), expected); + return { receipts, digests }; +} + +function replacementPatch(file: string, before: string, after: string): string { + if (before === after) return ""; + const lines = (text: string, prefix: string) => { + const parts = text.split("\n"); + const terminated = parts.pop() === ""; + if (!terminated) parts.push(text.slice(text.lastIndexOf("\n") + 1)); + return { + count: parts.length, + text: + parts.map((line) => `${prefix}${line}\n`).join("") + + (terminated ? "" : "\\ No newline at end of file\n"), + }; + }; + const oldLines = lines(before, "-"); + const newLines = lines(after, "+"); + return ( + `diff --git a/${file} b/${file}\n--- a/${file}\n+++ b/${file}\n` + + `@@ -1,${oldLines.count} +1,${newLines.count} @@\n${oldLines.text}${newLines.text}` + ); +} + +/** Generate a reviewable three-file patch; existing CI still checks source parity and authority. */ +export function piQualificationPatch( + collected: Awaited>, + originals: Record, +): string { + const authority = originals[AUTHORITY]; + const pattern = /pi: Object\.freeze\(\[\s*"[a-f0-9]{64}",\s*"[a-f0-9]{64}",?\s*\]\)/gu; + if ( + !authority || + [...authority.matchAll(pattern)].length !== 1 || + collected.digests.length !== 2 || + collected.digests.some((digest) => !/^[a-f0-9]{64}$/u.test(digest)) + ) { + throw new Error("Pi authority must contain one two-receipt declaration"); + } + const updates: Record = { + ...collected.receipts, + [AUTHORITY]: authority.replace( + pattern, + `pi: Object.freeze([\n "${collected.digests[0]}",\n "${collected.digests[1]}",\n ])`, + ), + }; + return [...ARCHITECTURES.map(receiptPath), AUTHORITY] + .map((file) => { + if (typeof originals[file] !== "string" || typeof updates[file] !== "string") { + throw new Error(`Missing Pi refresh input: ${file}`); + } + return replacementPatch(file, originals[file], updates[file]); + }) + .join(""); +} + +/** Print a patch from authenticated artifacts; never apply, commit, push, or dispatch it. */ +export async function main(argv = process.argv.slice(2), env = process.env): Promise { + if (argv.length !== 2 || argv.some((value) => !/^[1-9][0-9]*$/u.test(value))) { + throw new Error("Usage: collect-pi-qualification.mts "); + } + const token = env.GITHUB_TOKEN ?? ""; + if (!token || /[\r\n]/u.test(token)) throw new Error("GITHUB_TOKEN is required"); + const git = (...args: string[]) => + execFileSync("git", ["-c", "core.fsmonitor=false", ...args], { + encoding: "utf8", + timeout: 10_000, + env: { + PATH: env.PATH, + GIT_CONFIG_GLOBAL: "/dev/null", + GIT_CONFIG_NOSYSTEM: "1", + GIT_OPTIONAL_LOCKS: "0", + }, + }); + const candidateSha = git("rev-parse", "HEAD").trim(); + const files = [...ARCHITECTURES.map(receiptPath), AUTHORITY]; + const originals = Object.fromEntries( + files.map((file) => [file, git("show", `${candidateSha}:${file}`)]), + ); + const collected = await collectPiQualification( + { + candidateSha, + prNumber: positiveInteger(Number(argv[0])), + runId: positiveInteger(Number(argv[1])), + }, + (apiPath) => githubRequest(apiPath, token), + (identity) => downloadBoundArtifact(identity, token), + ); + if (git("rev-parse", "HEAD").trim() !== candidateSha) throw new Error("Local commit changed"); + process.stdout.write(piQualificationPatch(collected, originals)); +} + +if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1] ?? "")) { + await main(); +} From 0394cd43a9849e7188da9149a7aa8ca10652ab69 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 20:46:57 -0700 Subject: [PATCH 09/11] fix(ci): prepare reviewed OpenShell 0.1.3 bootstrap Register verified 0.1.3 identities while retaining the active SDK producer. Preserve registry history and constrain synthetic trust edits in tests. Use PATH-selected Git in the token-isolation regression. Signed-off-by: Prekshi Vyas --- ci/openshell-upgrade-trust.json | 77 ++++++++++++++++++- ci/reviewed-npm-audit.json | 14 ++-- .../pi-qualification-collection.test.ts | 11 +-- test/helpers/candidate-openshell-trust.ts | 18 +++-- test/install/installer-hash-check.test.ts | 4 +- .../package-openshell-sdk-for-pr.test.ts | 50 +++--------- 6 files changed, 111 insertions(+), 63 deletions(-) diff --git a/ci/openshell-upgrade-trust.json b/ci/openshell-upgrade-trust.json index fbadb7d59a2..dec2669ce87 100644 --- a/ci/openshell-upgrade-trust.json +++ b/ci/openshell-upgrade-trust.json @@ -1,5 +1,80 @@ { "schemaVersion": 1, - "releases": [], + "releases": [ + { + "brevTemplateSha256": ["e44a3952cd5f6be9f017a5b69028c2068a746060bff31c3f05eecbb36cd7237c"], + "formula": { + "asset": "openshell.rb", + "sha256": "e760d5c41f5d3fd7a430a87e1efdf813c44848689c76a10029c8f65ed4f4eb4b", + "url": "https://github.com/NVIDIA/OpenShell/releases/download/v0.1.3/openshell.rb" + }, + "installerTemplateSha256": [ + "0b9c65bcc255d97d2fbfef638fbb4b374d7617fb2aaaf6cb76b898ded74e498f" + ], + "manifests": [ + { + "asset": "openshell-checksums-sha256.txt", + "sha256": "a7bc832c2e777e43e373bcdfa2f3d6180f2e83efb491d81d4299e181697444eb" + }, + { + "asset": "openshell-gateway-checksums-sha256.txt", + "sha256": "414dc38f465086532077429a5d652ebad4d28fc384077c54c70139209568f8c6" + }, + { + "asset": "openshell-sandbox-checksums-sha256.txt", + "sha256": "1320a57cc9fd3ce8ad4bb9e1f8e225241f2d8b35ae3ceb1ae69992670211d576" + } + ], + "sandboxBuilds": [ + { + "required": false, + "sha256": "38fe063f19c72680a1bc4b0c343a3ec5b7a5cb087a627faab5b2aefd9d50d094" + }, + { + "required": false, + "sha256": "23147b42d31bd0b13e1a9ed7b3834b8e6075836cba0872fffa9e7d481f6dd281" + } + ], + "supervisor": { + "image": "ghcr.io/nvidia/openshell/supervisor", + "manifestDigest": "sha256:4ab2b970cdb02c7518ba4ccbbadb4861ae9a8d0b8770e5b160697f0453b0a8e4", + "required": false, + "runtimeTemplateSha256": [ + "5e698f27cbaae4c544696137afbccdda68d2466fbe7532c6d1c65970ec5c66f6" + ] + }, + "pinLayout": { + "brev": { + "assets": [ + "openshell-x86_64-unknown-linux-musl.tar.gz", + "openshell-aarch64-unknown-linux-musl.tar.gz" + ], + "manifests": ["openshell-checksums-sha256.txt"] + }, + "installer": { + "assets": [ + "openshell-x86_64-unknown-linux-musl.tar.gz", + "openshell-aarch64-unknown-linux-musl.tar.gz", + "openshell-aarch64-apple-darwin.tar.gz", + "openshell-gateway-x86_64-unknown-linux-gnu.tar.gz", + "openshell-gateway-aarch64-unknown-linux-gnu.tar.gz", + "openshell-gateway-aarch64-apple-darwin.tar.gz", + "openshell-sandbox-x86_64-unknown-linux-musl.tar.gz", + "openshell-sandbox-aarch64-unknown-linux-musl.tar.gz", + "openshell.rb" + ], + "manifests": [ + "openshell-checksums-sha256.txt", + "openshell-gateway-checksums-sha256.txt", + "openshell-sandbox-checksums-sha256.txt" + ] + } + }, + "featureGateTemplateSha256": [ + "cd2c1e6d74756d1a6d166bbfdb31a31f75b7bc6a50fc9d6b9e218f2a9eb97402" + ], + "version": "0.1.3" + } + ], "revokedTemplateSha256": [] } diff --git a/ci/reviewed-npm-audit.json b/ci/reviewed-npm-audit.json index 047dd2c041d..72d2cdf4045 100644 --- a/ci/reviewed-npm-audit.json +++ b/ci/reviewed-npm-audit.json @@ -12,9 +12,7 @@ "integrity": "sha512-MFnyX2vs47f/yVJRUXKmA7C6wZDH03ZGFFg+R5gZME+yMQDg9WF6G4Kdz/APM7nCUpaoGk2bwNEdUUmR60J54A==", "tarballUrl": "https://npm.pkg.github.com/download/@nvidia/openshell-sdk/0.0.116/3380652847354127ed1bb8010490f8815040ada3" }, - "sourceNestedShrinkwrapPackages": [ - "@earendil-works/pi-coding-agent@0.80.6" - ], + "sourceNestedShrinkwrapPackages": ["@earendil-works/pi-coding-agent@0.80.6"], "sourceRegistryPackagesWithoutIntegrity": [ { "label": "Pi agent core 0.80.6 nested shrinkwrap entry", @@ -203,10 +201,10 @@ } ], "sourceRegistryPackageReplacement": { - "artifactName": "nvidia-openshell-sdk-0.1.2.tgz", - "label": "OpenShell TypeScript SDK 0.1.2", - "packageSpec": "@nvidia/openshell-sdk@0.1.2", - "integrity": "sha512-GtNh/xzuIydm8pnBJSB+Pvo9wQrGcvAdVMgQOjmx2asjXIAMQcdX5/17sd0GjFF0K0KHCTW2gqgwYvf6BCqWMQ==", - "tarballUrl": "https://npm.pkg.github.com/download/@nvidia/openshell-sdk/0.1.2/2bef2b98c751484b2a8ad434915138f85d23cfba" + "artifactName": "nvidia-openshell-sdk-0.1.3.tgz", + "label": "OpenShell TypeScript SDK 0.1.3", + "packageSpec": "@nvidia/openshell-sdk@0.1.3", + "integrity": "sha512-JXWcEDIl/h8Pp6c2NrFMp0XLloDsLaDZvSVJzXvKUyGEulE64d/utiE1KtNh45JtiZXbVmB2PMJAWEmgZKW5kA==", + "tarballUrl": "https://npm.pkg.github.com/download/@nvidia/openshell-sdk/0.1.3/32e1b675af5ad8b8a8fe078a1a11d515a9f45571" } } diff --git a/test/e2e/support/pi-qualification-collection.test.ts b/test/e2e/support/pi-qualification-collection.test.ts index 4405bf23fa4..8363bc6173a 100644 --- a/test/e2e/support/pi-qualification-collection.test.ts +++ b/test/e2e/support/pi-qualification-collection.test.ts @@ -329,8 +329,8 @@ describe("Pi qualification collection", () => { it("prints a CLI patch without mutating the checkout or passing the API token to Git", async () => { const input = fixture(); const root = fs.mkdtempSync(path.join(os.tmpdir(), "pi-qualification-cli-")); - const git = (...args: string[]) => - execFileSync("/usr/bin/git", args, { cwd: root, encoding: "utf8" }); + const originalPath = process.env.PATH ?? ""; + const git = (...args: string[]) => execFileSync("git", args, { cwd: root, encoding: "utf8" }); try { git("init", "-q"); const originals = { @@ -393,7 +393,8 @@ describe("Pi qualification collection", () => { fs.mkdirSync(shim); fs.writeFileSync( path.join(shim, "git"), - '#!/bin/sh\n[ -z "${GITHUB_TOKEN+x}" ] || exit 87\nexec /usr/bin/git "$@"\n', + '#!/bin/sh\n[ -z "${GITHUB_TOKEN+x}" ] || exit 87\n' + + `PATH='${originalPath.replaceAll("'", "'\\''")}' exec git "$@"\n`, { mode: 0o700 }, ); const patch = execFileSync( @@ -410,13 +411,13 @@ describe("Pi qualification collection", () => { { cwd: root, encoding: "utf8", - env: { PATH: `${shim}:${process.env.PATH}`, GITHUB_TOKEN: "test-token" }, + env: { PATH: `${shim}:${originalPath}`, GITHUB_TOKEN: "test-token" }, }, ); expect(git("status", "--porcelain")).toBe(""); expect(patch).not.toContain("test-token"); expect(patch.match(/^diff --git /gmu)).toHaveLength(3); - execFileSync("/usr/bin/git", ["apply", "--check", "-"], { cwd: root, input: patch }); + execFileSync("git", ["apply", "--check", "-"], { cwd: root, input: patch }); } finally { fs.rmSync(root, { recursive: true, force: true }); } diff --git a/test/helpers/candidate-openshell-trust.ts b/test/helpers/candidate-openshell-trust.ts index b18a1926e2c..f407b432701 100644 --- a/test/helpers/candidate-openshell-trust.ts +++ b/test/helpers/candidate-openshell-trust.ts @@ -8,7 +8,10 @@ import { dirname, join } from "node:path"; import { pathToFileURL } from "node:url"; import { tmpdir } from "node:os"; import { vi } from "vitest"; -import { validateInstallerSources } from "../../scripts/checks/extract-installer-pins.mts"; +import { + readOpenShellTrustRegistry, + validateInstallerSources, +} from "../../scripts/checks/extract-installer-pins.mts"; import { CANDIDATE_OPENSHELL_SOURCES, CANDIDATE_OPENSHELL_TRUST_PATH, @@ -68,10 +71,10 @@ export function fixture() { sources[key as keyof typeof sources], ]), ); + const registry = readOpenShellTrustRegistry(); files[CANDIDATE_OPENSHELL_TRUST_PATH] = JSON.stringify({ - schemaVersion: 1, - releases: [release], - revokedTemplateSha256: [], + ...registry, + releases: [...registry.releases, release], }); const repository = { full_name: "NVIDIA/NemoClaw" }; const approvals = [ @@ -155,11 +158,10 @@ export function runCoveredRegistry( }), ); const candidateRegistry = structuredClone(oldRegistry); + const candidateRelease = candidateRegistry.releases.find((entry) => entry.version === version)!; if (scenario === "empty") candidateRegistry.releases = []; - if (scenario === "new-template") - candidateRegistry.releases[0]!.installerTemplateSha256 = ["0".repeat(64)]; - if (scenario === "changed-artifact") - candidateRegistry.releases[0]!.formula.sha256 = "0".repeat(64); + if (scenario === "new-template") candidateRelease.installerTemplateSha256 = ["0".repeat(64)]; + if (scenario === "changed-artifact") candidateRelease.formula.sha256 = "0".repeat(64); f.files[CANDIDATE_OPENSHELL_TRUST_PATH] = JSON.stringify(candidateRegistry); Object.entries(f.files).forEach(([path, source]) => { mkdirSync(dirname(join(candidate, path)), { recursive: true }); diff --git a/test/install/installer-hash-check.test.ts b/test/install/installer-hash-check.test.ts index 61eec9fa6db..9472591e14e 100644 --- a/test/install/installer-hash-check.test.ts +++ b/test/install/installer-hash-check.test.ts @@ -374,8 +374,8 @@ const removeFirstReleaseFormula = (source: string): string => ); const trustSyntheticSupervisorRuntimeTemplate = (source: string): string => { const marker = " runtimeTemplateSha256: [\n"; - const result = source.replaceAll( - marker, + const result = source.replace( + /^ runtimeTemplateSha256: \[\n/gmu, `${marker} "${SYNTHETIC_SUPERVISOR_RUNTIME_TEMPLATE_SHA256}",\n`, ); assert.notEqual(result, source, "synthetic supervisor runtime trust anchors"); diff --git a/test/repository/package-openshell-sdk-for-pr.test.ts b/test/repository/package-openshell-sdk-for-pr.test.ts index 133740dafcc..987e75ec410 100644 --- a/test/repository/package-openshell-sdk-for-pr.test.ts +++ b/test/repository/package-openshell-sdk-for-pr.test.ts @@ -174,62 +174,34 @@ describe("reviewed OpenShell SDK transition packaging", () => { it("packages exactly the active and replacement identities for PR selection", () => { const source = fixture(); - const configPath = path.resolve("ci/reviewed-npm-audit.json"); - const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record; - const replacement = config.sourceRegistryPackage; - config.sourceRegistryPackage = { - artifactName: "nvidia-openshell-sdk-0.0.106.tgz", - label: "OpenShell TypeScript SDK 0.0.106", - packageSpec: "@nvidia/openshell-sdk@0.0.106", - integrity: - "sha512-dB4mLex23Pnw61caGMR2CMHQihy9bj7IK2elJJd718k3yevm+fOt/vG6dJg8/5us4la2BwcOdRwLvOia3tdwFw==", - tarballUrl: - "https://npm.pkg.github.com/download/@nvidia/openshell-sdk/0.0.106/dc32180ba1d658fc4ec309bdf89d2b162196928d", - }; - config.sourceRegistryPackageReplacement = replacement; - - const artifactDirectory = packageReviewedOpenShellSdk(source.output, "require", { - ...source, - readAuditConfig: () => JSON.stringify(config), - }); + const artifactDirectory = packageReviewedOpenShellSdk(source.output, "require", source); expect(artifactDirectory).toBe(source.output); expect(fs.readdirSync(artifactDirectory).sort()).toEqual([ - "nvidia-openshell-sdk-0.0.106.tgz", "nvidia-openshell-sdk-0.0.116.tgz", + "nvidia-openshell-sdk-0.1.3.tgz", ]); expect(source.requests.map(({ packageSpec }) => packageSpec)).toEqual([ - "@nvidia/openshell-sdk@0.0.106", "@nvidia/openshell-sdk@0.0.116", + "@nvidia/openshell-sdk@0.1.3", ]); + expect(source.requests[1]).toMatchObject({ + expectedIntegrity: + "sha512-JXWcEDIl/h8Pp6c2NrFMp0XLloDsLaDZvSVJzXvKUyGEulE64d/utiE1KtNh45JtiZXbVmB2PMJAWEmgZKW5kA==", + tarballUrl: + "https://npm.pkg.github.com/download/@nvidia/openshell-sdk/0.1.3/32e1b675af5ad8b8a8fe078a1a11d515a9f45571", + }); expect(source.remove).toHaveBeenCalledTimes(2); }); it("packages the replacement when available without requiring transition metadata", () => { const source = fixture(); - const configPath = path.resolve("ci/reviewed-npm-audit.json"); - const config = JSON.parse(fs.readFileSync(configPath, "utf8")) as Record; - const replacement = config.sourceRegistryPackage; - config.sourceRegistryPackage = { - artifactName: "nvidia-openshell-sdk-0.0.106.tgz", - label: "OpenShell TypeScript SDK 0.0.106", - packageSpec: "@nvidia/openshell-sdk@0.0.106", - integrity: - "sha512-dB4mLex23Pnw61caGMR2CMHQihy9bj7IK2elJJd718k3yevm+fOt/vG6dJg8/5us4la2BwcOdRwLvOia3tdwFw==", - tarballUrl: - "https://npm.pkg.github.com/download/@nvidia/openshell-sdk/0.0.106/dc32180ba1d658fc4ec309bdf89d2b162196928d", - }; - config.sourceRegistryPackageReplacement = replacement; - - const artifactDirectory = packageReviewedOpenShellSdk(source.output, "if-present", { - ...source, - readAuditConfig: () => JSON.stringify(config), - }); + const artifactDirectory = packageReviewedOpenShellSdk(source.output, "if-present", source); expect(artifactDirectory).toBe(source.output); expect(source.requests.map(({ packageSpec }) => packageSpec)).toEqual([ - "@nvidia/openshell-sdk@0.0.106", "@nvidia/openshell-sdk@0.0.116", + "@nvidia/openshell-sdk@0.1.3", ]); }); From d1cf7ea4203144f688b23f8176aee0fa222d60c7 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 14 Oct 2026 22:01:47 -0700 Subject: [PATCH 10/11] ci(pi): refresh candidate qualification receipts --- 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 ++-- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/ci/pi-agent-qualification-v1-linux-amd64.json b/ci/pi-agent-qualification-v1-linux-amd64.json index 0f161bc93f9..097f9aafbef 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:a64fe4d7f96959259ac4bbf31078cc8479c8ad7f7b67e6a5f7ba72e5e338bd6b", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:a64fe4d7f96959259ac4bbf31078cc8479c8ad7f7b67e6a5f7ba72e5e338bd6b", + "digest": "sha256:e18e9f88a2acf642ca14229cf814a39c3170f5cd25cc6e32fc7757e40ac9a162", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:e18e9f88a2acf642ca14229cf814a39c3170f5cd25cc6e32fc7757e40ac9a162", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "482dd1305efd85d386757998fc8980de035f8b61", + "revision": "0394cd43a9849e7188da9149a7aa8ca10652ab69", "release": "v0.1.0", - "cohort": "ghrun-38530733040-1" + "cohort": "ghrun-38678295208-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 ab98540b49b..9999537fc89 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:3eeeb5a85fad5c49939d627355c9f26267a82241510892bbb632c096ac84c2b1", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:3eeeb5a85fad5c49939d627355c9f26267a82241510892bbb632c096ac84c2b1", + "digest": "sha256:457792d98d91752bedaad8626f3a46e1cb12c04884bacb1ad47ebf4519ee5a80", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:457792d98d91752bedaad8626f3a46e1cb12c04884bacb1ad47ebf4519ee5a80", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "482dd1305efd85d386757998fc8980de035f8b61", + "revision": "0394cd43a9849e7188da9149a7aa8ca10652ab69", "release": "v0.1.0", - "cohort": "ghrun-38530733040-1" + "cohort": "ghrun-38678295208-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index c252607e77f..7817aaa63a2 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([ - "f9a90de7888ecac7ab20fa1b6a9b8b083fd30c4a37e41a032803ed0712b66cb6", - "86ffbb6cb781c28ec0d781027e03e120756c416beafcc3f95cde2235da9324cc", + "7fcfb997c4894965687a28444c17780316151fd2191236ac4935cc7675fc25a4", + "20d4dabb4007d7a5157aec84087c520c9b2aa1ec2247b94700da3f10876c9949", ]), }); From 6ac688cfeaf7dc9b2f00fc198d9092da86d604b0 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 15 Oct 2026 01:00:59 -0700 Subject: [PATCH 11/11] fix(checks): read OpenShell release trust from registry Signed-off-by: Prekshi Vyas --- scripts/checks/dependency-pins.mts | 57 +++------ test/repository/dependency-pins-check.test.ts | 113 ++++++++++++++---- 2 files changed, 102 insertions(+), 68 deletions(-) diff --git a/scripts/checks/dependency-pins.mts b/scripts/checks/dependency-pins.mts index 0bf9d8a6f6c..fb584a76e80 100644 --- a/scripts/checks/dependency-pins.mts +++ b/scripts/checks/dependency-pins.mts @@ -7,6 +7,9 @@ import { fileURLToPath } from "node:url"; import { parse as parseYaml } from "yaml"; +import { resolveOpenShellTrustRegistry } from "./extract-installer-pins.mts"; +import { parseOpenShellTrustRegistry } from "./openshell-trust-data.mts"; + type OpenShellPins = Readonly<{ maxVersion: string; minVersion: string; @@ -31,11 +34,6 @@ type DependencyPins = Readonly<{ const REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "../.."); const OPENCLAW_VERSION_ARG_SUFFIX_RE = /[.-]/g; const NUMERIC_VERSION_RE = /^[0-9]+\.[0-9]+\.[0-9]+$/; -const OPENSHELL_RELEASE_MANIFESTS = [ - "openshell-checksums-sha256.txt", - "openshell-gateway-checksums-sha256.txt", - "openshell-sandbox-checksums-sha256.txt", -] as const; function isRecord(value: unknown): value is Record { return typeof value === "object" && value !== null && !Array.isArray(value); @@ -276,38 +274,15 @@ function requireOpenShellReleaseTrustRecord( expectedVersion: string, failures: string[], ): string { - const marker = "const TRUSTED_OPENSHELL_RELEASES: readonly OpenShellReleaseTrust[] = ["; - const start = source.indexOf(marker); - const end = source.indexOf("\n] as const;", start + marker.length); - const records = - start === -1 || end === -1 - ? [] - : [...source.slice(start + marker.length, end).matchAll(/^ \{\n([\s\S]*?)^ \},$/gm)].map( - (match) => match[1] ?? "", - ); - const matchingRecords = records.filter((record) => { - const versions = [...record.matchAll(/^ version: "([0-9]+\.[0-9]+\.[0-9]+)",$/gm)]; - return versions.length === 1 && versions[0]?.[1] === expectedVersion; - }); - const entries = [...(matchingRecords[0] ?? "").matchAll(/^ asset: "([^"]+)",$/gm)] - .map((match) => match[1]) - .filter((manifest): manifest is string => manifest !== undefined); - const complete = - matchingRecords.length === 1 && - entries.length === OPENSHELL_RELEASE_MANIFESTS.length && - OPENSHELL_RELEASE_MANIFESTS.every( - (manifest) => entries.filter((entry) => entry === manifest).length === 1, - ); - if (!complete) { + try { + const releases = resolveOpenShellTrustRegistry(parseOpenShellTrustRegistry(source)); + const release = releases.find((entry) => entry.version === expectedVersion); + if (release) return release.formula.sha256; failures.push(`OpenShell release trust: expected one complete record for ${expectedVersion}`); - return ""; + } catch (error) { + failures.push(`OpenShell release trust: ${(error as Error).message}`); } - return extractSingle( - matchingRecords[0] ?? "", - /^ sha256: "([a-f0-9]{64})",\s*$/gm, - "OpenShell release trust formula SHA-256", - failures, - ); + return ""; } function verifyOpenShellPins( @@ -320,7 +295,7 @@ function verifyOpenShellPins( hermesDockerfile: string; hermesMcpConfigTransaction: string; installer: string; - installerPinExtractor: string; + openshellTrustRegistry: string; mcpBridgeValidation: string; openshellFeatureGate: string; openshellInstall: string; @@ -358,7 +333,7 @@ function verifyOpenShellPins( failures, ); const formulaSha256 = requireOpenShellReleaseTrustRecord( - sources.installerPinExtractor, + sources.openshellTrustRegistry, pins.maxVersion, failures, ); @@ -571,11 +546,7 @@ export function verifyDependencyPins(rootDir: string = REPO_ROOT): string[] { const brevLaunchable = readText(rootDir, "scripts/brev-launchable-ci-cpu.sh", failures); const installer = readText(rootDir, "scripts/install-openshell.sh", failures); - const installerPinExtractor = readText( - rootDir, - "scripts/checks/extract-installer-pins.mts", - failures, - ); + const openshellTrustRegistry = readText(rootDir, "ci/openshell-upgrade-trust.json", failures); const e2eWorkflowSource = readText(rootDir, ".github/workflows/e2e.yaml", failures); const gatewayService = readText( rootDir, @@ -655,7 +626,7 @@ export function verifyDependencyPins(rootDir: string = REPO_ROOT): string[] { hermesDockerfile, hermesMcpConfigTransaction, installer, - installerPinExtractor, + openshellTrustRegistry, mcpBridgeValidation, openshellFeatureGate, openshellInstall, diff --git a/test/repository/dependency-pins-check.test.ts b/test/repository/dependency-pins-check.test.ts index 68d00715315..ca4bd290bce 100644 --- a/test/repository/dependency-pins-check.test.ts +++ b/test/repository/dependency-pins-check.test.ts @@ -53,27 +53,31 @@ function writeFixture(root: string, overrides: FixtureOverrides = {}): void { overrides.releaseTrustExtraVersion, overrides.releaseTrustVersion ?? openshellMax, ].filter((version): version is string => version !== undefined); - const installerTrustRecords = installerTrustVersions - .map( - (version) => ` { + const installerTrustRecords = installerTrustVersions.map((version) => ({ + version, formula: { asset: "openshell.rb", - sha256: "${overrides.releaseFormulaSha256 ?? FORMULA_SHA256}", + sha256: overrides.releaseFormulaSha256 ?? FORMULA_SHA256, + url: `https://github.com/NVIDIA/OpenShell/releases/download/v${version}/openshell.rb`, }, - manifests: [ -${OPENSHELL_RELEASE_MANIFESTS.filter((manifest) => manifest !== overrides.releaseTrustOmitManifest) - .map( - (manifest) => ` { - asset: "${manifest}", - sha256: "${MANIFEST_SHA256}", - },`, - ) - .join("\n")} - ], - version: "${version}", - },`, - ) - .join("\n"); + manifests: OPENSHELL_RELEASE_MANIFESTS.filter( + (manifest) => manifest !== overrides.releaseTrustOmitManifest, + ).map((asset) => ({ asset, sha256: MANIFEST_SHA256 })), + pinLayout: { + installer: { assets: ["openshell.rb"], manifests: [...OPENSHELL_RELEASE_MANIFESTS] }, + brev: { assets: ["openshell-linux.tar.gz"], manifests: [OPENSHELL_RELEASE_MANIFESTS[0]] }, + }, + sandboxBuilds: [{ required: false, sha256: MAP_SHA256 }], + supervisor: { + image: "ghcr.io/nvidia/openshell/supervisor", + manifestDigest: `sha256:${MAP_SHA256}`, + required: false, + runtimeTemplateSha256: [MAP_SHA256], + }, + installerTemplateSha256: [MAP_SHA256], + brevTemplateSha256: [MAP_SHA256], + featureGateTemplateSha256: [MAP_SHA256], + })); const files: Record = { "nemoclaw-blueprint/blueprint.yaml": ` @@ -85,12 +89,13 @@ MIN_VERSION="${overrides.installerMin ?? openshellMin}" MAX_VERSION="${overrides.installerMax ?? openshellMax}" PIN_VERSION="${overrides.installerPinExpression ?? "$MAX_VERSION"}" `, - "scripts/checks/extract-installer-pins.mts": ` -type OpenShellReleaseTrust = unknown; -const TRUSTED_OPENSHELL_RELEASES: readonly OpenShellReleaseTrust[] = [ -${installerTrustRecords} -] as const; -`, + "ci/openshell-upgrade-trust.json": + overrides.trustRegistry ?? + JSON.stringify({ + schemaVersion: 1, + releases: installerTrustRecords, + revokedTemplateSha256: [], + }), "scripts/brev-launchable-ci-cpu.sh": ` case "$NEMOCLAW_REF" in stable | auto) OPENSHELL_VERSION="v${overrides.brevVersion ?? openshellMax}" ;; @@ -226,6 +231,64 @@ describe("dependency pin drift check", () => { ); }); + it("accepts 0.1.3 from the registry without an inline release record", () => { + withFixture( + "nemoclaw-dependency-pins-registry-", + { openshellMin: "0.1.3", openshellMax: "0.1.3" }, + (root) => expect(verifyDependencyPins(root)).toEqual([]), + ); + }); + + it("retains legacy release identities when the registry is empty", () => { + withFixture( + "nemoclaw-dependency-pins-legacy-", + { + openshellMin: "0.0.116", + openshellMax: "0.0.116", + gatewayFormulaSha256: "cf00a9441589702ffe006720fd6a9dffc0f0745b337036aad26dc53eb94c1558", + trustRegistry: JSON.stringify({ + schemaVersion: 1, + releases: [], + revokedTemplateSha256: [], + }), + }, + (root) => expect(verifyDependencyPins(root)).toEqual([]), + ); + }); + + it.each([ + ["malformed JSON", { trustRegistry: "{" }, "OpenShell release trust:"], + [ + "an unsupported schema", + { trustRegistry: '{"schemaVersion":2,"releases":[],"revokedTemplateSha256":[]}' }, + "Unsupported upgrade trust schema", + ], + [ + "duplicate versions", + { releaseTrustExtraVersion: OPENSHELL_MAX }, + "Duplicate upgrade trust registry entry", + ], + [ + "a replaced legacy artifact", + { releaseTrustExtraVersion: "0.0.116" }, + "cannot replace an existing release's artifact identities", + ], + ["an invalid digest", { releaseFormulaSha256: "invalid" }, "Invalid upgrade trust identity"], + ])("rejects %s without accepting matching consumer pins", (_name, overrides, failure) => { + withFixture("nemoclaw-dependency-pins-invalid-registry-", overrides, (root) => { + expect(verifyDependencyPins(root)).toEqual([expect.stringContaining(failure)]); + }); + }); + + it("rejects a missing registry", () => { + withFixture("nemoclaw-dependency-pins-missing-registry-", {}, (root) => { + fs.unlinkSync(path.join(root, "ci/openshell-upgrade-trust.json")); + expect(verifyDependencyPins(root)).toEqual([ + expect.stringContaining("ci/openshell-upgrade-trust.json: failed to read"), + ]); + }); + }); + it("rejects a stale Homebrew lifecycle formula pin", () => { const staleFormulaSha256 = "e".repeat(64); withFixture( @@ -331,7 +394,7 @@ describe("dependency pin drift check", () => { { releaseTrustOmitManifest: "openshell-sandbox-checksums-sha256.txt" }, (root) => { expect(verifyDependencyPins(root)).toEqual([ - "OpenShell release trust: expected one complete record for 1.2.4", + "OpenShell release trust: Installer pin extraction failed: OpenShell v1.2.4 must have exactly three trusted release-manifest digests", ]); }, );