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/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts b/.dsh/tools/run_nemoclaw_focused_repair_validation/index.ts index 8f575ed3ff1..952d1646235 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,7 +92,248 @@ 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 nodeExecutable = realpathSync(process.execPath), + nodeBinDir = path.dirname(nodeExecutable), + 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_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/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) +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 + +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='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 --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 +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" + 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")) + (subpath (param "GIT_OBJECTS")) + (literal (param "NODE_EXECUTABLE")) + (subpath (param "NPM_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"))) +(deny file-write* (subpath (param "GIT_DIR"))) +(deny file-write* (subpath (param "GIT_COMMON_DIR"))) +(deny file-read* + (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)) +(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 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:$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)} + 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 -- "$@" --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 + if [ -n "$git_worktree_name" ]; then + git_pointer="$isolation_root/git-pointer" + printf 'gitdir: /git\n' >"$git_pointer" + set -- "$@" --ro-bind "$git_pointer" /workspace/.git + else + 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_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 "$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="/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)} + 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) { @@ -175,9 +419,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..ba788582bb0 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. */ @@ -63,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", @@ -78,11 +81,205 @@ 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 command = "npx " + args.map(quote).join(" "); + const nodeExecutable = realpathSync(process.execPath); + const nodeBinDir = path.dirname(nodeExecutable); + const nodePrefix = path.dirname(nodeBinDir); + const nodePrefixParent = path.dirname(nodePrefix); + 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 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" +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 + +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='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 --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' +(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")) + (subpath (param "GIT_OBJECTS")) + (literal (param "NODE_EXECUTABLE"))) +(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"))) +(deny file-read* + (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)) +(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 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="$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 \ + /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 + 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\n' >"$git_pointer" + set -- "$@" --ro-bind "$git_pointer" /workspace/.git + else + 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_executable" in + /usr|/usr/*|/bin|/bin/*|/sbin|/sbin/*|/lib|/lib/*|/lib64|/lib64/*|/opt|/opt/*|/etc|/etc/*) ;; + *) 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 \ + HOME=/home/validator XDG_CONFIG_HOME=/home/validator TMPDIR=/tmp \ + 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 \ + /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, + 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"); 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/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/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", ]), }); 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-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/src/lib/onboard/install-ollama-linux.test.ts b/src/lib/onboard/install-ollama-linux.test.ts index 2cf375c8e6e..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"; @@ -10,7 +12,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 +29,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 +56,21 @@ describe("resolveOllamaTarballArch", () => { }); }); +describe("sha256File", () => { + it("computes a lowercase SHA-256 identity for downloaded bytes", () => { + 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"); + 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 +509,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 +596,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", 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..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( - `${onboardChildRuntimeSource}\nreturn { installPromptQueue };`, - )() 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/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}); 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([]); + }); +}); diff --git a/test/tools/validation-wrapper-isolation.test.ts b/test/tools/validation-wrapper-isolation.test.ts new file mode 100644 index 00000000000..a23af219f40 --- /dev/null +++ b/test/tools/validation-wrapper-isolation.test.ts @@ -0,0 +1,450 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawn, 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<{ failed: unknown[]; ok: boolean }>; +type TargetedVitestRunner = ( + input: Record, +) => Promise<{ code: number; stderr: string }>; + +const nativeSandboxAvailable = + (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", + [ + "-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 { + 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 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('(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); +} + +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"); + 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"); + 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"); + 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 + ? "/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 readableCanaryProbe = outsideReadableCanary + ? `if /bin/cat ${shellQuote(outsideReadableCanary)} >/dev/null 2>&1; then + printf '%s\\n' 'outside credential canary was readable' >&2 + exit 47 +fi` + : ""; + + const bin = path.join(workdir, "node_modules", ".bin"); + fs.mkdirSync(bin, { recursive: true }); + const probe = `#!/bin/sh +set -eu +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 +fi +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 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 +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} +${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 +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(); +}); + +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); + expectFocusedNodeToolchainBoundary(commands[0]); + expectTargetedNodeToolchainBoundary(commands[1]); + }); + + 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, + 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.workdir); + + expect(result).toEqual({ focusedOk: true, targetedCode: 0 }); + const privateHomes = fs + .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(nativeSandboxAvailable)( + "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"); + 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 = parentHome; + 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 expect(runBothWrappers(fixture.workdir)).resolves.toEqual({ + focusedOk: true, + targetedCode: 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 }); + } + }, + ); + + 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 = createShortSocketRoot(); + 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 }); + } + }, + ); +});