From 0527523601c92fb13fd92a1682c517f9de695992 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 17:52:28 -0700 Subject: [PATCH 01/12] fix(security): verify pinned Ollama installer Signed-off-by: Prekshi Vyas --- src/lib/onboard/install-ollama-linux.test.ts | 56 +++++++++++++++++++- src/lib/onboard/install-ollama-linux.ts | 49 +++++++++++++---- 2 files changed, 94 insertions(+), 11 deletions(-) diff --git a/src/lib/onboard/install-ollama-linux.test.ts b/src/lib/onboard/install-ollama-linux.test.ts index 2cf375c8e6e..83a80fc04be 100644 --- a/src/lib/onboard/install-ollama-linux.test.ts +++ b/src/lib/onboard/install-ollama-linux.test.ts @@ -10,7 +10,10 @@ import { decideInstallOllamaLinuxMode, type InstallOllamaLinuxOptions, installOllamaOnLinux, + OFFICIAL_OLLAMA_INSTALLER_SHA256, + OFFICIAL_OLLAMA_INSTALLER_URL, resolveOllamaTarballArch, + sha256File, } from "./install-ollama-linux"; function makeOpts(overrides: Partial): InstallOllamaLinuxOptions { @@ -24,6 +27,7 @@ function makeOpts(overrides: Partial): InstallOllamaL runCaptureImpl: vi.fn().mockReturnValue(""), runCaptureExImpl: vi.fn().mockReturnValue({ stdout: "", exitCode: 0, timedOut: false }), runShellImpl: vi.fn().mockReturnValue({ status: 0, stdout: "", stderr: "", error: null }), + sha256FileImpl: vi.fn().mockReturnValue(OFFICIAL_OLLAMA_INSTALLER_SHA256), waitForHttpImpl: vi.fn().mockReturnValue(true), sleepSecondsImpl: vi.fn(), ensureManagedOllamaLoopbackSystemdOverrideImpl: vi.fn().mockReturnValue("ready"), @@ -50,6 +54,21 @@ describe("resolveOllamaTarballArch", () => { }); }); +describe("sha256File", () => { + it("computes a lowercase SHA-256 identity for downloaded bytes", () => { + const directory = fs.mkdtempSync("/tmp/nemoclaw-ollama-integrity-"); + const file = `${directory}/install.sh`; + try { + fs.writeFileSync(file, "#!/bin/sh\nexit 0\n"); + expect(sha256File(file)).toBe( + "306c6ca7407560340797866e077e053627ad409277d1b9da58106fce4cf717cb", + ); + } finally { + fs.rmSync(directory, { recursive: true, force: true }); + } + }); +}); + describe("decideInstallOllamaLinuxMode", () => { const originalEnv = process.env.NEMOCLAW_OLLAMA_INSTALL_MODE; @@ -488,6 +507,40 @@ describe("installOllamaOnLinux (system)", () => { } }); + it("rejects installer content whose digest differs from the pinned identity", () => { + let installerPath = ""; + const runCaptureExImpl = vi.fn().mockImplementation((command: readonly string[]) => { + installerPath = outputPathFromCurlCommand(command); + fs.writeFileSync(installerPath, "#!/bin/sh\nprintf substituted\n"); + return { stdout: "", stderr: "", exitCode: 0, timedOut: false }; + }); + const runShellImpl = vi.fn(); + const errorLog = vi.fn(); + const exitSpy = vi.spyOn(process, "exit").mockImplementation(((code?: number) => { + throw new Error(`process.exit(${code})`); + }) as never); + + try { + expect(() => + installOllamaOnLinux( + makeOpts({ + modeOverride: "system", + runCaptureImpl: vi.fn().mockReturnValue("/usr/bin/zstd"), + runCaptureExImpl, + runShellImpl, + sha256FileImpl: sha256File, + errorLog, + }), + ), + ).toThrow("process.exit(1)"); + expect(runShellImpl).not.toHaveBeenCalled(); + expect(errorLog).toHaveBeenCalledWith(expect.stringContaining("integrity check failed")); + expect(fs.existsSync(installerPath)).toBe(false); + } finally { + exitSpy.mockRestore(); + } + }); + it("does not retry an installer that exits nonzero (#9698)", () => { let installerPath = ""; const runCaptureExImpl = vi.fn().mockImplementation((command: readonly string[]) => { @@ -541,13 +594,14 @@ describe("installOllamaOnLinux (system)", () => { const result = installOllamaOnLinux(opts); expect(result).toEqual({ ok: true, mode: "system", binPath: "/usr/local/bin/ollama" }); const fetchCall = runCaptureExImpl.mock.calls.find(([command]) => - Array.isArray(command) ? command.includes("https://ollama.com/install.sh") : false, + Array.isArray(command) ? command.includes(OFFICIAL_OLLAMA_INSTALLER_URL) : false, )?.[0] as readonly string[] | undefined; expect(fetchCall).toContain("--connect-timeout"); expect(fetchCall).toContain("--max-time"); expect(fetchCall).toContain("--retry-max-time"); expect(fetchCall).toContain("--proto-redir"); expect(fetchCall).not.toContain("--insecure"); + expect(opts.sha256FileImpl).toHaveBeenCalled(); const installCall = findRunShellCall(runShellImpl, "sh '"); expect(installCall).toBeDefined(); expect(installCall).not.toContain("curl"); diff --git a/src/lib/onboard/install-ollama-linux.ts b/src/lib/onboard/install-ollama-linux.ts index b59ce76d6a4..655080ab064 100644 --- a/src/lib/onboard/install-ollama-linux.ts +++ b/src/lib/onboard/install-ollama-linux.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import nodePath from "node:path"; @@ -36,16 +37,23 @@ const { setResolvedOllamaHost, }: typeof import("../inference/local") = require("../inference/local"); -const OFFICIAL_OLLAMA_INSTALLER_URL = "https://ollama.com/install.sh"; +export const OFFICIAL_OLLAMA_INSTALLER_URL = + "https://raw.githubusercontent.com/ollama/ollama/de25dd526f4c9ba367ee69022168c6c5f2dc3285/scripts/install.sh"; +export const OFFICIAL_OLLAMA_INSTALLER_SHA256 = + "25f64b810b947145095956533e1bdf56eacea2673c55a7e586be4515fc882c9f"; const OFFICIAL_OLLAMA_INSTALLER_PROCESS_TIMEOUT_MS = 190_000; +export function sha256File(filePath: string): string { + return createHash("sha256").update(fs.readFileSync(filePath)).digest("hex"); +} + /** * Install location modes. * - * - `system` installs into `/usr/local` via the official Ollama - * installer script (`https://ollama.com/install.sh`). Requires - * sudo, configures a systemd service, and writes to a system - * user (`ollama`). This is the historical path. + * - `system` installs into `/usr/local` via a digest-verified snapshot of + * the official Ollama installer. Requires sudo, configures a + * systemd service, and writes to a system user (`ollama`). + * This is the historical path. * - `user-local` installs into `${HOME}/.local` by downloading the official * release tarball directly and extracting it as the invoking * user. No sudo, no systemd, no system user. The daemon is @@ -67,6 +75,8 @@ export type InstallOllamaLinuxOptions = InstallOllamaLinuxModeOptions & { arch?: () => NodeJS.Architecture; /** Test seam: override `runShell`. */ runShellImpl?: typeof runShell; + /** Test seam: override local SHA-256 calculation. */ + sha256FileImpl?: typeof sha256File; /** Test seam: override systemd loopback override. */ ensureManagedOllamaLoopbackSystemdOverrideImpl?: typeof ensureManagedOllamaLoopbackSystemdOverride; /** Minimum daemon context length to request for the selected agent. */ @@ -119,17 +129,18 @@ function detectJetpackVariant(opts: InstallOllamaLinuxOptions): "jetpack5" | "je } /** - * Run the official `https://ollama.com/install.sh`. Sudo-bound. Configures - * the systemd `ollama.service`, creates the `ollama` system user, and - * installs CUDA drivers when applicable. An upgrade that replaces a stale - * binary asks the installer for `MIN_OLLAMA_VERSION` by name; a fresh install - * has no floor to satisfy and takes latest. + * Run the pinned official Ollama installer. Sudo-bound. Configures the + * systemd `ollama.service`, creates the `ollama` system user, and installs + * CUDA drivers when applicable. An upgrade that replaces a stale binary asks + * the installer for `MIN_OLLAMA_VERSION` by name; a fresh install has no floor + * to satisfy and takes latest. */ function runOfficialInstallScript(opts: InstallOllamaLinuxOptions): void { const log = opts.log ?? ((m: string) => console.log(m)); const errorLog = opts.errorLog ?? ((m: string) => console.error(m)); const runCaptureExImpl = opts.runCaptureExImpl ?? runCaptureEx; const runShellImpl = opts.runShellImpl ?? runShell; + const sha256FileImpl = opts.sha256FileImpl ?? sha256File; ensureOllamaLinuxExtractionDependencies(opts); log( " The Ollama installer creates a system user, a systemd service, and writes to /usr/local. " + @@ -182,6 +193,24 @@ function runOfficialInstallScript(opts: InstallOllamaLinuxOptions): void { message: ` Ollama installer download failed after bounded retries (exit ${fetchResult.exitCode ?? "unknown"}).`, }; } else { + let actualSha256 = ""; + try { + actualSha256 = sha256FileImpl(installerPath); + } catch (error) { + failure = { + exitCode: 1, + message: ` Unable to verify Ollama installer integrity: ${error instanceof Error ? error.message : String(error)}`, + }; + } + if (!failure && actualSha256 !== OFFICIAL_OLLAMA_INSTALLER_SHA256) { + failure = { + exitCode: 1, + message: + " Ollama installer integrity check failed; refusing to execute downloaded content.", + }; + } + } + if (!failure) { const installResult = runShellImpl(`${versionPin}sh ${shellQuote(installerPath)}`, { ignoreError: true, stdio: "inherit", From d69b8740e36b04292b7af8e2f4bf492a51dd7837 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 18:03:42 -0700 Subject: [PATCH 02/12] fix(security): exclude nested Docker context secrets Signed-off-by: Prekshi Vyas --- .dockerignore | 52 +++++++++--------- ci/source-shape-test-budget.json | 5 ++ .../dockerignore-security-contract.test.ts | 54 +++++++++++++++++++ 3 files changed, 85 insertions(+), 26 deletions(-) create mode 100644 test/repository/dockerignore-security-contract.test.ts diff --git a/.dockerignore b/.dockerignore index b999f3f050a..49764926862 100644 --- a/.dockerignore +++ b/.dockerignore @@ -21,29 +21,29 @@ Thumbs.db # Security: secrets, credentials, and keys # Mirror .gitignore security patterns to prevent sensitive files from # being sent to the Docker daemon and permanently baked into image layers. -.env -.env.* -.envrc -.npmrc -.netrc -.pypirc -.direnv/ -.ssh/ -secrets/ -.credentials -*.key -*.pem -*.pfx -*.p12 -*.jks -*.keystore -*.tfvars -*_ecdsa -*_ed25519 -*_rsa -credentials.json -key.json -secrets.json -secrets.yaml -service-account*.json -token.json +**/.env +**/.env.* +**/.envrc +**/.npmrc +**/.netrc +**/.pypirc +**/.direnv/ +**/.ssh/ +**/secrets/ +**/.credentials +**/*.key +**/*.pem +**/*.pfx +**/*.p12 +**/*.jks +**/*.keystore +**/*.tfvars +**/*_ecdsa +**/*_ed25519 +**/*_rsa +**/credentials.json +**/key.json +**/secrets.json +**/secrets.yaml +**/service-account*.json +**/token.json diff --git a/ci/source-shape-test-budget.json b/ci/source-shape-test-budget.json index 3518016a419..cff9883f1db 100644 --- a/ci/source-shape-test-budget.json +++ b/ci/source-shape-test-budget.json @@ -1,6 +1,11 @@ { "maxSourceShapeCases": 0, "sourceShapeContractExceptions": [ + { + "file": "test/repository/dockerignore-security-contract.test.ts", + "test": "excludes secret-bearing names at every directory depth", + "category": "security" + }, { "file": "src/lib/readiness/host.test.ts", "test": "bounds and redacts successful probe text before schema validation", diff --git a/test/repository/dockerignore-security-contract.test.ts b/test/repository/dockerignore-security-contract.test.ts new file mode 100644 index 00000000000..206a8e17790 --- /dev/null +++ b/test/repository/dockerignore-security-contract.test.ts @@ -0,0 +1,54 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import path from "node:path"; + +import { describe, expect, it } from "vitest"; + +const REPO_ROOT = path.resolve(import.meta.dirname, "../.."); +const DOCKERIGNORE_PATH = path.join(REPO_ROOT, ".dockerignore"); + +describe("Docker build context secret exclusions", () => { + // source-shape-contract: security -- Recursive exclusions keep nested credentials outside every Docker build context consumer. + it("excludes secret-bearing names at every directory depth", () => { + const rules = new Set( + fs + .readFileSync(DOCKERIGNORE_PATH, "utf8") + .split(/\r?\n/u) + .map((line) => line.trim()) + .filter((line) => line && !line.startsWith("#")), + ); + const secretPatterns = [ + ".env", + ".env.*", + ".envrc", + ".npmrc", + ".netrc", + ".pypirc", + ".direnv/", + ".ssh/", + "secrets/", + ".credentials", + "*.key", + "*.pem", + "*.pfx", + "*.p12", + "*.jks", + "*.keystore", + "*.tfvars", + "*_ecdsa", + "*_ed25519", + "*_rsa", + "credentials.json", + "key.json", + "secrets.json", + "secrets.yaml", + "service-account*.json", + "token.json", + ] as const; + + expect(secretPatterns.filter((pattern) => !rules.has(`**/${pattern}`))).toEqual([]); + expect(secretPatterns.filter((pattern) => rules.has(pattern))).toEqual([]); + }); +}); From 412dbe525d9c97898d62f2d1e12b4c439c4de2aa Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 18:04:47 -0700 Subject: [PATCH 03/12] fix(tools): isolate candidate validation credentials Signed-off-by: Prekshi Vyas --- .../index.ts | 20 +++++++++++++++++-- .dsh/tools/run_targeted_vitest/index.ts | 19 ++++++++++++++++-- 2 files changed, 35 insertions(+), 4 deletions(-) diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index 8f575ed3ff1..afee470d0a3 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -90,6 +90,22 @@ export default async function run_nemoclaw_focused_repair_validation(input: { ]); if (!projects.every((x) => allowed.has(x))) throw new Error("Unsupported Vitest project"); const q = (v) => "'" + String(v).replaceAll("'", "'\"'\"'") + "'", + isolate = (command) => + [ + "umask 077", + 'isolation_root=$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/nemoclaw-validation.XXXXXX") || exit 1', + "trap '/bin/rm -rf -- \"$isolation_root\"' EXIT", + "/usr/bin/env -i" + + ' HOME="$isolation_root"' + + ' XDG_CONFIG_HOME="$isolation_root"' + + ' TMPDIR="$isolation_root"' + + ' PATH="$PATH"' + + " CI=true NO_COLOR=1 TERM=dumb" + + " NPM_CONFIG_USERCONFIG=/dev/null" + + " GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1" + + " /bin/sh -c " + + q(command), + ].join("; "), commands = [], oxc = files.filter((f) => /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/.test(f)); if (oxc.length) { @@ -175,9 +191,9 @@ export default async function run_nemoclaw_focused_repair_validation(input: { const steps = []; for (const item of commands) { const r = await tools.bash({ - command: item.command, + command: isolate(item.command), workdir: input.workdir, - description: "Run focused repair validation", + description: "Run credential-isolated focused repair validation", timeoutMs, }); if (r.kind !== "foreground") throw new Error("Unexpected background result"); diff --git a/.dsh/tools/run_targeted_vitest/index.ts b/.dsh/tools/run_targeted_vitest/index.ts index b149f2a7f96..29fc36a00de 100644 --- a/.dsh/tools/run_targeted_vitest/index.ts +++ b/.dsh/tools/run_targeted_vitest/index.ts @@ -79,10 +79,25 @@ export default async function run_targeted_vitest(input: { const clipMode = input.clipMode ?? "tail"; if (!new Set(["head", "tail"]).has(clipMode)) throw new Error("clipMode must be head or tail"); const command = "npx " + args.map(quote).join(" "); + const isolatedCommand = [ + "umask 077", + 'isolation_root=$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/nemoclaw-validation.XXXXXX") || exit 1', + "trap '/bin/rm -rf -- \"$isolation_root\"' EXIT", + "/usr/bin/env -i" + + ' HOME="$isolation_root"' + + ' XDG_CONFIG_HOME="$isolation_root"' + + ' TMPDIR="$isolation_root"' + + ' PATH="$PATH"' + + " CI=true NO_COLOR=1 TERM=dumb" + + " NPM_CONFIG_USERCONFIG=/dev/null" + + " GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1" + + " /bin/sh -c " + + quote(command), + ].join("; "); const result = await tools.bash({ - command, + command: isolatedCommand, workdir: input.workdir, - description: "Run selected Vitest files", + description: "Run selected Vitest files without host credentials", timeoutMs, }); if (result.kind !== "foreground") throw new Error("Unexpected background result"); From ad4266e85a17bce1159ec99f59e716220a23c0f6 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 19:45:19 -0700 Subject: [PATCH 04/12] fix(tools): enforce validation filesystem isolation Signed-off-by: Prekshi Vyas --- .../index.ts | 93 ++++++++++++++++--- .dsh/tools/run_targeted_vitest/index.ts | 93 ++++++++++++++++--- .../install-ollama-linux-upgrade.test.ts | 2 + test/helpers/onboard-child-runtime.ts | 31 ++++++- ...board-ollama-upgrade-version-floor.test.ts | 2 + test/onboarding/onboard-selection.test.ts | 4 +- 6 files changed, 192 insertions(+), 33 deletions(-) diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index afee470d0a3..1b0fe7d95a5 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -91,21 +91,84 @@ export default async function run_nemoclaw_focused_repair_validation(input: { if (!projects.every((x) => allowed.has(x))) throw new Error("Unsupported Vitest project"); const q = (v) => "'" + String(v).replaceAll("'", "'\"'\"'") + "'", isolate = (command) => - [ - "umask 077", - 'isolation_root=$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/nemoclaw-validation.XXXXXX") || exit 1', - "trap '/bin/rm -rf -- \"$isolation_root\"' EXIT", - "/usr/bin/env -i" + - ' HOME="$isolation_root"' + - ' XDG_CONFIG_HOME="$isolation_root"' + - ' TMPDIR="$isolation_root"' + - ' PATH="$PATH"' + - " CI=true NO_COLOR=1 TERM=dumb" + - " NPM_CONFIG_USERCONFIG=/dev/null" + - " GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1" + - " /bin/sh -c " + - q(command), - ].join("; "), + `set -eu +umask 077 +repo_root=$(/bin/pwd -P) +isolation_root=$(/usr/bin/mktemp -d /tmp/nemoclaw-validation.XXXXXX) +isolation_root=$(cd "$isolation_root" && /bin/pwd -P) +trap '/bin/rm -R -f -- "$isolation_root"' EXIT +/bin/mkdir -p "$isolation_root/home" "$isolation_root/tmp" + +if [ -x /usr/bin/sandbox-exec ]; then + sandbox_profile="$isolation_root/profile.sb" + cat >"$sandbox_profile" <<'PROFILE' +(version 1) +(deny default) +(allow process*) +(allow signal (target same-sandbox)) +(allow sysctl-read) +(allow mach-lookup + (global-name "com.apple.trustd") + (global-name "com.apple.trustd.agent")) +(allow file-read-metadata) +(allow file-read-data (literal "/")) +(allow file-read* + (subpath "/System") + (subpath "/usr") + (subpath "/bin") + (subpath "/sbin") + (subpath "/opt/homebrew") + (subpath "/usr/local") + (subpath "/Library") + (subpath "/private/etc") + (subpath "/private/var/db") + (subpath "/dev") + (subpath (param "REPO_ROOT")) + (subpath (param "ISOLATION_ROOT"))) +(allow file-write* + (subpath (param "REPO_ROOT")) + (subpath (param "ISOLATION_ROOT")) + (literal "/dev/null")) +(deny file-write* (subpath (string-append (param "REPO_ROOT") "/.git"))) +(allow network*) +PROFILE + set +e + /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ + -f "$sandbox_profile" /usr/bin/env -i \ + HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ + PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + CI=true NO_COLOR=1 TERM=dumb \ + NPM_CONFIG_USERCONFIG=/dev/null \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + /bin/sh -c ${q(command)} + validation_status=$? + set -e + exit "$validation_status" +fi + +if command -v bwrap >/dev/null 2>&1; then + set -- "$(command -v bwrap)" --die-with-parent --new-session --unshare-all --share-net + set -- "$@" --proc /proc --dev /dev --tmpfs /tmp --dir /home + set -- "$@" --bind "$isolation_root/home" /home/validator --bind "$repo_root" /workspace + if [ -e "$repo_root/.git" ]; then set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git; fi + for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do + if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi + done + set +e + "$@" --chdir /workspace /usr/bin/env -i \ + HOME=/home/validator XDG_CONFIG_HOME=/home/validator TMPDIR=/tmp \ + PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + CI=true NO_COLOR=1 TERM=dumb \ + NPM_CONFIG_USERCONFIG=/dev/null \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + /bin/sh -c ${q(command)} + validation_status=$? + set -e + exit "$validation_status" +fi + +printf '%s\n' 'Credential-isolated validation requires sandbox-exec or bubblewrap.' >&2 +exit 126`, commands = [], oxc = files.filter((f) => /\.(cjs|cts|js|jsx|mjs|mts|ts|tsx)$/.test(f)); if (oxc.length) { diff --git a/.dsh/tools/run_targeted_vitest/index.ts b/.dsh/tools/run_targeted_vitest/index.ts index 29fc36a00de..eed34bee1e0 100644 --- a/.dsh/tools/run_targeted_vitest/index.ts +++ b/.dsh/tools/run_targeted_vitest/index.ts @@ -79,21 +79,84 @@ export default async function run_targeted_vitest(input: { const clipMode = input.clipMode ?? "tail"; if (!new Set(["head", "tail"]).has(clipMode)) throw new Error("clipMode must be head or tail"); const command = "npx " + args.map(quote).join(" "); - const isolatedCommand = [ - "umask 077", - 'isolation_root=$(/usr/bin/mktemp -d "${TMPDIR:-/tmp}/nemoclaw-validation.XXXXXX") || exit 1', - "trap '/bin/rm -rf -- \"$isolation_root\"' EXIT", - "/usr/bin/env -i" + - ' HOME="$isolation_root"' + - ' XDG_CONFIG_HOME="$isolation_root"' + - ' TMPDIR="$isolation_root"' + - ' PATH="$PATH"' + - " CI=true NO_COLOR=1 TERM=dumb" + - " NPM_CONFIG_USERCONFIG=/dev/null" + - " GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1" + - " /bin/sh -c " + - quote(command), - ].join("; "); + const isolatedCommand = `set -eu +umask 077 +repo_root=$(/bin/pwd -P) +isolation_root=$(/usr/bin/mktemp -d /tmp/nemoclaw-validation.XXXXXX) +isolation_root=$(cd "$isolation_root" && /bin/pwd -P) +trap '/bin/rm -R -f -- "$isolation_root"' EXIT +/bin/mkdir -p "$isolation_root/home" "$isolation_root/tmp" + +if [ -x /usr/bin/sandbox-exec ]; then + sandbox_profile="$isolation_root/profile.sb" + cat >"$sandbox_profile" <<'PROFILE' +(version 1) +(deny default) +(allow process*) +(allow signal (target same-sandbox)) +(allow sysctl-read) +(allow mach-lookup + (global-name "com.apple.trustd") + (global-name "com.apple.trustd.agent")) +(allow file-read-metadata) +(allow file-read-data (literal "/")) +(allow file-read* + (subpath "/System") + (subpath "/usr") + (subpath "/bin") + (subpath "/sbin") + (subpath "/opt/homebrew") + (subpath "/usr/local") + (subpath "/Library") + (subpath "/private/etc") + (subpath "/private/var/db") + (subpath "/dev") + (subpath (param "REPO_ROOT")) + (subpath (param "ISOLATION_ROOT"))) +(allow file-write* + (subpath (param "REPO_ROOT")) + (subpath (param "ISOLATION_ROOT")) + (literal "/dev/null")) +(deny file-write* (subpath (string-append (param "REPO_ROOT") "/.git"))) +(allow network*) +PROFILE + set +e + /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ + -f "$sandbox_profile" /usr/bin/env -i \ + HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ + PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + CI=true NO_COLOR=1 TERM=dumb \ + NPM_CONFIG_USERCONFIG=/dev/null \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + /bin/sh -c ${quote(command)} + validation_status=$? + set -e + exit "$validation_status" +fi + +if command -v bwrap >/dev/null 2>&1; then + set -- "$(command -v bwrap)" --die-with-parent --new-session --unshare-all --share-net + set -- "$@" --proc /proc --dev /dev --tmpfs /tmp --dir /home + set -- "$@" --bind "$isolation_root/home" /home/validator --bind "$repo_root" /workspace + if [ -e "$repo_root/.git" ]; then set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git; fi + for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do + if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi + done + set +e + "$@" --chdir /workspace /usr/bin/env -i \ + HOME=/home/validator XDG_CONFIG_HOME=/home/validator TMPDIR=/tmp \ + PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + CI=true NO_COLOR=1 TERM=dumb \ + NPM_CONFIG_USERCONFIG=/dev/null \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + /bin/sh -c ${quote(command)} + validation_status=$? + set -e + exit "$validation_status" +fi + +printf '%s\n' 'Credential-isolated validation requires sandbox-exec or bubblewrap.' >&2 +exit 126`; const result = await tools.bash({ command: isolatedCommand, workdir: input.workdir, diff --git a/src/lib/onboard/install-ollama-linux-upgrade.test.ts b/src/lib/onboard/install-ollama-linux-upgrade.test.ts index 8b7f4494bc4..94364b9f5cb 100644 --- a/src/lib/onboard/install-ollama-linux-upgrade.test.ts +++ b/src/lib/onboard/install-ollama-linux-upgrade.test.ts @@ -8,6 +8,7 @@ import { decideInstallOllamaLinuxMode, type InstallOllamaLinuxOptions, installOllamaOnLinux, + OFFICIAL_OLLAMA_INSTALLER_SHA256, } from "./install-ollama-linux"; function makeOpts(overrides: Partial): InstallOllamaLinuxOptions { @@ -21,6 +22,7 @@ function makeOpts(overrides: Partial): InstallOllamaL runCaptureImpl: vi.fn().mockReturnValue(""), runCaptureExImpl: vi.fn().mockReturnValue({ stdout: "", exitCode: 0, timedOut: false }), runShellImpl: vi.fn().mockReturnValue({ status: 0, stdout: "", stderr: "", error: null }), + sha256FileImpl: vi.fn().mockReturnValue(OFFICIAL_OLLAMA_INSTALLER_SHA256), waitForHttpImpl: vi.fn().mockReturnValue(true), sleepSecondsImpl: vi.fn(), ensureManagedOllamaLoopbackSystemdOverrideImpl: vi.fn().mockReturnValue("ready"), diff --git a/test/helpers/onboard-child-runtime.ts b/test/helpers/onboard-child-runtime.ts index 6a06e6619f0..e4bd55dfa02 100644 --- a/test/helpers/onboard-child-runtime.ts +++ b/test/helpers/onboard-child-runtime.ts @@ -2,8 +2,30 @@ // SPDX-License-Identifier: Apache-2.0 import { MIN_OLLAMA_VERSION } from "../../src/lib/inference/ollama-version.js"; +import { OFFICIAL_OLLAMA_INSTALLER_SHA256 } from "../../src/lib/onboard/install-ollama-linux.js"; export const onboardChildRuntimeSource = String.raw` +const childCrypto = require("node:crypto"); +const childFs = require("node:fs"); +const verifiedOllamaInstallerFixture = Buffer.from("verified Ollama installer fixture"); +const originalChildCreateHash = childCrypto.createHash; +childCrypto.createHash = (algorithm, options) => { + const hash = originalChildCreateHash(algorithm, options); + const originalUpdate = hash.update.bind(hash); + const originalDigest = hash.digest.bind(hash); + let hashesVerifiedInstallerFixture = false; + hash.update = (data, inputEncoding) => { + hashesVerifiedInstallerFixture = + Buffer.isBuffer(data) && data.equals(verifiedOllamaInstallerFixture); + return hashesVerifiedInstallerFixture ? hash : originalUpdate(data, inputEncoding); + }; + hash.digest = (encoding) => + hashesVerifiedInstallerFixture + ? ${JSON.stringify(OFFICIAL_OLLAMA_INSTALLER_SHA256)} + : originalDigest(encoding); + return hash; +}; + function supportedOllamaHostMetadataOutput(command) { if (command.includes("ollama --version")) { return ${JSON.stringify(`ollama version is ${MIN_OLLAMA_VERSION}`)}; @@ -45,7 +67,14 @@ function createSuccessfulOllamaServiceExecutionProofRunner(fallback, systemdProo const runFallback = typeof fallback === "function" ? fallback - : () => ({ stdout: "", stderr: "", exitCode: 0, timedOut: false }); + : (command) => { + const argv = Array.isArray(command) ? command : []; + const outputIndex = argv.indexOf("--output"); + if (outputIndex >= 0 && typeof argv[outputIndex + 1] === "string") { + childFs.writeFileSync(argv[outputIndex + 1], verifiedOllamaInstallerFixture); + } + return { stdout: "", stderr: "", exitCode: 0, timedOut: false }; + }; return (command, options) => { const argv = Array.isArray(command) ? command : []; diff --git a/test/onboarding/onboard-ollama-upgrade-version-floor.test.ts b/test/onboarding/onboard-ollama-upgrade-version-floor.test.ts index b531afc6a07..31129b8de48 100644 --- a/test/onboarding/onboard-ollama-upgrade-version-floor.test.ts +++ b/test/onboarding/onboard-ollama-upgrade-version-floor.test.ts @@ -9,6 +9,7 @@ import { MIN_OLLAMA_VERSION } from "../../src/lib/inference/ollama-version.js"; import { type InstallOllamaLinuxOptions, installOllamaOnLinux, + OFFICIAL_OLLAMA_INSTALLER_SHA256, } from "../../src/lib/onboard/install-ollama-linux.js"; import { assertOllamaUpgradeApplied, @@ -49,6 +50,7 @@ function makeInstallOptions( .fn() .mockReturnValue({ stdout: "", stderr: "", exitCode: 0, timedOut: false }), runShellImpl: vi.fn().mockReturnValue({ status: 0, stdout: "", stderr: "", error: null }), + sha256FileImpl: vi.fn().mockReturnValue(OFFICIAL_OLLAMA_INSTALLER_SHA256), waitForHttpImpl: vi.fn().mockReturnValue(true), sleepSecondsImpl: vi.fn(), ensureManagedOllamaLoopbackSystemdOverrideImpl: vi.fn().mockReturnValue("ready"), diff --git a/test/onboarding/onboard-selection.test.ts b/test/onboarding/onboard-selection.test.ts index 7c7e8b55316..c63849e4cff 100644 --- a/test/onboarding/onboard-selection.test.ts +++ b/test/onboarding/onboard-selection.test.ts @@ -32,6 +32,7 @@ import { createInferenceSelectionValidationHelpers } from "../../src/lib/onboard import { type InstallOllamaLinuxOptions, installOllamaOnLinux, + OFFICIAL_OLLAMA_INSTALLER_SHA256, } from "../../src/lib/onboard/install-ollama-linux.js"; import { getWindowsHostOllamaDockerRequirement } from "../../src/lib/onboard/local-inference-topology.js"; import { @@ -235,6 +236,7 @@ function makeInstallOllamaLinuxOptions( .fn() .mockReturnValue({ stdout: "", stderr: "", exitCode: 0, timedOut: false }), runShellImpl: vi.fn().mockReturnValue({ status: 0, stdout: "", stderr: "", error: null }), + sha256FileImpl: vi.fn().mockReturnValue(OFFICIAL_OLLAMA_INSTALLER_SHA256), waitForHttpImpl: vi.fn().mockReturnValue(true), sleepSecondsImpl: vi.fn(), ensureManagedOllamaLoopbackSystemdOverrideImpl: vi.fn().mockReturnValue("ready"), @@ -473,7 +475,6 @@ function makeSetupNimOllamaDeps(overrides: Partial = {}): Se ensureOllamaLoopbackSystemdOverride: () => "not-applicable", runOllamaStartupOrGate: () => ({ kind: "ready" }), shouldFrontOllamaWithProxy: () => false, - // Proxy startup is deferred until configuration review acceptance. getLocalProviderBaseUrl: () => "http://host.docker.internal:11434/v1", selectAndValidateOllamaModel: async () => ({ outcome: "selected", @@ -2047,7 +2048,6 @@ wait.sleepSeconds = () => {}; // installOllamaSystem probes loopback at tries=1 before launching, then // waits at tries=10 after launch. The fake curl in these tests answers 200 // to any URL, so real waitForHttp would short-circuit the manual launch. -// Differentiate by tries count. wait.waitForHttp = (_url, tries) => (tries ?? 0) > 1; const { setupNim } = require(${onboardPath}); From 05655f7974c9b4ac8e60c31b5a6f41c3f5b9d0ad Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 19:46:42 -0700 Subject: [PATCH 05/12] ci(images): refresh Pi qualification receipts Signed-off-by: Prekshi Vyas --- 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 da108187f6e..71910d2017a 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:a4a531c77f0ecaaf05e1cdee8f84e0143a9036ec78788127d247708fa2d77597", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:a4a531c77f0ecaaf05e1cdee8f84e0143a9036ec78788127d247708fa2d77597", + "digest": "sha256:7a830e547e3bd10fad0f3486a2b6629ee6547e645aec0312ab1e461c290b0951", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:7a830e547e3bd10fad0f3486a2b6629ee6547e645aec0312ab1e461c290b0951", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "b3ab6c221a6187796eebceca6ad013d1e304ff4b", + "revision": "412dbe525d9c97898d62f2d1e12b4c439c4de2aa", "release": "v0.1.0", - "cohort": "ghrun-39497514794-1" + "cohort": "ghrun-39706025962-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 4e1f9211059..30174c63624 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:bed1d1b6fa7bd42f3f606972e564b8f9641c3b8ed0533434965adc52ac5c14ec", - "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:bed1d1b6fa7bd42f3f606972e564b8f9641c3b8ed0533434965adc52ac5c14ec", + "digest": "sha256:346759e626d469afb1013dfdcb4c0107c32ebc6db178df2cc337b1a415d339ac", + "reference": "ghcr.io/nvidia/nemoclaw/pi-sandbox@sha256:346759e626d469afb1013dfdcb4c0107c32ebc6db178df2cc337b1a415d339ac", "source": { "repository": "NVIDIA/NemoClaw", - "revision": "b3ab6c221a6187796eebceca6ad013d1e304ff4b", + "revision": "412dbe525d9c97898d62f2d1e12b4c439c4de2aa", "release": "v0.1.0", - "cohort": "ghrun-39497514794-1" + "cohort": "ghrun-39706025962-1" }, "startupProfileContractVersion": 1, "capabilityContractVersion": 1 diff --git a/src/lib/agent/candidate-authority.ts b/src/lib/agent/candidate-authority.ts index c7e5a482693..4d147ae03da 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([ - "4e8edda5bfc6dafe4ce3c0a1458229ce99dc3334bca174df5b4aedbd2b2a1365", - "6267cb30f8085e6ac129a1f3824f6ba84a291c9dedee2263e070e99798a4145d", + "a6fff3dd5d2e2fa16f5c6198e403f0de5d12671312715bf1ca06172917400a7e", + "1dc45d8071c8ace1a59ef38f8579b3b59f024e0e7f6e824a11c4009b8c03a100", ]), }); From f9b685bdeaf2dd10059e4e193e24b0703ab0dfa3 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 20:31:49 -0700 Subject: [PATCH 06/12] fix(tools): support isolated worktree validation --- .../index.ts | 37 ++++++++++++++++--- .dsh/tools/run_targeted_vitest/index.ts | 37 ++++++++++++++++--- .../external-component/activation.test.ts | 14 +++++-- .../external-component/onboarding.test.ts | 6 ++- src/lib/onboard/install-ollama-linux.test.ts | 4 +- .../hermes/hermes-tool-gateway-broker.test.ts | 26 ++++++++++--- test/e2e/support/dgx-station-express.test.ts | 5 ++- ...me-qualification-account-lifecycle.test.ts | 5 ++- ...le-profile-cgroup-cleanup-workflow.test.ts | 3 +- .../portable-profile-systemctl-shim.test.ts | 8 ++-- ...ows-mxc-openclaw-process-container.test.ts | 5 ++- test/helpers/bounded-temp-root.ts | 19 ++++++++++ test/helpers/onboard-child-runtime.test.ts | 6 +-- 13 files changed, 143 insertions(+), 32 deletions(-) create mode 100644 test/helpers/bounded-temp-root.ts diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index 1b0fe7d95a5..912d79468d1 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -94,10 +94,25 @@ export default async function run_nemoclaw_focused_repair_validation(input: { `set -eu umask 077 repo_root=$(/bin/pwd -P) -isolation_root=$(/usr/bin/mktemp -d /tmp/nemoclaw-validation.XXXXXX) +isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX) isolation_root=$(cd "$isolation_root" && /bin/pwd -P) trap '/bin/rm -R -f -- "$isolation_root"' EXIT /bin/mkdir -p "$isolation_root/home" "$isolation_root/tmp" +git_dir=$(/usr/bin/git -C "$repo_root" rev-parse --absolute-git-dir) +git_common_dir=$(/usr/bin/git -C "$repo_root" rev-parse --path-format=absolute --git-common-dir) +git_dir=$(cd "$git_dir" && /bin/pwd -P) +git_common_dir=$(cd "$git_common_dir" && /bin/pwd -P) +git_worktree_name= +if [ -f "$repo_root/.git" ]; then + git_worktree_name=\${git_dir##*/} + case "$git_worktree_name" in + ''|*[!A-Za-z0-9._-]*) printf '%s\n' 'Unsupported Git worktree metadata path.' >&2; exit 126 ;; + esac + if [ "$git_dir" != "$git_common_dir/worktrees/$git_worktree_name" ]; then + printf '%s\n' 'Git worktree metadata must belong to its common Git directory.' >&2 + exit 126 + fi +fi if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" @@ -124,22 +139,27 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath "/private/var/db") (subpath "/dev") (subpath (param "REPO_ROOT")) - (subpath (param "ISOLATION_ROOT"))) + (subpath (param "ISOLATION_ROOT")) + (subpath (param "GIT_DIR")) + (subpath (param "GIT_COMMON_DIR"))) (allow file-write* (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) (literal "/dev/null")) (deny file-write* (subpath (string-append (param "REPO_ROOT") "/.git"))) +(deny file-write* (subpath (param "GIT_DIR"))) +(deny file-write* (subpath (param "GIT_COMMON_DIR"))) (allow network*) PROFILE set +e /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ + -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ - GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ /bin/sh -c ${q(command)} validation_status=$? set -e @@ -150,7 +170,14 @@ if command -v bwrap >/dev/null 2>&1; then set -- "$(command -v bwrap)" --die-with-parent --new-session --unshare-all --share-net set -- "$@" --proc /proc --dev /dev --tmpfs /tmp --dir /home set -- "$@" --bind "$isolation_root/home" /home/validator --bind "$repo_root" /workspace - if [ -e "$repo_root/.git" ]; then set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git; fi + if [ -n "$git_worktree_name" ]; then + git_pointer="$isolation_root/git-pointer" + printf 'gitdir: /git/worktrees/%s\n' "$git_worktree_name" >"$git_pointer" + set -- "$@" --dir /git --ro-bind "$git_common_dir" /git + set -- "$@" --ro-bind "$git_pointer" /workspace/.git + else + set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git + fi for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi done @@ -160,7 +187,7 @@ if command -v bwrap >/dev/null 2>&1; then PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ - GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ /bin/sh -c ${q(command)} validation_status=$? set -e diff --git a/.dsh/tools/run_targeted_vitest/index.ts b/.dsh/tools/run_targeted_vitest/index.ts index eed34bee1e0..5158be77590 100644 --- a/.dsh/tools/run_targeted_vitest/index.ts +++ b/.dsh/tools/run_targeted_vitest/index.ts @@ -82,10 +82,25 @@ export default async function run_targeted_vitest(input: { const isolatedCommand = `set -eu umask 077 repo_root=$(/bin/pwd -P) -isolation_root=$(/usr/bin/mktemp -d /tmp/nemoclaw-validation.XXXXXX) +isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX) isolation_root=$(cd "$isolation_root" && /bin/pwd -P) trap '/bin/rm -R -f -- "$isolation_root"' EXIT /bin/mkdir -p "$isolation_root/home" "$isolation_root/tmp" +git_dir=$(/usr/bin/git -C "$repo_root" rev-parse --absolute-git-dir) +git_common_dir=$(/usr/bin/git -C "$repo_root" rev-parse --path-format=absolute --git-common-dir) +git_dir=$(cd "$git_dir" && /bin/pwd -P) +git_common_dir=$(cd "$git_common_dir" && /bin/pwd -P) +git_worktree_name= +if [ -f "$repo_root/.git" ]; then + git_worktree_name=\${git_dir##*/} + case "$git_worktree_name" in + ''|*[!A-Za-z0-9._-]*) printf '%s\n' 'Unsupported Git worktree metadata path.' >&2; exit 126 ;; + esac + if [ "$git_dir" != "$git_common_dir/worktrees/$git_worktree_name" ]; then + printf '%s\n' 'Git worktree metadata must belong to its common Git directory.' >&2 + exit 126 + fi +fi if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" @@ -112,22 +127,27 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath "/private/var/db") (subpath "/dev") (subpath (param "REPO_ROOT")) - (subpath (param "ISOLATION_ROOT"))) + (subpath (param "ISOLATION_ROOT")) + (subpath (param "GIT_DIR")) + (subpath (param "GIT_COMMON_DIR"))) (allow file-write* (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) (literal "/dev/null")) (deny file-write* (subpath (string-append (param "REPO_ROOT") "/.git"))) +(deny file-write* (subpath (param "GIT_DIR"))) +(deny file-write* (subpath (param "GIT_COMMON_DIR"))) (allow network*) PROFILE set +e /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ + -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ - GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ /bin/sh -c ${quote(command)} validation_status=$? set -e @@ -138,7 +158,14 @@ if command -v bwrap >/dev/null 2>&1; then set -- "$(command -v bwrap)" --die-with-parent --new-session --unshare-all --share-net set -- "$@" --proc /proc --dev /dev --tmpfs /tmp --dir /home set -- "$@" --bind "$isolation_root/home" /home/validator --bind "$repo_root" /workspace - if [ -e "$repo_root/.git" ]; then set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git; fi + if [ -n "$git_worktree_name" ]; then + git_pointer="$isolation_root/git-pointer" + printf 'gitdir: /git/worktrees/%s\n' "$git_worktree_name" >"$git_pointer" + set -- "$@" --dir /git --ro-bind "$git_common_dir" /git + set -- "$@" --ro-bind "$git_pointer" /workspace/.git + else + set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git + fi for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi done @@ -148,7 +175,7 @@ if command -v bwrap >/dev/null 2>&1; then PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ - GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ /bin/sh -c ${quote(command)} validation_status=$? set -e diff --git a/src/lib/onboard/external-component/activation.test.ts b/src/lib/onboard/external-component/activation.test.ts index 0f92c857b47..1e502a2aeee 100644 --- a/src/lib/onboard/external-component/activation.test.ts +++ b/src/lib/onboard/external-component/activation.test.ts @@ -8,6 +8,8 @@ import path from "node:path"; import { describe, expect, it, vi } from "vitest"; +import { boundedTestTempRoot } from "../../../../test/helpers/bounded-temp-root"; + import { EXTERNAL_COMPONENT_ACTIVATION_TIMEOUT_MS, type PreparedExternalComponent } from "./index"; import { activateExternalComponent, @@ -72,7 +74,9 @@ describe("external component activation", () => { }); it("completes a delayed response without half-closing the request (#11340)", async () => { - const root = fs.mkdtempSync(path.join("/tmp", "nc-component-http-")); + const root = fs.mkdtempSync( + path.join(boundedTestTempRoot("nc-XXXXXX/activation.sock", 104), "nc-"), + ); const socketPath = path.join(root, "activation.sock"); let serverSocket: net.Socket | undefined; let resolveRequest!: (request: { @@ -134,7 +138,9 @@ describe("external component activation", () => { { delivery: "one chunk", firstCopies: 2, lastCopies: 0 }, { delivery: "separate chunks", firstCopies: 1, lastCopies: 1 }, ])("rejects extra responses in $delivery (#11340)", async ({ firstCopies, lastCopies }) => { - const root = fs.mkdtempSync("/tmp/nc-extra-response-"); + const root = fs.mkdtempSync( + path.join(boundedTestTempRoot("nc-XXXXXX/activation.sock", 104), "nc-"), + ); const socketPath = `${root}/activation.sock`; const body = JSON.stringify({ schemaVersion: 1, @@ -176,7 +182,9 @@ describe("external component activation", () => { }); it("closes a pending activation socket when the fixed deadline expires (#11340)", async () => { - const root = fs.mkdtempSync(path.join("/tmp", "nc-component-timeout-")); + const root = fs.mkdtempSync( + path.join(boundedTestTempRoot("nc-XXXXXX/activation.sock", 104), "nc-"), + ); const socketPath = path.join(root, "activation.sock"); let resolveAccepted!: () => void; const accepted = new Promise((resolve) => { diff --git a/src/lib/onboard/external-component/onboarding.test.ts b/src/lib/onboard/external-component/onboarding.test.ts index 8b89ccc8e87..74142f36576 100644 --- a/src/lib/onboard/external-component/onboarding.test.ts +++ b/src/lib/onboard/external-component/onboarding.test.ts @@ -7,6 +7,8 @@ import path from "node:path"; import { beforeEach, describe, expect, it, vi } from "vitest"; +import { boundedTestTempRoot } from "../../../../test/helpers/bounded-temp-root"; + const mocks = vi.hoisted(() => ({ inspectPolicyMutationContext: vi.fn(), loadExternalComponentDeclaration: vi.fn(), @@ -95,7 +97,9 @@ describe("external component onboarding lifecycle", () => { }); it("activates with final proof from registry, policy, and OpenShell evidence (#11340)", async () => { - const root = fs.mkdtempSync(path.join("/tmp", "nc-component-final-deps-")); + const root = fs.mkdtempSync( + path.join(boundedTestTempRoot("nc-XXXXXX/activation.sock", 104), "nc-"), + ); const socketPath = path.join(root, "activation.sock"); const sandboxId = "sandbox-123"; const sandboxName = "assistant"; diff --git a/src/lib/onboard/install-ollama-linux.test.ts b/src/lib/onboard/install-ollama-linux.test.ts index 83a80fc04be..52489f86a00 100644 --- a/src/lib/onboard/install-ollama-linux.test.ts +++ b/src/lib/onboard/install-ollama-linux.test.ts @@ -2,6 +2,8 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -56,7 +58,7 @@ describe("resolveOllamaTarballArch", () => { describe("sha256File", () => { it("computes a lowercase SHA-256 identity for downloaded bytes", () => { - const directory = fs.mkdtempSync("/tmp/nemoclaw-ollama-integrity-"); + const directory = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-ollama-integrity-")); const file = `${directory}/install.sh`; try { fs.writeFileSync(file, "#!/bin/sh\nexit 0\n"); diff --git a/test/agents/hermes/hermes-tool-gateway-broker.test.ts b/test/agents/hermes/hermes-tool-gateway-broker.test.ts index 937beeba545..6973635bec6 100644 --- a/test/agents/hermes/hermes-tool-gateway-broker.test.ts +++ b/test/agents/hermes/hermes-tool-gateway-broker.test.ts @@ -25,6 +25,7 @@ import { type OwnedTestResources, test as it, } from "../../helpers/owned-test-resources"; +import { boundedTestTempRoot } from "../../helpers/bounded-temp-root"; import { testTimeout } from "../../helpers/timeouts"; const SCRIPT = path.join( @@ -52,6 +53,17 @@ const CONTROL_CONTRACT = path.join( "tool-gateway-control-contract.ts", ); +function temporaryBrokerHome(resources: OwnedTestResources): string { + return resources.ownDirectory( + fs.mkdtempSync( + path.join( + boundedTestTempRoot("nc-XXXXXX/.cache/nemoclaw/hermes-tool-gateway/control.sock", 104), + "nc-", + ), + ), + ); +} + const BROKER_READINESS_TIMEOUT_MS = 15_000; const BROKER_TEST_TIMEOUT_MS = testTimeout(45_000); @@ -329,7 +341,7 @@ describe("Hermes managed-tool gateway broker", () => { it("refuses a listener whose ownership changes during health verification", async ({ resources, }) => { - const home = resources.ownDirectory(fs.mkdtempSync("/tmp/nc-broker-ownership-race-")); + const home = temporaryBrokerHome(resources); vi.stubEnv("HOME", home); delete require.cache[require.resolve(BROKER_WRAPPER)]; const broker = require(BROKER_WRAPPER); @@ -402,7 +414,7 @@ describe("Hermes managed-tool gateway broker", () => { it( "reuses its listener and rechecks ownership after the process exits", async ({ resources, skip }) => { - const home = resources.ownDirectory(fs.mkdtempSync("/tmp/nc-broker-ownership-")); + const home = temporaryBrokerHome(resources); vi.stubEnv("HOME", home); delete require.cache[require.resolve(BROKER_WRAPPER)]; const broker = require(BROKER_WRAPPER); @@ -460,7 +472,7 @@ describe("Hermes managed-tool gateway broker", () => { it( "refuses a live recorded process that does not own the managed-tool port", async ({ resources, skip }) => { - const home = resources.ownDirectory(fs.mkdtempSync("/tmp/nc-broker-port-owner-")); + const home = temporaryBrokerHome(resources); vi.stubEnv("HOME", home); delete require.cache[require.resolve(BROKER_WRAPPER)]; const broker = require(BROKER_WRAPPER); @@ -547,7 +559,7 @@ describe("Hermes managed-tool gateway broker", () => { it( "keeps a stale broker-like non-listener alive while replacement startup clears its records", async ({ resources, skip }) => { - const home = resources.ownDirectory(fs.mkdtempSync("/tmp/nc-broker-stale-non-listener-")); + const home = temporaryBrokerHome(resources); vi.stubEnv("HOME", home); delete require.cache[require.resolve(BROKER_WRAPPER)]; const broker = require(BROKER_WRAPPER); @@ -684,7 +696,7 @@ describe("Hermes managed-tool gateway broker", () => { async ({ resources }) => { const previousHome = process.env.HOME; const previousPath = process.env.PATH; - const home = resources.ownDirectory(fs.mkdtempSync("/tmp/nc-hermes-node-control-")); + const home = temporaryBrokerHome(resources); try { process.env.HOME = home; delete require.cache[require.resolve(BROKER_WRAPPER)]; @@ -1181,7 +1193,9 @@ describe("Hermes managed-tool gateway broker", () => { const binDir = path.join(tmp, "bin"); // AF_UNIX paths are short on macOS; the Vitest-owned TMPDIR itself can // exceed that limit before the socket name is appended. - const socketDir = resources.ownDirectory(fs.mkdtempSync("/tmp/nc-hermes-broker-")); + const socketDir = resources.ownDirectory( + fs.mkdtempSync(path.join(boundedTestTempRoot("nc-XXXXXX/control.sock", 104), "nc-")), + ); const controlSocket = path.join(socketDir, "control.sock"); // The broad starting mode proves that broker startup narrows the directory to 0o700. fs.chmodSync(socketDir, 0o777); diff --git a/test/e2e/support/dgx-station-express.test.ts b/test/e2e/support/dgx-station-express.test.ts index 39e25d5bb12..1233b17ccb0 100644 --- a/test/e2e/support/dgx-station-express.test.ts +++ b/test/e2e/support/dgx-station-express.test.ts @@ -18,6 +18,7 @@ import { CleanupRegistry } from "../fixtures/cleanup.ts"; import { ShellProbe, trustedShellCommand } from "../fixtures/shell-probe.ts"; import type { HostCliClient } from "../fixtures/clients/host.ts"; import type { SandboxClient } from "../fixtures/clients/sandbox.ts"; +import { boundedTestTempRoot } from "../../helpers/bounded-temp-root"; import { stationVllmCommands, assertStationWorkload, @@ -663,7 +664,9 @@ it("allows consecutive tsx IPC servers within the generated temporary path lengt const env = stationSmokeEnvironment(base, "/candidate"); const worstCaseSocket = `${env.TMPDIR}/tsx-4294967295/4294967295.pipe`; expect(Buffer.byteLength(worstCaseSocket)).toBeLessThan(108); - const root = fs.mkdtempSync("/tmp/ncs-ipc-"); + const root = fs.mkdtempSync( + path.join(boundedTestTempRoot("nc-XXXXXX", Buffer.byteLength(env.TMPDIR!)), "nc-"), + ); directories.push(root); const tmp = path.join(root, "x".repeat(env.TMPDIR!.length - root.length - 1)); fs.mkdirSync(tmp); diff --git a/test/e2e/support/native-runtime-qualification-account-lifecycle.test.ts b/test/e2e/support/native-runtime-qualification-account-lifecycle.test.ts index 70d84f0014f..0501feb01a2 100644 --- a/test/e2e/support/native-runtime-qualification-account-lifecycle.test.ts +++ b/test/e2e/support/native-runtime-qualification-account-lifecycle.test.ts @@ -8,6 +8,7 @@ import * as os from "node:os"; import * as path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { boundedTestTempRoot } from "../../helpers/bounded-temp-root"; import { readYaml, type Workflow } from "../../helpers/e2e-workflow-contract"; const roots: string[] = []; @@ -363,7 +364,9 @@ describe("native runtime qualification account lifecycle", () => { it("rejects a symlinked or wrong-owner user bus while accepting the exact account socket", async () => { const fixture = createFixture(); - const socketRoot = fs.mkdtempSync("/tmp/nrq-bus-"); + const socketRoot = fs.mkdtempSync( + path.join(boundedTestTempRoot("nc-XXXXXX/bus-link", 104), "nc-"), + ); roots.push(socketRoot); const socket = path.join(socketRoot, "bus"); const socketLink = path.join(socketRoot, "bus-link"); diff --git a/test/e2e/support/portable-profile-cgroup-cleanup-workflow.test.ts b/test/e2e/support/portable-profile-cgroup-cleanup-workflow.test.ts index f912412880f..8d1e0fc42c7 100644 --- a/test/e2e/support/portable-profile-cgroup-cleanup-workflow.test.ts +++ b/test/e2e/support/portable-profile-cgroup-cleanup-workflow.test.ts @@ -3,6 +3,7 @@ import { spawnSync } from "node:child_process"; import fs from "node:fs"; +import os from "node:os"; import path from "node:path"; import { expect, it } from "vitest"; @@ -23,7 +24,7 @@ function portableCleanupRun(): string { } it("restores the portable user manager and linger state after refusing a changed drop-in", () => { - const root = fs.mkdtempSync("/tmp/portable-cpu-delegation-restoration-"); + const root = fs.mkdtempSync(path.join(os.tmpdir(), "portable-cpu-delegation-restoration-")); const bin = path.join(root, "bin"); const changed = path.join(root, "changed.conf"); const podmanConfig = path.join(root, "portable-containers.conf"); diff --git a/test/e2e/support/portable-profile-systemctl-shim.test.ts b/test/e2e/support/portable-profile-systemctl-shim.test.ts index 0cf691ed19e..6b1e5c39ec5 100644 --- a/test/e2e/support/portable-profile-systemctl-shim.test.ts +++ b/test/e2e/support/portable-profile-systemctl-shim.test.ts @@ -7,7 +7,7 @@ import net from "node:net"; import path from "node:path"; import { describe, expect, it, vi } from "vitest"; - +import { boundedTestTempRoot } from "../../helpers/bounded-temp-root"; import { cleanupPortableProfileRootlessFixture, cleanupPortableProfileSystemctlFixture, @@ -30,7 +30,6 @@ interface FixtureScope { readonly shim: string; readonly socketPath: string; } - interface FixtureProcessRecord { readonly identity: string; readonly pid: number; @@ -54,7 +53,8 @@ ExecStart=${gatewayBin} } function createFixture(): FixtureScope { - const directory = fs.mkdtempSync("/tmp/portable-systemctl-shim-"); + const tempRoot = boundedTestTempRoot("nc-XXXXXX/runtime/podman/podman.sock", 104); + const directory = fs.mkdtempSync(path.join(tempRoot, "nc-")); const binDir = path.join(directory, "bin"); const homeDir = path.join(directory, "home"); const binHome = path.join(homeDir, ".local", "bin"); @@ -834,7 +834,7 @@ describe("portable profile systemctl fixture", () => { "isolates the managed gateway user service from ambient XDG homes (#9208)", { timeout: 30_000 }, async () => { - const ambientRoot = fs.mkdtempSync("/tmp/portable-systemctl-ambient-"); + const ambientRoot = fs.mkdtempSync(path.join(process.env.TMPDIR!, "nc-")); vi.stubEnv("XDG_BIN_HOME", path.join(ambientRoot, "bin")); vi.stubEnv("XDG_CONFIG_HOME", path.join(ambientRoot, "config")); vi.stubEnv("XDG_RUNTIME_DIR", path.join(ambientRoot, "runtime")); diff --git a/test/e2e/support/windows-mxc-openclaw-process-container.test.ts b/test/e2e/support/windows-mxc-openclaw-process-container.test.ts index 57d75c576e3..ec413728edf 100644 --- a/test/e2e/support/windows-mxc-openclaw-process-container.test.ts +++ b/test/e2e/support/windows-mxc-openclaw-process-container.test.ts @@ -8,6 +8,7 @@ import os from "node:os"; import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; +import { boundedTestTempRoot } from "../../helpers/bounded-temp-root"; import { sha256WindowsOpenClawArtifactTree } from "../../../tools/e2e/windows-mxc-openclaw-artifact-tree.mts"; import { allowlistedWindowsProcessEnvironment, @@ -1112,7 +1113,9 @@ describe("inactive Windows MXC OpenClaw process_container qualification", () => it.runIf(process.platform !== "win32")( "rejects unsupported entries in the OpenClaw artifact tree (#8178)", async () => { - const artifact = fs.mkdtempSync(path.join("/tmp", "nemoclaw-mxc-socket-")); + const artifact = fs.mkdtempSync( + path.join(boundedTestTempRoot("nc-XXXXXX/runtime.sock", 104), "nc-"), + ); roots.push(artifact); const socketPath = path.join(artifact, "runtime.sock"); const server = net.createServer(); diff --git a/test/helpers/bounded-temp-root.ts b/test/helpers/bounded-temp-root.ts new file mode 100644 index 00000000000..96755bca1ec --- /dev/null +++ b/test/helpers/bounded-temp-root.ts @@ -0,0 +1,19 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import os from "node:os"; +import path from "node:path"; + +export function boundedTestTempRoot(relativePath: string, maxPathBytes: number): string { + const privateTempRoot = os.tmpdir(); + if (Buffer.byteLength(path.join(privateTempRoot, relativePath)) < maxPathBytes) { + return privateTempRoot; + } + + const shortSystemTempRoot = path.join(path.parse(privateTempRoot).root, "tmp"); + if (Buffer.byteLength(path.join(shortSystemTempRoot, relativePath)) < maxPathBytes) { + return shortSystemTempRoot; + } + + throw new Error(`Temporary path cannot fit within ${maxPathBytes} bytes`); +} diff --git a/test/helpers/onboard-child-runtime.test.ts b/test/helpers/onboard-child-runtime.test.ts index 8aa08e32759..6e191e62c0d 100644 --- a/test/helpers/onboard-child-runtime.test.ts +++ b/test/helpers/onboard-child-runtime.test.ts @@ -39,9 +39,9 @@ type ExecutionProofRuntime = { }; function loadPromptQueueRuntime(): PromptQueueRuntime { - return new Function( - `${onboardChildRuntimeSource}\nreturn { installPromptQueue };`, - )() as PromptQueueRuntime; + return new Function("require", `${onboardChildRuntimeSource}\nreturn { installPromptQueue };`)( + createRequire(import.meta.url), + ) as PromptQueueRuntime; } function loadExecutionProofRuntime(): ExecutionProofRuntime { From 7565f463853492192b220808dd7e6e7aca961592 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 22:53:04 -0700 Subject: [PATCH 07/12] fix(tools): preserve isolated validation runtime --- .../index.ts | 24 +- .dsh/tools/run_targeted_vitest/index.ts | 22 +- test/helpers/onboard-child-runtime.test.ts | 34 ++- .../validation-wrapper-isolation.test.ts | 210 ++++++++++++++++++ 4 files changed, 276 insertions(+), 14 deletions(-) create mode 100644 test/tools/validation-wrapper-isolation.test.ts diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index 912d79468d1..c0c1dc3944d 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -1,3 +1,6 @@ +import { realpathSync } from "node:fs"; +import path from "node:path"; + /** * Run guarded focused validation for a NemoClaw repair. */ @@ -89,11 +92,18 @@ export default async function run_nemoclaw_focused_repair_validation(input: { "e2e-support", ]); if (!projects.every((x) => allowed.has(x))) throw new Error("Unsupported Vitest project"); - const q = (v) => "'" + String(v).replaceAll("'", "'\"'\"'") + "'", + const nodeExecutable = realpathSync(process.execPath), + nodeBinDir = path.dirname(nodeExecutable), + nodePrefix = path.dirname(nodeBinDir), + nodePrefixParent = path.dirname(nodePrefix), + q = (v) => "'" + String(v).replaceAll("'", "'\"'\"'") + "'", isolate = (command) => `set -eu umask 077 repo_root=$(/bin/pwd -P) +node_bin_dir=${q(nodeBinDir)} +node_prefix=${q(nodePrefix)} +node_prefix_parent=${q(nodePrefixParent)} isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX) isolation_root=$(cd "$isolation_root" && /bin/pwd -P) trap '/bin/rm -R -f -- "$isolation_root"' EXIT @@ -141,7 +151,8 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) (subpath (param "GIT_DIR")) - (subpath (param "GIT_COMMON_DIR"))) + (subpath (param "GIT_COMMON_DIR")) + (subpath (param "NODE_PREFIX"))) (allow file-write* (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) @@ -154,9 +165,10 @@ PROFILE set +e /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ + -D NODE_PREFIX="$node_prefix" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ - PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + PATH="$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ @@ -181,10 +193,14 @@ if command -v bwrap >/dev/null 2>&1; then for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi done + case "$node_prefix" in + /usr|/usr/*|/bin|/bin/*|/sbin|/sbin/*|/lib|/lib/*|/lib64|/lib64/*|/opt|/opt/*|/etc|/etc/*) ;; + *) set -- "$@" --dir "$node_prefix_parent" --ro-bind "$node_prefix" "$node_prefix" ;; + esac set +e "$@" --chdir /workspace /usr/bin/env -i \ HOME=/home/validator XDG_CONFIG_HOME=/home/validator TMPDIR=/tmp \ - PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + PATH="$node_bin_dir:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ diff --git a/.dsh/tools/run_targeted_vitest/index.ts b/.dsh/tools/run_targeted_vitest/index.ts index 5158be77590..c5636c7de16 100644 --- a/.dsh/tools/run_targeted_vitest/index.ts +++ b/.dsh/tools/run_targeted_vitest/index.ts @@ -1,3 +1,6 @@ +import { realpathSync } from "node:fs"; +import path from "node:path"; + /** * Run focused Vitest files with selected projects, bounded head/tail output, and explicit truncation metadata. */ @@ -78,10 +81,17 @@ export default async function run_targeted_vitest(input: { const maxLines = Math.max(1, Math.min(500, input.maxLines ?? 120)); const clipMode = input.clipMode ?? "tail"; if (!new Set(["head", "tail"]).has(clipMode)) throw new Error("clipMode must be head or tail"); + const nodeExecutable = realpathSync(process.execPath); + const nodeBinDir = path.dirname(nodeExecutable); + const nodePrefix = path.dirname(nodeBinDir); + const nodePrefixParent = path.dirname(nodePrefix); const command = "npx " + args.map(quote).join(" "); const isolatedCommand = `set -eu umask 077 repo_root=$(/bin/pwd -P) +node_bin_dir=${quote(nodeBinDir)} +node_prefix=${quote(nodePrefix)} +node_prefix_parent=${quote(nodePrefixParent)} isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX) isolation_root=$(cd "$isolation_root" && /bin/pwd -P) trap '/bin/rm -R -f -- "$isolation_root"' EXIT @@ -129,7 +139,8 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) (subpath (param "GIT_DIR")) - (subpath (param "GIT_COMMON_DIR"))) + (subpath (param "GIT_COMMON_DIR")) + (subpath (param "NODE_PREFIX"))) (allow file-write* (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) @@ -142,9 +153,10 @@ PROFILE set +e /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ + -D NODE_PREFIX="$node_prefix" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ - PATH=/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + PATH="$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ @@ -169,10 +181,14 @@ if command -v bwrap >/dev/null 2>&1; then for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi done + case "$node_prefix" in + /usr|/usr/*|/bin|/bin/*|/sbin|/sbin/*|/lib|/lib/*|/lib64|/lib64/*|/opt|/opt/*|/etc|/etc/*) ;; + *) set -- "$@" --dir "$node_prefix_parent" --ro-bind "$node_prefix" "$node_prefix" ;; + esac set +e "$@" --chdir /workspace /usr/bin/env -i \ HOME=/home/validator XDG_CONFIG_HOME=/home/validator TMPDIR=/tmp \ - PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin \ + PATH="$node_bin_dir:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ diff --git a/test/helpers/onboard-child-runtime.test.ts b/test/helpers/onboard-child-runtime.test.ts index 6e191e62c0d..5cb41e0c8c1 100644 --- a/test/helpers/onboard-child-runtime.test.ts +++ b/test/helpers/onboard-child-runtime.test.ts @@ -39,19 +39,39 @@ type ExecutionProofRuntime = { }; function loadPromptQueueRuntime(): PromptQueueRuntime { - return new Function("require", `${onboardChildRuntimeSource}\nreturn { installPromptQueue };`)( - createRequire(import.meta.url), - ) as PromptQueueRuntime; + return loadChildRuntime("installPromptQueue"); } function loadExecutionProofRuntime(): ExecutionProofRuntime { - return new Function( - "require", - `${onboardChildRuntimeSource}\nreturn { createSuccessfulOllamaServiceExecutionProofRunner };`, - )(createRequire(import.meta.url)) as ExecutionProofRuntime; + return loadChildRuntime( + "createSuccessfulOllamaServiceExecutionProofRunner", + ); +} + +function loadChildRuntime(exportName: string): T { + const childRequire = createRequire(import.meta.url); + const childCrypto = childRequire("node:crypto") as typeof import("node:crypto"); + const originalCreateHash = childCrypto.createHash; + try { + return new Function("require", `${onboardChildRuntimeSource}\nreturn { ${exportName} };`)( + childRequire, + ) as T; + } finally { + childCrypto.createHash = originalCreateHash; + } } describe("onboard child prompt queue", () => { + it("restores the parent crypto implementation after loading the child fixture", () => { + const childRequire = createRequire(import.meta.url); + const childCrypto = childRequire("node:crypto") as typeof import("node:crypto"); + const originalCreateHash = childCrypto.createHash; + + loadPromptQueueRuntime(); + + assert.equal(childCrypto.createHash, originalCreateHash); + }); + it("fails when a child scenario asks an unscripted question", async () => { const target: PromptTarget = {}; const { messages, prompts } = loadPromptQueueRuntime().installPromptQueue(target, ["answer"]); diff --git a/test/tools/validation-wrapper-isolation.test.ts b/test/tools/validation-wrapper-isolation.test.ts new file mode 100644 index 00000000000..8e90e841081 --- /dev/null +++ b/test/tools/validation-wrapper-isolation.test.ts @@ -0,0 +1,210 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it, vi } from "vitest"; + +type BashInput = { + command: string; + workdir: string; + timeoutMs: number; +}; + +type BashResult = { + kind: "foreground"; + exitCode: number | null; + stdout: { text: string; truncated: boolean }; + stderr: { text: string; truncated: boolean }; +}; + +type FocusedValidationRunner = (input: Record) => Promise<{ ok: boolean }>; +type TargetedVitestRunner = (input: Record) => Promise<{ code: number }>; + +const nativeSandboxAvailable = + (process.platform === "darwin" && fs.existsSync("/usr/bin/sandbox-exec")) || + (process.platform === "linux" && + spawnSync("/bin/sh", ["-c", "command -v bwrap"], { encoding: "utf8" }).status === 0); + +function foreground(exitCode: number | null = 0, stdout = "", stderr = ""): BashResult { + return { + kind: "foreground", + exitCode, + stdout: { text: stdout, truncated: false }, + stderr: { text: stderr, truncated: false }, + }; +} + +function installTools(runBash: (input: BashInput) => BashResult): void { + vi.stubGlobal("tools", { + bash: async (input: BashInput) => runBash(input), + infer_validation_for_changed_files: async () => ({ + baseRef: "HEAD", + files: [], + branchFiles: [], + workingTreeFiles: [], + untrackedFiles: [], + projects: ["integration"], + targetedFiles: ["probe.test.ts"], + commands: [], + notes: [], + }), + project_diagnostic_text: async (input: { lines: string[]; sourceTruncated: boolean }) => ({ + text: input.lines.join("\n"), + sourceTruncated: input.sourceTruncated, + lineClipped: false, + truncated: input.sourceTruncated, + selectedLines: input.lines.length, + returnedLines: input.lines.length, + }), + }); +} + +async function runBothWrappers( + workdir: string, +): Promise<{ focusedOk: boolean; targetedCode: number }> { + const [{ default: runFocusedValidation }, { default: runTargetedVitest }] = await Promise.all([ + vi.importActual<{ default: FocusedValidationRunner }>( + "../../.dsh/tools/run_nemoclaw_focused_repair_validation/index", + ), + vi.importActual<{ default: TargetedVitestRunner }>( + "../../.dsh/tools/run_targeted_vitest/index", + ), + ]); + const focused = await runFocusedValidation({ + workdir, + files: [], + testFiles: ["probe.test.ts"], + projects: ["integration"], + baseRef: "HEAD", + formatWrite: false, + typecheckCli: false, + typecheckPlugin: false, + repoChecks: false, + diffCheck: false, + nulCheck: false, + docs: false, + dryRun: false, + }); + const targeted = await runTargetedVitest({ + workdir, + files: ["probe.test.ts"], + projects: ["integration"], + }); + return { focusedOk: focused.ok, targetedCode: targeted.code }; +} + +function shellQuote(value: string): string { + return `'${value.replaceAll("'", `'"'"'`)}'`; +} + +function expectNodeToolchainBoundary(command: string): void { + expect(command).toContain('(subpath (param "NODE_PREFIX"))'); + expect(command).toContain('-D NODE_PREFIX="$node_prefix"'); + expect(command).toContain('--ro-bind "$node_prefix" "$node_prefix"'); + expect(command).toContain('PATH="$node_bin_dir:'); +} + +function createWorktreeFixture(): { root: string; sentinel: string; worktree: string } { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wrapper-isolation-")); + const repository = path.join(root, "repository"); + const worktree = path.join(root, "worktree"); + const sentinel = path.join(root, "outside-checkout-sentinel"); + fs.mkdirSync(repository); + fs.writeFileSync(sentinel, "must remain unreadable\n", { mode: 0o600 }); + const git = (...args: string[]) => { + const result = spawnSync("/usr/bin/git", args, { + cwd: repository, + encoding: "utf8", + }); + expect(result.status, result.stderr).toBe(0); + }; + git("init", "--initial-branch=main"); + git("config", "user.name", "NemoClaw Validation Test"); + git("config", "user.email", "validation-test@example.invalid"); + fs.writeFileSync(path.join(repository, "tracked.txt"), "fixture\n"); + git("add", "tracked.txt"); + git("commit", "-m", "fixture"); + git("worktree", "add", "-b", "fixture-worktree", worktree); + + const bin = path.join(worktree, "node_modules", ".bin"); + fs.mkdirSync(bin, { recursive: true }); + const probe = `#!/bin/sh +set -eu +/usr/bin/git status --short >/dev/null +git_common=$(/usr/bin/git rev-parse --path-format=absolute --git-common-dir) +if /bin/cat ${shellQuote(sentinel)} >/dev/null 2>&1; then + printf '%s\n' 'outside-checkout sentinel was readable' >&2 + exit 41 +fi +if /usr/bin/touch "$git_common/nemoclaw-validation-write-probe" >/dev/null 2>&1; then + printf '%s\n' 'Git metadata was writable' >&2 + exit 42 +fi +command -v node >/dev/null +command -v npx >/dev/null +printf '%s\n' "$HOME" >>"$PWD/wrapper-probe.log" +`; + const vitest = path.join(bin, "vitest"); + fs.writeFileSync(vitest, probe, { mode: 0o755 }); + return { root, sentinel, worktree }; +} + +afterEach(() => { + vi.unstubAllGlobals(); +}); + +describe("credential-isolated validation wrappers", () => { + it("exposes the active host Node toolchain read-only in both sandbox implementations", async () => { + const commands: string[] = []; + installTools((input) => { + commands.push(input.command); + return foreground(); + }); + + const result = await runBothWrappers(process.cwd()); + + expect(result).toEqual({ focusedOk: true, targetedCode: 0 }); + expect(commands).toHaveLength(2); + expectNodeToolchainBoundary(commands[0]); + expectNodeToolchainBoundary(commands[1]); + }); + + it.runIf(nativeSandboxAvailable)( + "runs both actual wrappers from a worktree without exposing host files or writable Git metadata", + async () => { + const fixture = createWorktreeFixture(); + installTools((input) => { + const result = spawnSync("/bin/sh", ["-c", input.command], { + cwd: input.workdir, + encoding: "utf8", + env: process.env, + timeout: input.timeoutMs, + }); + return foreground( + result.status, + result.stdout, + result.stderr || result.error?.message || "", + ); + }); + + try { + const result = await runBothWrappers(fixture.worktree); + + expect(result).toEqual({ focusedOk: true, targetedCode: 0 }); + const privateHomes = fs + .readFileSync(path.join(fixture.worktree, "wrapper-probe.log"), "utf8") + .trim() + .split("\n"); + expect(privateHomes).toHaveLength(2); + expect(privateHomes.every((home) => home !== os.homedir())).toBe(true); + expect(fs.readFileSync(fixture.sentinel, "utf8")).toBe("must remain unreadable\n"); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }, + ); +}); From 3866cfc390cdd94d5b9d08b990fe981811a2dc7f Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 23:11:56 -0700 Subject: [PATCH 08/12] fix(tools): mask validation host credentials --- .../index.ts | 48 +++++++- .dsh/tools/run_targeted_vitest/index.ts | 48 +++++++- .../validation-wrapper-isolation.test.ts | 114 ++++++++++++++++-- 3 files changed, 185 insertions(+), 25 deletions(-) diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index c0c1dc3944d..69c5dc45b25 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -124,6 +124,29 @@ if [ -f "$repo_root/.git" ]; then fi fi +git_shadow="$isolation_root/git" +/bin/mkdir -p "$git_shadow/objects/info" "$git_shadow/refs" +cat >"$git_shadow/config" <<'GIT_CONFIG' +[core] + repositoryformatversion = 0 + bare = false + logallrefupdates = false +GIT_CONFIG +printf '%s\n' "$git_common_dir/objects" >"$git_shadow/objects/info/alternates" +if [ -f "$git_dir/index" ]; then /bin/cp "$git_dir/index" "$git_shadow/index"; fi +if [ -f "$git_common_dir/shallow" ]; then /bin/cp "$git_common_dir/shallow" "$git_shadow/shallow"; fi +git_head_ref=$(/usr/bin/git -C "$repo_root" symbolic-ref -q HEAD || :) +if [ -n "$git_head_ref" ]; then + printf 'ref: %s\n' "$git_head_ref" >"$git_shadow/HEAD" +else + /usr/bin/git -C "$repo_root" rev-parse --verify HEAD >"$git_shadow/HEAD" +fi +/usr/bin/git -C "$repo_root" for-each-ref --format='%(objectname) %(refname)' | +while IFS=' ' read -r git_ref_oid git_ref_name; do + /usr/bin/env -i PATH=/usr/bin:/bin GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + /usr/bin/git --git-dir="$git_shadow" update-ref "$git_ref_name" "$git_ref_oid" +done + if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" cat >"$sandbox_profile" <<'PROFILE' @@ -150,8 +173,7 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath "/dev") (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) - (subpath (param "GIT_DIR")) - (subpath (param "GIT_COMMON_DIR")) + (subpath (param "GIT_OBJECTS")) (subpath (param "NODE_PREFIX"))) (allow file-write* (subpath (param "REPO_ROOT")) @@ -160,11 +182,20 @@ if [ -x /usr/bin/sandbox-exec ]; then (deny file-write* (subpath (string-append (param "REPO_ROOT") "/.git"))) (deny file-write* (subpath (param "GIT_DIR"))) (deny file-write* (subpath (param "GIT_COMMON_DIR"))) -(allow network*) +(deny file-read* + (literal (param "GIT_CONFIG_PATH")) + (literal (param "GIT_WORKTREE_CONFIG_PATH"))) +(allow network-outbound (remote ip)) +(allow network-inbound (local ip)) +(allow network-bind (local ip)) +(allow network* (subpath (param "ISOLATION_ROOT"))) PROFILE set +e /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ + -D GIT_OBJECTS="$git_common_dir/objects" \ + -D GIT_CONFIG_PATH="$git_common_dir/config" \ + -D GIT_WORKTREE_CONFIG_PATH="$git_dir/config.worktree" \ -D NODE_PREFIX="$node_prefix" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ @@ -172,6 +203,7 @@ PROFILE CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ + GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root" \ /bin/sh -c ${q(command)} validation_status=$? set -e @@ -182,13 +214,16 @@ if command -v bwrap >/dev/null 2>&1; then set -- "$(command -v bwrap)" --die-with-parent --new-session --unshare-all --share-net set -- "$@" --proc /proc --dev /dev --tmpfs /tmp --dir /home set -- "$@" --bind "$isolation_root/home" /home/validator --bind "$repo_root" /workspace + set -- "$@" --dir /git --ro-bind "$git_shadow" /git + set -- "$@" --ro-bind "$git_common_dir/objects" /git/objects if [ -n "$git_worktree_name" ]; then git_pointer="$isolation_root/git-pointer" - printf 'gitdir: /git/worktrees/%s\n' "$git_worktree_name" >"$git_pointer" - set -- "$@" --dir /git --ro-bind "$git_common_dir" /git + printf 'gitdir: /git\n' >"$git_pointer" set -- "$@" --ro-bind "$git_pointer" /workspace/.git else - set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git + empty_git="$isolation_root/empty-git" + /bin/mkdir "$empty_git" + set -- "$@" --ro-bind "$empty_git" /workspace/.git fi for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi @@ -204,6 +239,7 @@ if command -v bwrap >/dev/null 2>&1; then CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ + GIT_DIR=/git GIT_WORK_TREE=/workspace \ /bin/sh -c ${q(command)} validation_status=$? set -e diff --git a/.dsh/tools/run_targeted_vitest/index.ts b/.dsh/tools/run_targeted_vitest/index.ts index c5636c7de16..3405377301f 100644 --- a/.dsh/tools/run_targeted_vitest/index.ts +++ b/.dsh/tools/run_targeted_vitest/index.ts @@ -112,6 +112,29 @@ if [ -f "$repo_root/.git" ]; then fi fi +git_shadow="$isolation_root/git" +/bin/mkdir -p "$git_shadow/objects/info" "$git_shadow/refs" +cat >"$git_shadow/config" <<'GIT_CONFIG' +[core] + repositoryformatversion = 0 + bare = false + logallrefupdates = false +GIT_CONFIG +printf '%s\n' "$git_common_dir/objects" >"$git_shadow/objects/info/alternates" +if [ -f "$git_dir/index" ]; then /bin/cp "$git_dir/index" "$git_shadow/index"; fi +if [ -f "$git_common_dir/shallow" ]; then /bin/cp "$git_common_dir/shallow" "$git_shadow/shallow"; fi +git_head_ref=$(/usr/bin/git -C "$repo_root" symbolic-ref -q HEAD || :) +if [ -n "$git_head_ref" ]; then + printf 'ref: %s\n' "$git_head_ref" >"$git_shadow/HEAD" +else + /usr/bin/git -C "$repo_root" rev-parse --verify HEAD >"$git_shadow/HEAD" +fi +/usr/bin/git -C "$repo_root" for-each-ref --format='%(objectname) %(refname)' | +while IFS=' ' read -r git_ref_oid git_ref_name; do + /usr/bin/env -i PATH=/usr/bin:/bin GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ + /usr/bin/git --git-dir="$git_shadow" update-ref "$git_ref_name" "$git_ref_oid" +done + if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" cat >"$sandbox_profile" <<'PROFILE' @@ -138,8 +161,7 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath "/dev") (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) - (subpath (param "GIT_DIR")) - (subpath (param "GIT_COMMON_DIR")) + (subpath (param "GIT_OBJECTS")) (subpath (param "NODE_PREFIX"))) (allow file-write* (subpath (param "REPO_ROOT")) @@ -148,11 +170,20 @@ if [ -x /usr/bin/sandbox-exec ]; then (deny file-write* (subpath (string-append (param "REPO_ROOT") "/.git"))) (deny file-write* (subpath (param "GIT_DIR"))) (deny file-write* (subpath (param "GIT_COMMON_DIR"))) -(allow network*) +(deny file-read* + (literal (param "GIT_CONFIG_PATH")) + (literal (param "GIT_WORKTREE_CONFIG_PATH"))) +(allow network-outbound (remote ip)) +(allow network-inbound (local ip)) +(allow network-bind (local ip)) +(allow network* (subpath (param "ISOLATION_ROOT"))) PROFILE set +e /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ + -D GIT_OBJECTS="$git_common_dir/objects" \ + -D GIT_CONFIG_PATH="$git_common_dir/config" \ + -D GIT_WORKTREE_CONFIG_PATH="$git_dir/config.worktree" \ -D NODE_PREFIX="$node_prefix" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ @@ -160,6 +191,7 @@ PROFILE CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ + GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root" \ /bin/sh -c ${quote(command)} validation_status=$? set -e @@ -170,13 +202,16 @@ if command -v bwrap >/dev/null 2>&1; then set -- "$(command -v bwrap)" --die-with-parent --new-session --unshare-all --share-net set -- "$@" --proc /proc --dev /dev --tmpfs /tmp --dir /home set -- "$@" --bind "$isolation_root/home" /home/validator --bind "$repo_root" /workspace + set -- "$@" --dir /git --ro-bind "$git_shadow" /git + set -- "$@" --ro-bind "$git_common_dir/objects" /git/objects if [ -n "$git_worktree_name" ]; then git_pointer="$isolation_root/git-pointer" - printf 'gitdir: /git/worktrees/%s\n' "$git_worktree_name" >"$git_pointer" - set -- "$@" --dir /git --ro-bind "$git_common_dir" /git + printf 'gitdir: /git\n' >"$git_pointer" set -- "$@" --ro-bind "$git_pointer" /workspace/.git else - set -- "$@" --ro-bind "$repo_root/.git" /workspace/.git + empty_git="$isolation_root/empty-git" + /bin/mkdir "$empty_git" + set -- "$@" --ro-bind "$empty_git" /workspace/.git fi for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi @@ -192,6 +227,7 @@ if command -v bwrap >/dev/null 2>&1; then CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ + GIT_DIR=/git GIT_WORK_TREE=/workspace \ /bin/sh -c ${quote(command)} validation_status=$? set -e diff --git a/test/tools/validation-wrapper-isolation.test.ts b/test/tools/validation-wrapper-isolation.test.ts index 8e90e841081..daf170e3bc6 100644 --- a/test/tools/validation-wrapper-isolation.test.ts +++ b/test/tools/validation-wrapper-isolation.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; +import { spawn, spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; @@ -106,9 +106,19 @@ function expectNodeToolchainBoundary(command: string): void { expect(command).toContain('-D NODE_PREFIX="$node_prefix"'); expect(command).toContain('--ro-bind "$node_prefix" "$node_prefix"'); expect(command).toContain('PATH="$node_bin_dir:'); + expect(command).toContain('GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root"'); + expect(command).toContain("GIT_DIR=/git GIT_WORK_TREE=/workspace"); + expect(command).toContain('(literal (param "GIT_CONFIG_PATH"))'); + expect(command).toContain('--ro-bind "$git_shadow" /git'); + expect(command).toContain("(allow network-outbound (remote ip))"); + expect(command).toContain('(allow network* (subpath (param "ISOLATION_ROOT")))'); + expect(command).not.toContain("(allow network*)"); } -function createWorktreeFixture(): { root: string; sentinel: string; worktree: string } { +function createCheckoutFixture( + linked: boolean, + outsideSocket?: string, +): { config: string; root: string; sentinel: string; workdir: string } { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wrapper-isolation-")); const repository = path.join(root, "repository"); const worktree = path.join(root, "worktree"); @@ -125,32 +135,61 @@ function createWorktreeFixture(): { root: string; sentinel: string; worktree: st git("init", "--initial-branch=main"); git("config", "user.name", "NemoClaw Validation Test"); git("config", "user.email", "validation-test@example.invalid"); + git( + "config", + "http.https://example.invalid/.extraHeader", + "Authorization: Bearer benign-git-config-canary", + ); fs.writeFileSync(path.join(repository, "tracked.txt"), "fixture\n"); git("add", "tracked.txt"); git("commit", "-m", "fixture"); - git("worktree", "add", "-b", "fixture-worktree", worktree); + linked ? git("worktree", "add", "-b", "fixture-worktree", worktree) : undefined; + const workdir = linked ? worktree : repository; + const config = path.join(repository, ".git", "config"); + const sandboxConfig = + process.platform === "linux" ? (linked ? "/git/config" : "/workspace/.git/config") : config; + const sandboxGitMetadata = + process.platform === "linux" + ? linked + ? "/git" + : "/workspace/.git" + : path.join(repository, ".git"); + const socketProbe = outsideSocket + ? `if /usr/bin/nc -w 1 -U ${shellQuote(outsideSocket)} 2>/dev/null | /usr/bin/grep -F 'outside-unix-socket-canary' >/dev/null; then + printf '%s\\n' 'outside Unix socket was reachable' >&2 + exit 45 +fi` + : ""; - const bin = path.join(worktree, "node_modules", ".bin"); + const bin = path.join(workdir, "node_modules", ".bin"); fs.mkdirSync(bin, { recursive: true }); const probe = `#!/bin/sh set -eu /usr/bin/git status --short >/dev/null -git_common=$(/usr/bin/git rev-parse --path-format=absolute --git-common-dir) if /bin/cat ${shellQuote(sentinel)} >/dev/null 2>&1; then printf '%s\n' 'outside-checkout sentinel was readable' >&2 exit 41 fi -if /usr/bin/touch "$git_common/nemoclaw-validation-write-probe" >/dev/null 2>&1; then +if /usr/bin/touch ${shellQuote(path.join(sandboxGitMetadata, "nemoclaw-validation-write-probe"))} >/dev/null 2>&1; then printf '%s\n' 'Git metadata was writable' >&2 exit 42 fi +if /bin/cat ${shellQuote(sandboxConfig)} 2>/dev/null | /usr/bin/grep -F 'benign-git-config-canary' >/dev/null; then + printf '%s\n' 'repository Git credential config was readable' >&2 + exit 43 +fi +if /usr/bin/git config --local --get-regexp '^http\\..*\\.extraHeader$' 2>/dev/null | /usr/bin/grep -F 'benign-git-config-canary' >/dev/null; then + printf '%s\n' 'repository Git credential config was active' >&2 + exit 44 +fi +${socketProbe} command -v node >/dev/null command -v npx >/dev/null printf '%s\n' "$HOME" >>"$PWD/wrapper-probe.log" `; const vitest = path.join(bin, "vitest"); fs.writeFileSync(vitest, probe, { mode: 0o755 }); - return { root, sentinel, worktree }; + return { config, root, sentinel, workdir }; } afterEach(() => { @@ -173,10 +212,13 @@ describe("credential-isolated validation wrappers", () => { expectNodeToolchainBoundary(commands[1]); }); - it.runIf(nativeSandboxAvailable)( - "runs both actual wrappers from a worktree without exposing host files or writable Git metadata", - async () => { - const fixture = createWorktreeFixture(); + it.runIf(nativeSandboxAvailable).each([ + ["ordinary checkout", false], + ["linked worktree", true], + ] as const)( + "runs both actual wrappers from a %s without exposing host files, Git credentials, or writable Git metadata", + async (_name, linked) => { + const fixture = createCheckoutFixture(linked); installTools((input) => { const result = spawnSync("/bin/sh", ["-c", input.command], { cwd: input.workdir, @@ -192,18 +234,64 @@ describe("credential-isolated validation wrappers", () => { }); try { - const result = await runBothWrappers(fixture.worktree); + const result = await runBothWrappers(fixture.workdir); expect(result).toEqual({ focusedOk: true, targetedCode: 0 }); const privateHomes = fs - .readFileSync(path.join(fixture.worktree, "wrapper-probe.log"), "utf8") + .readFileSync(path.join(fixture.workdir, "wrapper-probe.log"), "utf8") .trim() .split("\n"); expect(privateHomes).toHaveLength(2); expect(privateHomes.every((home) => home !== os.homedir())).toBe(true); expect(fs.readFileSync(fixture.sentinel, "utf8")).toBe("must remain unreadable\n"); + expect(fs.readFileSync(fixture.config, "utf8")).toContain("benign-git-config-canary"); + } finally { + fs.rmSync(fixture.root, { recursive: true, force: true }); + } + }, + ); + + it.runIf(process.platform === "darwin" && nativeSandboxAvailable)( + "denies outside Unix sockets through both actual macOS wrappers", + async () => { + const socketRoot = fs.mkdtempSync("/tmp/ncv-socket-"); + const socketPath = path.join(socketRoot, "outside.sock"); + const serverScript = path.join(socketRoot, "server.mjs"); + fs.writeFileSync( + serverScript, + `import net from "node:net";\nconst server = net.createServer((socket) => socket.end("outside-unix-socket-canary"));\nserver.listen(process.argv[2], () => process.stdout.write("ready\\n"));\n`, + ); + const server = spawn(process.execPath, [serverScript, socketPath], { + stdio: ["ignore", "pipe", "pipe"], + }); + const fixture = createCheckoutFixture(true, socketPath); + installTools((input) => { + const result = spawnSync("/bin/sh", ["-c", input.command], { + cwd: input.workdir, + encoding: "utf8", + env: process.env, + timeout: input.timeoutMs, + }); + return foreground( + result.status, + result.stdout, + result.stderr || result.error?.message || "", + ); + }); + + try { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.stdout.once("data", () => resolve()); + }); + await expect(runBothWrappers(fixture.workdir)).resolves.toEqual({ + focusedOk: true, + targetedCode: 0, + }); } finally { + server.kill(); fs.rmSync(fixture.root, { recursive: true, force: true }); + fs.rmSync(socketRoot, { recursive: true, force: true }); } }, ); From de585666c208b9ed6166be411954580b7461784c Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 23:18:04 -0700 Subject: [PATCH 09/12] test(tools): probe bubblewrap startup --- test/tools/validation-wrapper-isolation.test.ts | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/test/tools/validation-wrapper-isolation.test.ts b/test/tools/validation-wrapper-isolation.test.ts index daf170e3bc6..c73a59e8bf9 100644 --- a/test/tools/validation-wrapper-isolation.test.ts +++ b/test/tools/validation-wrapper-isolation.test.ts @@ -27,7 +27,14 @@ type TargetedVitestRunner = (input: Record) => Promise<{ code: const nativeSandboxAvailable = (process.platform === "darwin" && fs.existsSync("/usr/bin/sandbox-exec")) || (process.platform === "linux" && - spawnSync("/bin/sh", ["-c", "command -v bwrap"], { encoding: "utf8" }).status === 0); + spawnSync( + "/bin/sh", + [ + "-c", + "command -v bwrap >/dev/null 2>&1 && bwrap --die-with-parent --new-session --unshare-all --share-net --ro-bind / / /bin/true", + ], + { encoding: "utf8" }, + ).status === 0); function foreground(exitCode: number | null = 0, stdout = "", stderr = ""): BashResult { return { From 3b56741ad41ef5d7fcd660b5728d568092ba42e9 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Wed, 21 Oct 2026 23:29:21 -0700 Subject: [PATCH 10/12] fix(tools): hide nested Git credentials --- .../index.ts | 13 +++++-------- .dsh/tools/run_targeted_vitest/index.ts | 13 +++++-------- test/tools/validation-wrapper-isolation.test.ts | 16 +++++++++++++++- 3 files changed, 25 insertions(+), 17 deletions(-) diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index 69c5dc45b25..b64a1ab8fdc 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -141,11 +141,9 @@ if [ -n "$git_head_ref" ]; then else /usr/bin/git -C "$repo_root" rev-parse --verify HEAD >"$git_shadow/HEAD" fi -/usr/bin/git -C "$repo_root" for-each-ref --format='%(objectname) %(refname)' | -while IFS=' ' read -r git_ref_oid git_ref_name; do +/usr/bin/git -C "$repo_root" for-each-ref --format='update %(refname) %(objectname)' | /usr/bin/env -i PATH=/usr/bin:/bin GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ - /usr/bin/git --git-dir="$git_shadow" update-ref "$git_ref_name" "$git_ref_oid" -done + /usr/bin/git --git-dir="$git_shadow" update-ref --stdin if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" @@ -183,8 +181,9 @@ if [ -x /usr/bin/sandbox-exec ]; then (deny file-write* (subpath (param "GIT_DIR"))) (deny file-write* (subpath (param "GIT_COMMON_DIR"))) (deny file-read* - (literal (param "GIT_CONFIG_PATH")) - (literal (param "GIT_WORKTREE_CONFIG_PATH"))) + (subpath (param "GIT_DIR")) + (subpath (param "GIT_COMMON_DIR"))) +(allow file-read* (subpath (param "GIT_OBJECTS"))) (allow network-outbound (remote ip)) (allow network-inbound (local ip)) (allow network-bind (local ip)) @@ -194,8 +193,6 @@ PROFILE /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ -D GIT_OBJECTS="$git_common_dir/objects" \ - -D GIT_CONFIG_PATH="$git_common_dir/config" \ - -D GIT_WORKTREE_CONFIG_PATH="$git_dir/config.worktree" \ -D NODE_PREFIX="$node_prefix" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ diff --git a/.dsh/tools/run_targeted_vitest/index.ts b/.dsh/tools/run_targeted_vitest/index.ts index 3405377301f..9cba2dfd8dd 100644 --- a/.dsh/tools/run_targeted_vitest/index.ts +++ b/.dsh/tools/run_targeted_vitest/index.ts @@ -129,11 +129,9 @@ if [ -n "$git_head_ref" ]; then else /usr/bin/git -C "$repo_root" rev-parse --verify HEAD >"$git_shadow/HEAD" fi -/usr/bin/git -C "$repo_root" for-each-ref --format='%(objectname) %(refname)' | -while IFS=' ' read -r git_ref_oid git_ref_name; do +/usr/bin/git -C "$repo_root" for-each-ref --format='update %(refname) %(objectname)' | /usr/bin/env -i PATH=/usr/bin:/bin GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ - /usr/bin/git --git-dir="$git_shadow" update-ref "$git_ref_name" "$git_ref_oid" -done + /usr/bin/git --git-dir="$git_shadow" update-ref --stdin if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" @@ -171,8 +169,9 @@ if [ -x /usr/bin/sandbox-exec ]; then (deny file-write* (subpath (param "GIT_DIR"))) (deny file-write* (subpath (param "GIT_COMMON_DIR"))) (deny file-read* - (literal (param "GIT_CONFIG_PATH")) - (literal (param "GIT_WORKTREE_CONFIG_PATH"))) + (subpath (param "GIT_DIR")) + (subpath (param "GIT_COMMON_DIR"))) +(allow file-read* (subpath (param "GIT_OBJECTS"))) (allow network-outbound (remote ip)) (allow network-inbound (local ip)) (allow network-bind (local ip)) @@ -182,8 +181,6 @@ PROFILE /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ -D GIT_OBJECTS="$git_common_dir/objects" \ - -D GIT_CONFIG_PATH="$git_common_dir/config" \ - -D GIT_WORKTREE_CONFIG_PATH="$git_dir/config.worktree" \ -D NODE_PREFIX="$node_prefix" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ diff --git a/test/tools/validation-wrapper-isolation.test.ts b/test/tools/validation-wrapper-isolation.test.ts index c73a59e8bf9..4cb882a854f 100644 --- a/test/tools/validation-wrapper-isolation.test.ts +++ b/test/tools/validation-wrapper-isolation.test.ts @@ -115,7 +115,8 @@ function expectNodeToolchainBoundary(command: string): void { expect(command).toContain('PATH="$node_bin_dir:'); expect(command).toContain('GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root"'); expect(command).toContain("GIT_DIR=/git GIT_WORK_TREE=/workspace"); - expect(command).toContain('(literal (param "GIT_CONFIG_PATH"))'); + expect(command).toContain('(deny file-read*\n (subpath (param "GIT_DIR"))'); + expect(command).toContain('(allow file-read* (subpath (param "GIT_OBJECTS")))'); expect(command).toContain('--ro-bind "$git_shadow" /git'); expect(command).toContain("(allow network-outbound (remote ip))"); expect(command).toContain('(allow network* (subpath (param "ISOLATION_ROOT")))'); @@ -153,8 +154,17 @@ function createCheckoutFixture( linked ? git("worktree", "add", "-b", "fixture-worktree", worktree) : undefined; const workdir = linked ? worktree : repository; const config = path.join(repository, ".git", "config"); + const nestedConfig = path.join(repository, ".git", "modules", "fixture", "config"); + fs.mkdirSync(path.dirname(nestedConfig), { recursive: true }); + fs.writeFileSync(nestedConfig, "benign-submodule-git-config-canary\n", { mode: 0o600 }); const sandboxConfig = process.platform === "linux" ? (linked ? "/git/config" : "/workspace/.git/config") : config; + const sandboxNestedConfig = + process.platform === "linux" + ? linked + ? "/git/modules/fixture/config" + : "/workspace/.git/modules/fixture/config" + : nestedConfig; const sandboxGitMetadata = process.platform === "linux" ? linked @@ -189,6 +199,10 @@ if /usr/bin/git config --local --get-regexp '^http\\..*\\.extraHeader$' 2>/dev/n printf '%s\n' 'repository Git credential config was active' >&2 exit 44 fi +if /bin/cat ${shellQuote(sandboxNestedConfig)} 2>/dev/null | /usr/bin/grep -F 'benign-submodule-git-config-canary' >/dev/null; then + printf '%s\n' 'nested Git credential config was readable' >&2 + exit 46 +fi ${socketProbe} command -v node >/dev/null command -v npx >/dev/null From 6951b19e10aedc51397d9528de227f640dfa99e8 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 22 Oct 2026 00:05:24 -0700 Subject: [PATCH 11/12] fix(tools): close validation isolation gaps --- .../index.ts | 63 +++++- .dsh/tools/run_targeted_vitest/index.ts | 71 +++++-- .../validation-wrapper-isolation.test.ts | 192 ++++++++++++++++-- 3 files changed, 285 insertions(+), 41 deletions(-) diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index b64a1ab8fdc..328a0ecb8ed 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -104,10 +104,11 @@ repo_root=$(/bin/pwd -P) node_bin_dir=${q(nodeBinDir)} node_prefix=${q(nodePrefix)} node_prefix_parent=${q(nodePrefixParent)} -isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX) +isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX 2>/dev/null) || + isolation_root=$(/usr/bin/mktemp -d "\${TMPDIR:-/tmp}/ncv.XXXXXX") isolation_root=$(cd "$isolation_root" && /bin/pwd -P) trap '/bin/rm -R -f -- "$isolation_root"' EXIT -/bin/mkdir -p "$isolation_root/home" "$isolation_root/tmp" +/bin/mkdir -p "$isolation_root/bin" "$isolation_root/home" "$isolation_root/tmp" git_dir=$(/usr/bin/git -C "$repo_root" rev-parse --absolute-git-dir) git_common_dir=$(/usr/bin/git -C "$repo_root" rev-parse --path-format=absolute --git-common-dir) git_dir=$(cd "$git_dir" && /bin/pwd -P) @@ -145,6 +146,46 @@ fi /usr/bin/env -i PATH=/usr/bin:/bin GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ /usr/bin/git --git-dir="$git_shadow" update-ref --stdin +cat >"$isolation_root/bin/git" <<'GIT_WRAPPER' +#!/bin/sh +set -eu +repo_root=\${NEMOCLAW_REPO_ROOT:?} +git_shadow=\${NEMOCLAW_GIT_SHADOW:?} +if [ "\${GIT_DIR+x}" = x ] || [ "\${GIT_WORK_TREE+x}" = x ]; then + exec /usr/bin/git "$@" +fi +for git_arg do + if [ "$git_arg" = init ]; then exec /usr/bin/git "$@"; fi +done +git_cwd=$PWD +git_expect_c=false +for git_arg do + if [ "$git_expect_c" = true ]; then + case "$git_arg" in /*) git_cwd=$git_arg ;; *) git_cwd=$git_cwd/$git_arg ;; esac + git_expect_c=false + continue + fi + case "$git_arg" in + -C) git_expect_c=true ;; + -C?*) git_c_value=\${git_arg#-C}; case "$git_c_value" in /*) git_cwd=$git_c_value ;; *) git_cwd=$git_cwd/$git_c_value ;; esac ;; + esac +done +if git_cwd=$(cd "$git_cwd" 2>/dev/null && /bin/pwd -P); then + case "$git_cwd/" in + "$repo_root/"*) + git_probe=$git_cwd + while [ "$git_probe" != "$repo_root" ]; do + if [ -e "$git_probe/.git" ]; then exec /usr/bin/git "$@"; fi + git_probe=\${git_probe%/*} + done + exec /usr/bin/env GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root" /usr/bin/git "$@" + ;; + esac +fi +exec /usr/bin/git "$@" +GIT_WRAPPER +/bin/chmod 0555 "$isolation_root/bin/git" + if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" cat >"$sandbox_profile" <<'PROFILE' @@ -196,11 +237,11 @@ PROFILE -D NODE_PREFIX="$node_prefix" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ - PATH="$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ + PATH="$isolation_root/bin:$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ + NEMOCLAW_REPO_ROOT="$repo_root" NEMOCLAW_GIT_SHADOW="$git_shadow" \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ - GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root" \ /bin/sh -c ${q(command)} validation_status=$? set -e @@ -218,9 +259,8 @@ if command -v bwrap >/dev/null 2>&1; then printf 'gitdir: /git\n' >"$git_pointer" set -- "$@" --ro-bind "$git_pointer" /workspace/.git else - empty_git="$isolation_root/empty-git" - /bin/mkdir "$empty_git" - set -- "$@" --ro-bind "$empty_git" /workspace/.git + set -- "$@" --ro-bind "$git_shadow" /workspace/.git + set -- "$@" --ro-bind "$git_common_dir/objects" /workspace/.git/objects fi for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi @@ -236,7 +276,6 @@ if command -v bwrap >/dev/null 2>&1; then CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ - GIT_DIR=/git GIT_WORK_TREE=/workspace \ /bin/sh -c ${q(command)} validation_status=$? set -e @@ -327,6 +366,14 @@ exit 126`, failed: [], nul: null, }; + const hostHome = process.env.HOME ? realpathSync(process.env.HOME) : null; + if (!hostHome) throw new Error("Credential-isolated validation requires a resolvable host HOME."); + const homeRelativeToNodePrefix = path.relative(nodePrefix, hostHome); + if ( + homeRelativeToNodePrefix === "" || + (homeRelativeToNodePrefix !== ".." && !homeRelativeToNodePrefix.startsWith(".." + path.sep)) + ) + throw new Error("Credential-isolated validation cannot expose the host HOME."); const steps = []; for (const item of commands) { const r = await tools.bash({ diff --git a/.dsh/tools/run_targeted_vitest/index.ts b/.dsh/tools/run_targeted_vitest/index.ts index 9cba2dfd8dd..ba788582bb0 100644 --- a/.dsh/tools/run_targeted_vitest/index.ts +++ b/.dsh/tools/run_targeted_vitest/index.ts @@ -66,7 +66,7 @@ export default async function run_targeted_vitest(input: { "Vitest projects must be non-option repository-relative names of at most 128 characters", ); const quote = (v) => "'" + String(v).replaceAll("'", "'\"'\"'") + "'"; - const args = ["vitest", "run", ...projects.flatMap((x) => ["--project", x]), ...input.files]; + const args = ["run", ...projects.flatMap((x) => ["--project", x]), ...input.files]; if (input.coverage) args.push( "--coverage", @@ -85,17 +85,21 @@ export default async function run_targeted_vitest(input: { const nodeBinDir = path.dirname(nodeExecutable); const nodePrefix = path.dirname(nodeBinDir); const nodePrefixParent = path.dirname(nodePrefix); - const command = "npx " + args.map(quote).join(" "); + const command = + `${quote(nodeExecutable)} ${quote("node_modules/vitest/vitest.mjs")} ` + + args.map(quote).join(" "); const isolatedCommand = `set -eu umask 077 repo_root=$(/bin/pwd -P) +node_executable=${quote(nodeExecutable)} node_bin_dir=${quote(nodeBinDir)} node_prefix=${quote(nodePrefix)} node_prefix_parent=${quote(nodePrefixParent)} -isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX) +isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX 2>/dev/null) || + isolation_root=$(/usr/bin/mktemp -d "\${TMPDIR:-/tmp}/ncv.XXXXXX") isolation_root=$(cd "$isolation_root" && /bin/pwd -P) trap '/bin/rm -R -f -- "$isolation_root"' EXIT -/bin/mkdir -p "$isolation_root/home" "$isolation_root/tmp" +/bin/mkdir -p "$isolation_root/bin" "$isolation_root/home" "$isolation_root/tmp" git_dir=$(/usr/bin/git -C "$repo_root" rev-parse --absolute-git-dir) git_common_dir=$(/usr/bin/git -C "$repo_root" rev-parse --path-format=absolute --git-common-dir) git_dir=$(cd "$git_dir" && /bin/pwd -P) @@ -133,6 +137,46 @@ fi /usr/bin/env -i PATH=/usr/bin:/bin GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 \ /usr/bin/git --git-dir="$git_shadow" update-ref --stdin +cat >"$isolation_root/bin/git" <<'GIT_WRAPPER' +#!/bin/sh +set -eu +repo_root=\${NEMOCLAW_REPO_ROOT:?} +git_shadow=\${NEMOCLAW_GIT_SHADOW:?} +if [ "\${GIT_DIR+x}" = x ] || [ "\${GIT_WORK_TREE+x}" = x ]; then + exec /usr/bin/git "$@" +fi +for git_arg do + if [ "$git_arg" = init ]; then exec /usr/bin/git "$@"; fi +done +git_cwd=$PWD +git_expect_c=false +for git_arg do + if [ "$git_expect_c" = true ]; then + case "$git_arg" in /*) git_cwd=$git_arg ;; *) git_cwd=$git_cwd/$git_arg ;; esac + git_expect_c=false + continue + fi + case "$git_arg" in + -C) git_expect_c=true ;; + -C?*) git_c_value=\${git_arg#-C}; case "$git_c_value" in /*) git_cwd=$git_c_value ;; *) git_cwd=$git_cwd/$git_c_value ;; esac ;; + esac +done +if git_cwd=$(cd "$git_cwd" 2>/dev/null && /bin/pwd -P); then + case "$git_cwd/" in + "$repo_root/"*) + git_probe=$git_cwd + while [ "$git_probe" != "$repo_root" ]; do + if [ -e "$git_probe/.git" ]; then exec /usr/bin/git "$@"; fi + git_probe=\${git_probe%/*} + done + exec /usr/bin/env GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root" /usr/bin/git "$@" + ;; + esac +fi +exec /usr/bin/git "$@" +GIT_WRAPPER +/bin/chmod 0555 "$isolation_root/bin/git" + if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" cat >"$sandbox_profile" <<'PROFILE' @@ -160,7 +204,7 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) (subpath (param "GIT_OBJECTS")) - (subpath (param "NODE_PREFIX"))) + (literal (param "NODE_EXECUTABLE"))) (allow file-write* (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) @@ -181,14 +225,14 @@ PROFILE /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ -D GIT_OBJECTS="$git_common_dir/objects" \ - -D NODE_PREFIX="$node_prefix" \ + -D NODE_EXECUTABLE="$node_executable" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ - PATH="$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ + PATH="$isolation_root/bin:$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ + NEMOCLAW_REPO_ROOT="$repo_root" NEMOCLAW_GIT_SHADOW="$git_shadow" \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ - GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root" \ /bin/sh -c ${quote(command)} validation_status=$? set -e @@ -206,16 +250,16 @@ if command -v bwrap >/dev/null 2>&1; then printf 'gitdir: /git\n' >"$git_pointer" set -- "$@" --ro-bind "$git_pointer" /workspace/.git else - empty_git="$isolation_root/empty-git" - /bin/mkdir "$empty_git" - set -- "$@" --ro-bind "$empty_git" /workspace/.git + set -- "$@" --ro-bind "$git_shadow" /workspace/.git + set -- "$@" --ro-bind "$git_common_dir/objects" /workspace/.git/objects fi for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi done - case "$node_prefix" in + case "$node_executable" in /usr|/usr/*|/bin|/bin/*|/sbin|/sbin/*|/lib|/lib/*|/lib64|/lib64/*|/opt|/opt/*|/etc|/etc/*) ;; - *) set -- "$@" --dir "$node_prefix_parent" --ro-bind "$node_prefix" "$node_prefix" ;; + *) set -- "$@" --dir "$node_prefix_parent" --dir "$node_prefix" --dir "$node_bin_dir" \ + --ro-bind "$node_executable" "$node_executable" ;; esac set +e "$@" --chdir /workspace /usr/bin/env -i \ @@ -224,7 +268,6 @@ if command -v bwrap >/dev/null 2>&1; then CI=true NO_COLOR=1 TERM=dumb \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ - GIT_DIR=/git GIT_WORK_TREE=/workspace \ /bin/sh -c ${quote(command)} validation_status=$? set -e diff --git a/test/tools/validation-wrapper-isolation.test.ts b/test/tools/validation-wrapper-isolation.test.ts index 4cb882a854f..112833ced91 100644 --- a/test/tools/validation-wrapper-isolation.test.ts +++ b/test/tools/validation-wrapper-isolation.test.ts @@ -21,11 +21,19 @@ type BashResult = { stderr: { text: string; truncated: boolean }; }; -type FocusedValidationRunner = (input: Record) => Promise<{ ok: boolean }>; -type TargetedVitestRunner = (input: Record) => Promise<{ code: number }>; +type FocusedValidationRunner = ( + input: Record, +) => Promise<{ failed: unknown[]; ok: boolean }>; +type TargetedVitestRunner = ( + input: Record, +) => Promise<{ code: number; stderr: string }>; const nativeSandboxAvailable = - (process.platform === "darwin" && fs.existsSync("/usr/bin/sandbox-exec")) || + (process.platform === "darwin" && + fs.existsSync("/usr/bin/sandbox-exec") && + spawnSync("/usr/bin/sandbox-exec", ["-p", "(version 1)\n(allow default)", "/usr/bin/true"], { + encoding: "utf8", + }).status === 0) || (process.platform === "linux" && spawnSync( "/bin/sh", @@ -108,24 +116,37 @@ function shellQuote(value: string): string { return `'${value.replaceAll("'", `'"'"'`)}'`; } -function expectNodeToolchainBoundary(command: string): void { - expect(command).toContain('(subpath (param "NODE_PREFIX"))'); - expect(command).toContain('-D NODE_PREFIX="$node_prefix"'); - expect(command).toContain('--ro-bind "$node_prefix" "$node_prefix"'); - expect(command).toContain('PATH="$node_bin_dir:'); - expect(command).toContain('GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root"'); - expect(command).toContain("GIT_DIR=/git GIT_WORK_TREE=/workspace"); - expect(command).toContain('(deny file-read*\n (subpath (param "GIT_DIR"))'); - expect(command).toContain('(allow file-read* (subpath (param "GIT_OBJECTS")))'); - expect(command).toContain('--ro-bind "$git_shadow" /git'); +function expectCommonIsolationBoundary(command: string): void { + expect(command).toContain('PATH="$isolation_root/bin:'); + expect(command).toContain('exec /usr/bin/env GIT_DIR="$git_shadow" GIT_WORK_TREE="$repo_root"'); + expect(command).not.toContain("GIT_DIR=/git GIT_WORK_TREE=/workspace"); + expect(command).toMatch(/\(deny file-read\*\s+\(subpath \(param "GIT_DIR"\)\)/); + expect(command).toMatch(/\(allow file-read\* \(subpath \(param "GIT_OBJECTS"\)\)\)/); + expect(command).toContain('--ro-bind "$git_shadow" /workspace/.git'); expect(command).toContain("(allow network-outbound (remote ip))"); expect(command).toContain('(allow network* (subpath (param "ISOLATION_ROOT")))'); expect(command).not.toContain("(allow network*)"); } +function expectFocusedNodeToolchainBoundary(command: string): void { + expect(command).toContain('(subpath (param "NODE_PREFIX"))'); + expect(command).toContain('-D NODE_PREFIX="$node_prefix"'); + expect(command).toContain('--ro-bind "$node_prefix" "$node_prefix"'); + expectCommonIsolationBoundary(command); +} + +function expectTargetedNodeToolchainBoundary(command: string): void { + expect(command).toContain('(literal (param "NODE_EXECUTABLE"))'); + expect(command).toContain('-D NODE_EXECUTABLE="$node_executable"'); + expect(command).toContain('--ro-bind "$node_executable" "$node_executable"'); + expect(command).not.toContain('(subpath (param "NODE_PREFIX"))'); + expectCommonIsolationBoundary(command); +} + function createCheckoutFixture( linked: boolean, outsideSocket?: string, + outsideReadableCanary?: string, ): { config: string; root: string; sentinel: string; workdir: string } { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-wrapper-isolation-")); const repository = path.join(root, "repository"); @@ -175,6 +196,12 @@ function createCheckoutFixture( ? `if /usr/bin/nc -w 1 -U ${shellQuote(outsideSocket)} 2>/dev/null | /usr/bin/grep -F 'outside-unix-socket-canary' >/dev/null; then printf '%s\\n' 'outside Unix socket was reachable' >&2 exit 45 +fi` + : ""; + const readableCanaryProbe = outsideReadableCanary + ? `if /bin/cat ${shellQuote(outsideReadableCanary)} >/dev/null 2>&1; then + printf '%s\\n' 'outside credential canary was readable' >&2 + exit 47 fi` : ""; @@ -182,7 +209,7 @@ fi` fs.mkdirSync(bin, { recursive: true }); const probe = `#!/bin/sh set -eu -/usr/bin/git status --short >/dev/null +git status --short >/dev/null if /bin/cat ${shellQuote(sentinel)} >/dev/null 2>&1; then printf '%s\n' 'outside-checkout sentinel was readable' >&2 exit 41 @@ -195,7 +222,7 @@ if /bin/cat ${shellQuote(sandboxConfig)} 2>/dev/null | /usr/bin/grep -F 'benign- printf '%s\n' 'repository Git credential config was readable' >&2 exit 43 fi -if /usr/bin/git config --local --get-regexp '^http\\..*\\.extraHeader$' 2>/dev/null | /usr/bin/grep -F 'benign-git-config-canary' >/dev/null; then +if git config --local --get-regexp '^http\\..*\\.extraHeader$' 2>/dev/null | /usr/bin/grep -F 'benign-git-config-canary' >/dev/null; then printf '%s\n' 'repository Git credential config was active' >&2 exit 44 fi @@ -204,15 +231,39 @@ if /bin/cat ${shellQuote(sandboxNestedConfig)} 2>/dev/null | /usr/bin/grep -F 'b exit 46 fi ${socketProbe} +${readableCanaryProbe} +nested_repository="$TMPDIR/nested-repository" +/bin/mkdir "$nested_repository" +git init --initial-branch=main "$nested_repository" >/dev/null +printf '%s\n' 'nested fixture' >"$nested_repository/tracked.txt" +git -C "$nested_repository" add tracked.txt +test -f "$nested_repository/.git/index" command -v node >/dev/null -command -v npx >/dev/null printf '%s\n' "$HOME" >>"$PWD/wrapper-probe.log" `; const vitest = path.join(bin, "vitest"); fs.writeFileSync(vitest, probe, { mode: 0o755 }); + const vitestPackage = path.join(workdir, "node_modules", "vitest"); + fs.mkdirSync(vitestPackage, { recursive: true }); + fs.writeFileSync( + path.join(vitestPackage, "vitest.mjs"), + `import { spawnSync } from "node:child_process"; +import path from "node:path"; +const result = spawnSync(path.join(process.cwd(), "node_modules", ".bin", "vitest"), { + stdio: "inherit", +}); +process.exit(result.status ?? 1); +`, + ); return { config, root, sentinel, workdir }; } +function createShortSocketRoot(): string { + const preferred = path.join(os.tmpdir(), "ncv-s."); + const socketSuffixLength = 6 + "/outside.sock".length; + return fs.mkdtempSync(preferred.length + socketSuffixLength <= 103 ? preferred : "/tmp/ncv-s."); +} + afterEach(() => { vi.unstubAllGlobals(); }); @@ -229,8 +280,8 @@ describe("credential-isolated validation wrappers", () => { expect(result).toEqual({ focusedOk: true, targetedCode: 0 }); expect(commands).toHaveLength(2); - expectNodeToolchainBoundary(commands[0]); - expectNodeToolchainBoundary(commands[1]); + expectFocusedNodeToolchainBoundary(commands[0]); + expectTargetedNodeToolchainBoundary(commands[1]); }); it.runIf(nativeSandboxAvailable).each([ @@ -272,10 +323,113 @@ describe("credential-isolated validation wrappers", () => { }, ); + it.runIf(nativeSandboxAvailable)( + "denies sibling credentials when Node is installed directly under the host home", + async () => { + const syntheticHome = fs.mkdtempSync(path.join(os.tmpdir(), "ncv-node-home-")); + const syntheticBin = path.join(syntheticHome, "bin"); + const syntheticNode = path.join(syntheticBin, "node"); + const credentialCanary = path.join(syntheticHome, ".ssh", "nemoclaw-canary"); + fs.mkdirSync(syntheticBin, { recursive: true }); + fs.mkdirSync(path.dirname(credentialCanary), { recursive: true }); + fs.writeFileSync(syntheticNode, '#!/bin/sh\nexec "$PWD/node_modules/.bin/vitest" "$@"\n', { + mode: 0o755, + }); + fs.writeFileSync(credentialCanary, "must remain unreadable\n", { mode: 0o600 }); + const fixture = createCheckoutFixture(false, undefined, credentialCanary); + const originalExecPath = Object.getOwnPropertyDescriptor(process, "execPath"); + const originalHome = process.env.HOME; + Object.defineProperty(process, "execPath", { ...originalExecPath, value: syntheticNode }); + process.env.HOME = syntheticHome; + installTools((input) => { + const result = spawnSync("/bin/sh", ["-c", input.command], { + cwd: input.workdir, + encoding: "utf8", + env: process.env, + timeout: input.timeoutMs, + }); + return foreground( + result.status, + result.stdout, + result.stderr || result.error?.message || "", + ); + }); + + try { + const [{ default: runFocusedValidation }, { default: runTargetedVitest }] = + await Promise.all([ + vi.importActual<{ default: FocusedValidationRunner }>( + "../../.dsh/tools/run_nemoclaw_focused_repair_validation/index", + ), + vi.importActual<{ default: TargetedVitestRunner }>( + "../../.dsh/tools/run_targeted_vitest/index", + ), + ]); + await expect( + runFocusedValidation({ + workdir: fixture.workdir, + files: [], + testFiles: ["probe.test.ts"], + projects: ["integration"], + baseRef: "HEAD", + formatWrite: false, + typecheckCli: false, + typecheckPlugin: false, + repoChecks: false, + diffCheck: false, + nulCheck: false, + docs: false, + dryRun: false, + }), + ).rejects.toThrow("cannot expose the host HOME"); + const targeted = await runTargetedVitest({ + workdir: fixture.workdir, + files: ["probe.test.ts"], + projects: ["integration"], + }); + expect(targeted, targeted.stderr).toMatchObject({ code: 0 }); + expect(fs.readFileSync(credentialCanary, "utf8")).toBe("must remain unreadable\n"); + } finally { + Object.defineProperty(process, "execPath", originalExecPath as PropertyDescriptor); + originalHome === undefined ? delete process.env.HOME : (process.env.HOME = originalHome); + fs.rmSync(fixture.root, { recursive: true, force: true }); + fs.rmSync(syntheticHome, { recursive: true, force: true }); + } + }, + ); + + it.runIf(process.platform === "darwin")( + "creates the Unix-socket fixture under the active bounded temporary root", + async () => { + const socketRoot = createShortSocketRoot(); + const socketPath = path.join(socketRoot, "outside.sock"); + const server = spawn( + process.execPath, + [ + "-e", + 'const net = require("node:net"); const server = net.createServer(); server.listen(process.argv[1], () => process.stdout.write("ready\\n"));', + socketPath, + ], + { stdio: ["ignore", "pipe", "pipe"] }, + ); + try { + await new Promise((resolve, reject) => { + server.once("error", reject); + server.stdout.once("data", () => resolve()); + }); + expect(socketPath.length).toBeLessThanOrEqual(103); + expect(socketRoot.startsWith(os.tmpdir()) || socketRoot.startsWith("/tmp/")).toBe(true); + } finally { + server.kill(); + fs.rmSync(socketRoot, { recursive: true, force: true }); + } + }, + ); + it.runIf(process.platform === "darwin" && nativeSandboxAvailable)( "denies outside Unix sockets through both actual macOS wrappers", async () => { - const socketRoot = fs.mkdtempSync("/tmp/ncv-socket-"); + const socketRoot = createShortSocketRoot(); const socketPath = path.join(socketRoot, "outside.sock"); const serverScript = path.join(socketRoot, "server.mjs"); fs.writeFileSync( From 0609b8cac04c311ab102bb8ab305cec6084288f6 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Thu, 22 Oct 2026 00:38:45 -0700 Subject: [PATCH 12/12] fix(tools): restrict focused validation runtime --- .../index.ts | 84 ++++++++++++++----- .../validation-wrapper-isolation.test.ts | 49 +++-------- 2 files changed, 76 insertions(+), 57 deletions(-) diff --git a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index 328a0ecb8ed..952d1646235 100644 --- a/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts +++ b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts @@ -94,21 +94,51 @@ export default async function run_nemoclaw_focused_repair_validation(input: { if (!projects.every((x) => allowed.has(x))) throw new Error("Unsupported Vitest project"); const nodeExecutable = realpathSync(process.execPath), nodeBinDir = path.dirname(nodeExecutable), - nodePrefix = path.dirname(nodeBinDir), - nodePrefixParent = path.dirname(nodePrefix), - q = (v) => "'" + String(v).replaceAll("'", "'\"'\"'") + "'", + nodeBinParent = path.dirname(nodeBinDir), + resolveNpmCli = (name: "npm" | "npx") => { + const candidates = [ + nodeBinDir, + ...(process.env.PATH ?? "").split(path.delimiter).filter(Boolean), + ]; + for (const directory of new Set(candidates)) { + try { + const cli = realpathSync(path.join(directory, name)), + cliDirectory = path.dirname(cli), + root = path.dirname(cliDirectory); + if ( + path.basename(cli) === `${name}-cli.js` && + path.basename(cliDirectory) === "bin" && + path.basename(root) === "npm" + ) + return { cli, root }; + } catch { + // Try the next host PATH entry. + } + } + throw new Error(`Credential-isolated validation requires the standard ${name} CLI layout.`); + }, + npmRuntime = resolveNpmCli("npm"), + npxRuntime = resolveNpmCli("npx"); + if (npmRuntime.root !== npxRuntime.root) + throw new Error("Credential-isolated validation requires npm and npx from one package."); + const q = (v) => "'" + String(v).replaceAll("'", "'\"'\"'") + "'", isolate = (command) => `set -eu umask 077 repo_root=$(/bin/pwd -P) +node_executable=${q(nodeExecutable)} node_bin_dir=${q(nodeBinDir)} -node_prefix=${q(nodePrefix)} -node_prefix_parent=${q(nodePrefixParent)} +node_bin_parent=${q(nodeBinParent)} +npm_cli=${q(npmRuntime.cli)} +npx_cli=${q(npxRuntime.cli)} +npm_root=${q(npmRuntime.root)} +npm_root_parent=${q(path.dirname(npmRuntime.root))} isolation_root=$(/usr/bin/mktemp -d /tmp/ncv.XXXXXX 2>/dev/null) || isolation_root=$(/usr/bin/mktemp -d "\${TMPDIR:-/tmp}/ncv.XXXXXX") isolation_root=$(cd "$isolation_root" && /bin/pwd -P) trap '/bin/rm -R -f -- "$isolation_root"' EXIT -/bin/mkdir -p "$isolation_root/bin" "$isolation_root/home" "$isolation_root/tmp" +/bin/mkdir -p \ + "$isolation_root/bin" "$isolation_root/runtime-bin" "$isolation_root/home" "$isolation_root/tmp" git_dir=$(/usr/bin/git -C "$repo_root" rev-parse --absolute-git-dir) git_common_dir=$(/usr/bin/git -C "$repo_root" rev-parse --path-format=absolute --git-common-dir) git_dir=$(cd "$git_dir" && /bin/pwd -P) @@ -184,7 +214,16 @@ if git_cwd=$(cd "$git_cwd" 2>/dev/null && /bin/pwd -P); then fi exec /usr/bin/git "$@" GIT_WRAPPER -/bin/chmod 0555 "$isolation_root/bin/git" +cat >"$isolation_root/runtime-bin/npm" <<'NPM_WRAPPER' +#!/bin/sh +exec "$NEMOCLAW_NODE_EXECUTABLE" "$NEMOCLAW_NPM_CLI" "$@" +NPM_WRAPPER +cat >"$isolation_root/runtime-bin/npx" <<'NPX_WRAPPER' +#!/bin/sh +exec "$NEMOCLAW_NODE_EXECUTABLE" "$NEMOCLAW_NPX_CLI" "$@" +NPX_WRAPPER +/bin/chmod 0555 \ + "$isolation_root/bin/git" "$isolation_root/runtime-bin/npm" "$isolation_root/runtime-bin/npx" if [ -x /usr/bin/sandbox-exec ]; then sandbox_profile="$isolation_root/profile.sb" @@ -213,7 +252,8 @@ if [ -x /usr/bin/sandbox-exec ]; then (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) (subpath (param "GIT_OBJECTS")) - (subpath (param "NODE_PREFIX"))) + (literal (param "NODE_EXECUTABLE")) + (subpath (param "NPM_ROOT"))) (allow file-write* (subpath (param "REPO_ROOT")) (subpath (param "ISOLATION_ROOT")) @@ -234,12 +274,14 @@ PROFILE /usr/bin/sandbox-exec -D REPO_ROOT="$repo_root" -D ISOLATION_ROOT="$isolation_root" \ -D GIT_DIR="$git_dir" -D GIT_COMMON_DIR="$git_common_dir" \ -D GIT_OBJECTS="$git_common_dir/objects" \ - -D NODE_PREFIX="$node_prefix" \ + -D NODE_EXECUTABLE="$node_executable" -D NPM_ROOT="$npm_root" \ -f "$sandbox_profile" /usr/bin/env -i \ HOME="$isolation_root/home" XDG_CONFIG_HOME="$isolation_root/home" TMPDIR="$isolation_root/tmp" \ - PATH="$isolation_root/bin:$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ + PATH="$isolation_root/bin:$isolation_root/runtime-bin:$node_bin_dir:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ NEMOCLAW_REPO_ROOT="$repo_root" NEMOCLAW_GIT_SHADOW="$git_shadow" \ + NEMOCLAW_NODE_EXECUTABLE="$node_executable" \ + NEMOCLAW_NPM_CLI="$npm_cli" NEMOCLAW_NPX_CLI="$npx_cli" \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ /bin/sh -c ${q(command)} @@ -251,6 +293,7 @@ fi if command -v bwrap >/dev/null 2>&1; then set -- "$(command -v bwrap)" --die-with-parent --new-session --unshare-all --share-net set -- "$@" --proc /proc --dev /dev --tmpfs /tmp --dir /home + set -- "$@" --dir /ncv --ro-bind "$isolation_root/runtime-bin" /ncv/bin set -- "$@" --bind "$isolation_root/home" /home/validator --bind "$repo_root" /workspace set -- "$@" --dir /git --ro-bind "$git_shadow" /git set -- "$@" --ro-bind "$git_common_dir/objects" /git/objects @@ -265,15 +308,22 @@ if command -v bwrap >/dev/null 2>&1; then for system_path in /usr /bin /sbin /lib /lib64 /opt /etc; do if [ -e "$system_path" ]; then set -- "$@" --ro-bind "$system_path" "$system_path"; fi done - case "$node_prefix" in + case "$node_executable" in + /usr|/usr/*|/bin|/bin/*|/sbin|/sbin/*|/lib|/lib/*|/lib64|/lib64/*|/opt|/opt/*|/etc|/etc/*) ;; + *) set -- "$@" --dir "$node_bin_parent" --dir "$node_bin_dir" \ + --ro-bind "$node_executable" "$node_executable" ;; + esac + case "$npm_root" in /usr|/usr/*|/bin|/bin/*|/sbin|/sbin/*|/lib|/lib/*|/lib64|/lib64/*|/opt|/opt/*|/etc|/etc/*) ;; - *) set -- "$@" --dir "$node_prefix_parent" --ro-bind "$node_prefix" "$node_prefix" ;; + *) set -- "$@" --dir "$npm_root_parent" --ro-bind "$npm_root" "$npm_root" ;; esac set +e "$@" --chdir /workspace /usr/bin/env -i \ HOME=/home/validator XDG_CONFIG_HOME=/home/validator TMPDIR=/tmp \ - PATH="$node_bin_dir:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ + PATH="/ncv/bin:$node_bin_dir:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin" \ CI=true NO_COLOR=1 TERM=dumb \ + NEMOCLAW_NODE_EXECUTABLE="$node_executable" \ + NEMOCLAW_NPM_CLI="$npm_cli" NEMOCLAW_NPX_CLI="$npx_cli" \ NPM_CONFIG_USERCONFIG=/dev/null \ GIT_CONFIG_GLOBAL=/dev/null GIT_CONFIG_NOSYSTEM=1 GIT_OPTIONAL_LOCKS=0 \ /bin/sh -c ${q(command)} @@ -366,14 +416,6 @@ exit 126`, failed: [], nul: null, }; - const hostHome = process.env.HOME ? realpathSync(process.env.HOME) : null; - if (!hostHome) throw new Error("Credential-isolated validation requires a resolvable host HOME."); - const homeRelativeToNodePrefix = path.relative(nodePrefix, hostHome); - if ( - homeRelativeToNodePrefix === "" || - (homeRelativeToNodePrefix !== ".." && !homeRelativeToNodePrefix.startsWith(".." + path.sep)) - ) - throw new Error("Credential-isolated validation cannot expose the host HOME."); const steps = []; for (const item of commands) { const r = await tools.bash({ diff --git a/test/tools/validation-wrapper-isolation.test.ts b/test/tools/validation-wrapper-isolation.test.ts index 112833ced91..a23af219f40 100644 --- a/test/tools/validation-wrapper-isolation.test.ts +++ b/test/tools/validation-wrapper-isolation.test.ts @@ -129,9 +129,12 @@ function expectCommonIsolationBoundary(command: string): void { } function expectFocusedNodeToolchainBoundary(command: string): void { - expect(command).toContain('(subpath (param "NODE_PREFIX"))'); - expect(command).toContain('-D NODE_PREFIX="$node_prefix"'); - expect(command).toContain('--ro-bind "$node_prefix" "$node_prefix"'); + expect(command).toContain('(literal (param "NODE_EXECUTABLE"))'); + expect(command).toContain('(subpath (param "NPM_ROOT"))'); + expect(command).toContain('-D NODE_EXECUTABLE="$node_executable" -D NPM_ROOT="$npm_root"'); + expect(command).toContain('--ro-bind "$node_executable" "$node_executable"'); + expect(command).toContain('--ro-bind "$npm_root" "$npm_root"'); + expect(command).not.toContain('(subpath (param "NODE_PREFIX"))'); expectCommonIsolationBoundary(command); } @@ -324,9 +327,10 @@ describe("credential-isolated validation wrappers", () => { ); it.runIf(nativeSandboxAvailable)( - "denies sibling credentials when Node is installed directly under the host home", + "denies sibling credentials when Node is installed under a home other than parent HOME", async () => { const syntheticHome = fs.mkdtempSync(path.join(os.tmpdir(), "ncv-node-home-")); + const parentHome = fs.mkdtempSync(path.join(os.tmpdir(), "ncv-parent-home-")); const syntheticBin = path.join(syntheticHome, "bin"); const syntheticNode = path.join(syntheticBin, "node"); const credentialCanary = path.join(syntheticHome, ".ssh", "nemoclaw-canary"); @@ -340,7 +344,7 @@ describe("credential-isolated validation wrappers", () => { const originalExecPath = Object.getOwnPropertyDescriptor(process, "execPath"); const originalHome = process.env.HOME; Object.defineProperty(process, "execPath", { ...originalExecPath, value: syntheticNode }); - process.env.HOME = syntheticHome; + process.env.HOME = parentHome; installTools((input) => { const result = spawnSync("/bin/sh", ["-c", input.command], { cwd: input.workdir, @@ -356,44 +360,17 @@ describe("credential-isolated validation wrappers", () => { }); try { - const [{ default: runFocusedValidation }, { default: runTargetedVitest }] = - await Promise.all([ - vi.importActual<{ default: FocusedValidationRunner }>( - "../../.dsh/tools/run_nemoclaw_focused_repair_validation/index", - ), - vi.importActual<{ default: TargetedVitestRunner }>( - "../../.dsh/tools/run_targeted_vitest/index", - ), - ]); - await expect( - runFocusedValidation({ - workdir: fixture.workdir, - files: [], - testFiles: ["probe.test.ts"], - projects: ["integration"], - baseRef: "HEAD", - formatWrite: false, - typecheckCli: false, - typecheckPlugin: false, - repoChecks: false, - diffCheck: false, - nulCheck: false, - docs: false, - dryRun: false, - }), - ).rejects.toThrow("cannot expose the host HOME"); - const targeted = await runTargetedVitest({ - workdir: fixture.workdir, - files: ["probe.test.ts"], - projects: ["integration"], + await expect(runBothWrappers(fixture.workdir)).resolves.toEqual({ + focusedOk: true, + targetedCode: 0, }); - expect(targeted, targeted.stderr).toMatchObject({ code: 0 }); expect(fs.readFileSync(credentialCanary, "utf8")).toBe("must remain unreadable\n"); } finally { Object.defineProperty(process, "execPath", originalExecPath as PropertyDescriptor); originalHome === undefined ? delete process.env.HOME : (process.env.HOME = originalHome); fs.rmSync(fixture.root, { recursive: true, force: true }); fs.rmSync(syntheticHome, { recursive: true, force: true }); + fs.rmSync(parentHome, { recursive: true, force: true }); } }, );