Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 69 additions & 0 deletions src/lib/actions/sandbox/sandbox-exec-output.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,69 @@
// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
// SPDX-License-Identifier: Apache-2.0

import { Buffer } from "node:buffer";
import { describe, expect, it } from "vitest";
import {
buildSandboxExecMarkedCommand,
extractSandboxExecCommandStdout,
SANDBOX_EXEC_STARTED_MARKER,
} from "./sandbox-exec-output";

describe("buildSandboxExecMarkedCommand", () => {
it("prints the sentinel before the command for ordinary scripts", () => {
const command = buildSandboxExecMarkedCommand("echo hi");
expect(command).toBe(`printf '%s\\n' '${SANDBOX_EXEC_STARTED_MARKER}'; echo hi`);
});

it("base64-encodes the hermes secret boundary script instead of inlining it", () => {
const script = "python3 validate-hermes-env-secret-boundary.py --check";
const command = buildSandboxExecMarkedCommand(script);

expect(command).toContain(`printf '%s\\n' '${SANDBOX_EXEC_STARTED_MARKER}'`);
expect(command).not.toContain(script);
const encoded = Buffer.from(script, "utf8").toString("base64");
expect(command).toContain(encoded);
});
});

describe("extractSandboxExecCommandStdout", () => {
it("returns null for empty output", () => {
expect(extractSandboxExecCommandStdout("")).toBeNull();
expect(extractSandboxExecCommandStdout(" \n ")).toBeNull();
});

it("returns null when the sentinel never appears", () => {
expect(extractSandboxExecCommandStdout("exec failed\n")).toBeNull();
});

it("extracts stdout after a raw, unframed sentinel", () => {
const output = `${SANDBOX_EXEC_STARTED_MARKER}\nNEMOCLAW_DCODE_PROBE=idle\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=idle");
});

it("strips the 'stdout: ' frame prefix", () => {
const output = `stdout: ${SANDBOX_EXEC_STARTED_MARKER}\nstdout: NEMOCLAW_DCODE_PROBE=idle\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=idle");
});

it("strips the '[stdout] ' frame prefix", () => {
const output = `[stdout] ${SANDBOX_EXEC_STARTED_MARKER}\n[stdout] NEMOCLAW_DCODE_PROBE=active\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=active");
});

it("uses the last sentinel line so a preamble cannot forge the parser boundary", () => {
const output = [
SANDBOX_EXEC_STARTED_MARKER,
"NEMOCLAW_DCODE_PROBE=idle",
SANDBOX_EXEC_STARTED_MARKER,
"NEMOCLAW_DCODE_PROBE=active",
].join("\n");

expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=active");
});

it("does not match a sentinel embedded in a preamble line as a substring", () => {
const output = `some login banner ${SANDBOX_EXEC_STARTED_MARKER} noise\n${SANDBOX_EXEC_STARTED_MARKER}\nNEMOCLAW_DCODE_PROBE=idle\n`;
expect(extractSandboxExecCommandStdout(output)).toBe("NEMOCLAW_DCODE_PROBE=idle");
});
});
24 changes: 16 additions & 8 deletions src/lib/actions/sandbox/sandbox-exec-output.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,19 +32,27 @@ function parseSandboxExecStdoutFrame(line: string): { text: string; framed: bool
* 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.
* Security boundary: `markedCommand` always prints the sentinel as the first
* thing the marked command does, so the authentic sentinel line is always the
* last one in the captured output. Take the LAST exact sentinel line rather
* than the first, so sandbox-controlled output that precedes the marked
* command (e.g. login-shell profile output) cannot plant a decoy sentinel and
* have its own forged follow-up lines misread as the real command's stdout.
* Remove this compatibility shim once OpenShell exposes a stable
* machine-readable exec output mode that preserves child stdout/stderr
* without human framing.
*/
export 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,
);
let exactMarkerIndex = -1;
for (let i = lines.length - 1; i >= 0; i--) {
if (lines[i].text.trim() === SANDBOX_EXEC_STARTED_MARKER) {
exactMarkerIndex = i;
break;
}
}
if (exactMarkerIndex >= 0) {
return lines
.slice(exactMarkerIndex + 1)
Expand Down
69 changes: 68 additions & 1 deletion src/lib/actions/sandbox/snapshot.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { SANDBOX_EXEC_STARTED_MARKER } from "./sandbox-exec-output";

type OpenshellCaptureResult = {
status: number | null;
Expand All @@ -23,7 +24,11 @@ type SandboxRecord = {
type DcodeProbeState = "active" | "idle" | "unverifiable" | "no-runtime";

function dcodeProbeOutput(state: DcodeProbeState, extra = ""): string {
return `NEMOCLAW_DCODE_PROBE=${state}\n${extra}`;
return `${SANDBOX_EXEC_STARTED_MARKER}\nNEMOCLAW_DCODE_PROBE=${state}\n${extra}`;
}

function framedDcodeProbeOutput(state: DcodeProbeState, framePrefix = "stdout: "): string {
return `${framePrefix}${SANDBOX_EXEC_STARTED_MARKER}\n${framePrefix}NEMOCLAW_DCODE_PROBE=${state}\n`;
}

function openshellResponses(
Expand Down Expand Up @@ -404,6 +409,68 @@ describe("runSandboxSnapshot", () => {
expect(consoleLog.mock.calls.flat().join("\n")).toContain("Snapshot v8 name=idle created");
});

it("allows dcode snapshot creation when OpenShell frames the probe stdout", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 0, output: framedDcodeProbeOutput("idle") });
const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {});
const manifest = {
timestamp: "2026-06-15T00:00:00.000Z",
backupPath: "/tmp/backup-alpha",
name: "framed-idle",
};
backupSandboxStateMock.mockReturnValue({
success: true,
backedUpDirs: ["workspace"],
backedUpFiles: ["config.toml"],
failedDirs: [],
failedFiles: [],
manifest,
});
findBackupMock.mockReturnValue({
match: { ...manifest, snapshotVersion: 9, name: "framed-idle" },
});
const { runSandboxSnapshot } = await import("./snapshot");

await runSandboxSnapshot("alpha", { kind: "create", name: "framed-idle" });

expect(backupSandboxStateMock).toHaveBeenCalledWith("alpha", { name: "framed-idle" });
expect(consoleLog.mock.calls.flat().join("\n")).toContain(
"Snapshot v9 name=framed-idle created",
);
});

it("refuses an active dcode task when OpenShell frames the probe stdout", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 0, output: framedDcodeProbeOutput("active", "[stdout] ") });
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const { runSandboxSnapshot } = await import("./snapshot");

await expect(runSandboxSnapshot("alpha", { kind: "create" })).rejects.toMatchObject({
exitCode: 1,
});

expect(backupSandboxStateMock).not.toHaveBeenCalled();
expect(consoleError.mock.calls.flat().join("\n")).toContain(
"Sandbox is actively running a dcode task. Please retry after the task completes.",
);
});

it("refuses an idle dcode snapshot when the exec wrapper reports a non-zero status", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 1, output: dcodeProbeOutput("idle") });
const consoleError = vi.spyOn(console, "error").mockImplementation(() => {});
const { runSandboxSnapshot } = await import("./snapshot");

await expect(runSandboxSnapshot("alpha", { kind: "create" })).rejects.toMatchObject({
exitCode: 1,
});

expect(backupSandboxStateMock).not.toHaveBeenCalled();
expect(consoleError.mock.calls.flat().join("\n")).toContain(
"Cannot verify whether sandbox 'alpha' is actively running a dcode task. Refusing to create snapshot.",
);
});

it("refuses registered dcode snapshots when raw status 1 has no idle sentinel", async () => {
getSandboxMock.mockReturnValue(dcodeSandboxEntry);
mockDcodeProbeResult({ status: 1, output: "exec failed" });
Expand Down
27 changes: 20 additions & 7 deletions src/lib/actions/sandbox/snapshot.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ import type { SandboxEntry } from "../../state/registry";
import * as registry from "../../state/registry";
import * as sandboxState from "../../state/sandbox";
import { cleanupShieldsDestroyArtifacts, removeSandboxRegistryEntry } from "./destroy";
import {
buildSandboxExecMarkedCommand,
extractSandboxExecCommandStdout,
} from "./sandbox-exec-output";
import {
probeGatewayRunning,
selectSandboxGatewayIfRegistered,
Expand Down Expand Up @@ -426,23 +430,32 @@ function isSnapshotCreationAllowedByDcodeActivity(sandboxName: string): boolean
// when dcode exposes a wrapper-owned idle/active lock or equivalent snapshot
// quiescence signal and the backup path checks that source directly.
const probe = captureOpenshell(
["sandbox", "exec", "--name", sandboxName, "--", "sh", "-lc", DCODE_BUSY_PROBE_SCRIPT],
[
"sandbox",
"exec",
"--name",
sandboxName,
"--",
"sh",
"-lc",
buildSandboxExecMarkedCommand(DCODE_BUSY_PROBE_SCRIPT),
],
{
ignoreError: true,
includeStderr: true,
timeout: OPENSHELL_PROBE_TIMEOUT_MS,
},
);
const probeState = parseDcodeProbeState(probe.output || "");
const probeSucceeded = probe.status === 0 && !probe.error && !probe.signal;
const probeCompleted = probe.status === 0 && !probe.error && !probe.signal;
const commandStdout = probeCompleted ? extractSandboxExecCommandStdout(probe.output || "") : null;
const probeState = commandStdout === null ? null : parseDcodeProbeState(commandStdout);
if (
probeSucceeded &&
(probeState === DCODE_PROBE_STATE.idleDcodeRuntime ||
probeState === DCODE_PROBE_STATE.noDcodeRuntime)
probeState === DCODE_PROBE_STATE.idleDcodeRuntime ||
probeState === DCODE_PROBE_STATE.noDcodeRuntime
) {
return true;
}
if (probeSucceeded && probeState === DCODE_PROBE_STATE.active) {
if (probeState === DCODE_PROBE_STATE.active) {
console.error(
" Sandbox is actively running a dcode task. Please retry after the task completes.",
);
Expand Down
Loading