diff --git a/src/lib/actions/sandbox/process-recovery.ts b/src/lib/actions/sandbox/process-recovery.ts index 2693bd0408b..5546070d88d 100644 --- a/src/lib/actions/sandbox/process-recovery.ts +++ b/src/lib/actions/sandbox/process-recovery.ts @@ -1,7 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { Buffer } from "node:buffer"; import { spawnSync } from "node:child_process"; +import { dockerSpawnSync } from "../../adapters/docker"; import { captureOpenshell, captureOpenshellForStatus, @@ -61,6 +63,57 @@ export type SandboxForwardHealth = boolean | "occupied" | null; const SANDBOX_EXEC_STARTED_MARKER = "__NEMOCLAW_SANDBOX_EXEC_STARTED__"; +function buildSandboxExecMarkedCommand(command: string): string { + if (!command.includes("validate-hermes-env-secret-boundary.py")) { + return `printf '%s\n' '${SANDBOX_EXEC_STARTED_MARKER}'; ${command}`; + } + const encodedCommand = Buffer.from(command, "utf8").toString("base64"); + return [ + `printf '%s\\n' '${SANDBOX_EXEC_STARTED_MARKER}'`, + "command -v base64 >/dev/null 2>&1 || { echo NEMOCLAW_BASE64_MISSING >&2; exit 127; }", + `printf '%s' '${encodedCommand}' | base64 -d | sh`, + ].join("; "); +} + +function parseSandboxExecStdoutFrame(line: string): { text: string; framed: boolean } { + const trimmed = line.trimStart(); + const stdoutPrefix = trimmed.match(/^(?:\[stdout\]|stdout:)\s*/i); + if (!stdoutPrefix) return { text: line, framed: false }; + return { text: trimmed.slice(stdoutPrefix[0].length), framed: true }; +} + +/** + * Extract child-command stdout from `openshell sandbox exec` output after the + * sentinel printed by `markedCommand`. Some OpenShell versions frame child + * stdout for humans, e.g. `stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__`, while + * older versions pass raw stdout through unchanged. Normalize only recognized + * stdout frame prefixes at this transport boundary so recovery, status, and + * Hermes boundary callers keep consuming plain command stdout. + * + * Security boundary: the sentinel must occupy its own stdout line after optional + * frame-prefix stripping. A preamble that merely contains the sentinel string is + * rejected so sandbox output cannot move the parser boundary forward. Remove + * this compatibility shim once OpenShell exposes a stable machine-readable exec + * output mode that preserves child stdout/stderr without human framing. + */ +function extractSandboxExecCommandStdout(output: string): string | null { + const stdout = output.trim(); + if (!stdout) return null; + const lines = stdout.split(/\r?\n/).map(parseSandboxExecStdoutFrame); + const exactMarkerIndex = lines.findIndex( + (line) => line.text.trim() === SANDBOX_EXEC_STARTED_MARKER, + ); + if (exactMarkerIndex >= 0) { + return lines + .slice(exactMarkerIndex + 1) + .map((line) => line.text) + .join("\n") + .trim(); + } + + return null; +} + function isValidPort(value: unknown): value is number { return typeof value === "number" && Number.isInteger(value) && value >= 1 && value <= 65535; } @@ -133,12 +186,66 @@ export function executeSandboxCommand( } } +function parseSandboxCommandResult( + result: ReturnType, +): SandboxCommandResult | null { + if (result.error) return null; + const stdout = typeof result.stdout === "string" ? result.stdout : String(result.stdout || ""); + const stderr = typeof result.stderr === "string" ? result.stderr : String(result.stderr || ""); + const commandStdout = extractSandboxExecCommandStdout(stdout); + if (commandStdout === null) return null; + return { + status: result.status ?? 1, + stdout: commandStdout, + stderr: stderr.trim(), + }; +} + +function findLocalDockerSandboxContainer(sandboxName: string): string | null { + const expectedName = `openshell-${sandboxName}`; + try { + const result = dockerSpawnSync(["ps", "--format", "{{.ID}}\t{{.Names}}"], { + encoding: "utf-8", + stdio: ["ignore", "pipe", "pipe"], + timeout: 5000, + }); + if (result.error || result.status !== 0) return null; + for (const line of String(result.stdout || "").split(/\r?\n/)) { + const [id = "", names = ""] = line.split("\t"); + const containerNames = names.split(",").map((name) => name.trim()); + if (id && containerNames.includes(expectedName)) return id; + } + return null; + } catch { + return null; + } +} + +function executeLocalDockerSandboxCommand( + sandboxName: string, + markedCommand: string, + timeout: number, +): SandboxCommandResult | null { + const containerId = findLocalDockerSandboxContainer(sandboxName); + if (!containerId) return null; + try { + const result = dockerSpawnSync(["exec", "-u", "root", containerId, "sh", "-c", markedCommand], { + encoding: "utf-8", + stdio: ["ignore", "pipe", "pipe"], + timeout, + }); + return parseSandboxCommandResult(result); + } catch { + return null; + } +} + export function executeSandboxExecCommand( sandboxName: string, command: string, timeout = 15000, ): SandboxCommandResult | null { - const markedCommand = `printf '%s\n' '${SANDBOX_EXEC_STARTED_MARKER}'; ${command}`; + const markedCommand = buildSandboxExecMarkedCommand(command); const timeoutOverride = Number(process.env.NEMOCLAW_SANDBOX_EXEC_TIMEOUT_MS || ""); const effectiveTimeout = Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : timeout; @@ -154,19 +261,12 @@ export function executeSandboxExecCommand( timeout: effectiveTimeout, }, ); - if (result.error) return null; - const stdout = (result.stdout || "").trim(); - const stdoutLines = stdout.split(/\r?\n/); - const markerIndex = stdoutLines.indexOf(SANDBOX_EXEC_STARTED_MARKER); - if (markerIndex === -1) return null; - const commandStdoutLines = stdoutLines.slice(markerIndex + 1); - return { - status: result.status ?? 1, - stdout: commandStdoutLines.join("\n").trim(), - stderr: (result.stderr || "").trim(), - }; + return ( + parseSandboxCommandResult(result) ?? + executeLocalDockerSandboxCommand(sandboxName, markedCommand, effectiveTimeout) + ); } catch { - return null; + return executeLocalDockerSandboxCommand(sandboxName, markedCommand, effectiveTimeout); } } @@ -174,20 +274,17 @@ async function executeSandboxExecCommandForStatus( sandboxName: string, command: string, ): Promise { - const markedCommand = `printf '%s\n' '${SANDBOX_EXEC_STARTED_MARKER}'; ${command}`; + const markedCommand = buildSandboxExecMarkedCommand(command); const result = await captureOpenshellForStatus( ["sandbox", "exec", "--name", sandboxName, "--", "sh", "-c", markedCommand], { ignoreError: true }, ); if (isCommandTimeout(result) || result.error) return null; - const stdout = (result.output || "").trim(); - const stdoutLines = stdout.split(/\r?\n/); - const markerIndex = stdoutLines.indexOf(SANDBOX_EXEC_STARTED_MARKER); - if (markerIndex === -1) return null; - const commandStdoutLines = stdoutLines.slice(markerIndex + 1); + const commandStdout = extractSandboxExecCommandStdout(result.output || ""); + if (commandStdout === null) return null; return { status: result.status ?? 1, - stdout: commandStdoutLines.join("\n").trim(), + stdout: commandStdout, stderr: "", }; } diff --git a/test/process-recovery.test.ts b/test/process-recovery.test.ts index b79d4b90e4b..6ef8b60a614 100644 --- a/test/process-recovery.test.ts +++ b/test/process-recovery.test.ts @@ -1,6 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import { Buffer } from "node:buffer"; import fs from "node:fs"; import { createRequire } from "node:module"; import os from "node:os"; @@ -11,6 +12,7 @@ import { checkAndRecoverSandboxProcesses, classifyForwardHealthWithReachability, classifySandboxForwardHealth, + executeSandboxExecCommand, resolveSandboxDashboardPort, type SandboxForwardListEntry, } from "../dist/lib/actions/sandbox/process-recovery.js"; @@ -21,6 +23,16 @@ afterEach(() => { vi.restoreAllMocks(); }); +function decodeSandboxExecShellPayload(payload: string): string { + const match = payload.match(/printf '%s' '([A-Za-z0-9+\/=]+)' \| base64 -d \| sh/); + return match ? Buffer.from(match[1], "base64").toString("utf8") : payload; +} + +function getSandboxExecShellCommand(rawArgs: unknown): string { + const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; + return decodeSandboxExecShellPayload(String(args.at(-1) ?? "")); +} + function withFakeOpenshellBinary(fn: () => T): T { const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-fake-openshell-")); const bin = path.join(dir, "openshell"); @@ -173,6 +185,107 @@ describe("classifyForwardHealthWithReachability", () => { }); }); +describe("executeSandboxExecCommand", () => { + it("parses stdout-framed root exec output after the startup marker", () => { + const childProcess = requireDist("node:child_process"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: [ + "OpenShell sandbox exec output:", + "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__", + "stdout: SECRET_BOUNDARY_OK", + ].join("\n"), + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), + ); + + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + }); + + it("rejects a non-frame preamble that contains the startup marker", () => { + const childProcess = requireDist("node:child_process"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: [ + "operator preamble mentions __NEMOCLAW_SANDBOX_EXEC_STARTED__ before child stdout", + "stdout: RUNNING", + ].join("\n"), + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo RUNNING"), + ); + + expect(result).toBeNull(); + }); + + it("passes a newline-free Hermes validator payload to OpenShell", () => { + const childProcess = requireDist("node:child_process"); + const spawn = vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand( + "hermes-box", + "python3 /usr/local/lib/nemoclaw/validate-hermes-env-secret-boundary.py env-file /sandbox/.hermes/.env\necho SECRET_BOUNDARY_OK", + ), + ); + + const args = spawn.mock.calls[0]?.[1] as string[]; + const shellPayload = args.at(-1) ?? ""; + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + expect(shellPayload.includes("\n")).toBe(false); + expect(shellPayload.includes("\r")).toBe(false); + expect(shellPayload).toContain("printf '%s\\n' '__NEMOCLAW_SANDBOX_EXEC_STARTED__'"); + expect(shellPayload).toContain("base64 -d | sh"); + }); + + it("falls back to local Docker root exec when OpenShell exec output has no marker", () => { + const childProcess = requireDist("node:child_process"); + const dockerExec = requireDist("../dist/lib/adapters/docker/exec.js"); + vi.spyOn(childProcess, "spawnSync").mockReturnValue({ + status: 0, + stdout: "OpenShell transport preamble\n", + stderr: "", + } as never); + const dockerSpawnSync = vi + .spyOn(dockerExec, "dockerSpawnSync") + .mockReturnValueOnce({ + status: 0, + stdout: "abc123\topenshell-hermes-box\n", + stderr: "", + } as never) + .mockReturnValueOnce({ + status: 0, + stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_OK\n", + stderr: "", + } as never); + + const result = withFakeOpenshellBinary(() => + executeSandboxExecCommand("hermes-box", "echo SECRET_BOUNDARY_OK"), + ); + + expect(result).toEqual({ status: 0, stdout: "SECRET_BOUNDARY_OK", stderr: "" }); + expect(dockerSpawnSync.mock.calls[0]?.[0]).toEqual(["ps", "--format", "{{.ID}}\t{{.Names}}"]); + expect(dockerSpawnSync.mock.calls[1]?.[0]).toEqual([ + "exec", + "-u", + "root", + "abc123", + "sh", + "-c", + expect.stringContaining("echo SECRET_BOUNDARY_OK"), + ]); + }); +}); + describe("checkAndRecoverSandboxProcesses", () => { it("scopes forward stop to the target sandbox when restarting a dead forward", () => { const openshellRuntime = requireDist("../dist/lib/adapters/openshell/runtime.js"); @@ -188,8 +301,7 @@ beta 127.0.0.1 18789 12345 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -263,8 +375,7 @@ beta 127.0.0.1 18789 12345 running`; try { vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { healthProbeCalls += 1; const status = healthProbeCalls >= 3 ? "RUNNING" : "STOPPED"; @@ -333,8 +444,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -424,8 +534,7 @@ sibling-box 127.0.0.1 8642 99999 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -486,8 +595,7 @@ hermes-box 127.0.0.1 18789 12345 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -544,8 +652,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { return { status: 0, @@ -612,12 +719,11 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nRUNNING\n", + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: RUNNING\n", stderr: "", } as never; } @@ -625,7 +731,7 @@ hermes-box 127.0.0.1 8642 12346 running`; secretBoundaryCalls += 1; return { status: 1, - stdout: "__NEMOCLAW_SANDBOX_EXEC_STARTED__\nSECRET_BOUNDARY_REFUSED\n", + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: SECRET_BOUNDARY_REFUSED\n", stderr: "[SECURITY] Refusing Hermes startup because /sandbox/.hermes/.env contains raw secret-shaped values\n[SECURITY] TELEGRAM_BOT_TOKEN (line 3)", } as never; @@ -694,8 +800,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -746,6 +851,74 @@ hermes-box 127.0.0.1 8642 12346 running`; ); }); + it("falls through when the Hermes secret-boundary check parses stdout-framed root exec markers", () => { + const openshellRuntime = requireDist("../dist/lib/adapters/openshell/runtime.js"); + const agentRuntime = requireDist("../dist/lib/agent/runtime.js"); + const registry = requireDist("../dist/lib/state/registry.js"); + const forwardHealth = requireDist("../dist/lib/actions/sandbox/forward-health.js"); + const childProcess = requireDist("node:child_process"); + let secretBoundaryCalls = 0; + + const execResponses: Array<[string, () => never]> = [ + [ + "HTTP_CODE=$(curl", + () => + ({ + status: 0, + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: RUNNING\n", + stderr: "", + }) as never, + ], + [ + "validate-hermes-env-secret-boundary.py", + () => { + secretBoundaryCalls += 1; + return { + status: 0, + stdout: "stdout: __NEMOCLAW_SANDBOX_EXEC_STARTED__\nstdout: SECRET_BOUNDARY_OK\n", + stderr: "", + } as never; + }, + ], + ]; + vi.spyOn(childProcess, "spawnSync").mockImplementation( + (_command: unknown, rawArgs: unknown) => { + const shellCommand = getSandboxExecShellCommand(rawArgs); + return ( + execResponses.find(([needle]) => shellCommand.includes(needle))?.[1] ?? + (() => ({ status: 0, stdout: "", stderr: "" }) as never) + )(); + }, + ); + vi.spyOn(agentRuntime, "getSessionAgent").mockReturnValue({ + name: "hermes", + forwardPort: 8642, + displayName: "Hermes Agent", + }); + vi.spyOn(registry, "getSandbox").mockReturnValue({ + name: "hermes-box", + agent: "hermes", + dashboardPort: 18789, + }); + vi.spyOn(forwardHealth, "isLocalForwardReachable").mockReturnValue(true); + vi.spyOn(openshellRuntime, "captureOpenshell").mockReturnValue({ + status: 0, + output: `SANDBOX BIND PORT PID STATUS\nhermes-box 127.0.0.1 18789 12345 running`, + }); + vi.spyOn(openshellRuntime, "runOpenshell").mockReturnValue({ status: 0 } as never); + + const result = withFakeOpenshellBinary(() => + checkAndRecoverSandboxProcesses("hermes-box", { quiet: true }), + ); + expect(result).toEqual({ + checked: true, + wasRunning: true, + recovered: false, + forwardRecovered: false, + }); + expect(secretBoundaryCalls).toBe(1); + }); + it("falls through to the forward-refresh path when the Hermes secret-boundary check passes", () => { const openshellRuntime = requireDist("../dist/lib/adapters/openshell/runtime.js"); const agentRuntime = requireDist("../dist/lib/agent/runtime.js"); @@ -756,8 +929,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -815,8 +987,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -877,8 +1048,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("validate-hermes-env-secret-boundary.py")) { secretBoundaryCalls += 1; } @@ -917,8 +1087,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0, @@ -984,8 +1153,7 @@ hermes-box 127.0.0.1 8642 12346 running`; vi.spyOn(childProcess, "spawnSync").mockImplementation( (_command: unknown, rawArgs: unknown) => { - const args = Array.isArray(rawArgs) ? rawArgs.map(String) : []; - const shellCommand = String(args.at(-1) ?? ""); + const shellCommand = getSandboxExecShellCommand(rawArgs); if (shellCommand.includes("HTTP_CODE=$(curl")) { return { status: 0,