diff --git a/docs/reference/commands.mdx b/docs/reference/commands.mdx index b0557a3a66b..3a454b15e9a 100644 --- a/docs/reference/commands.mdx +++ b/docs/reference/commands.mdx @@ -2556,7 +2556,7 @@ Before an OpenShell upgrade, the installer prepares the current release CLI and Strict mode requires every registered sandbox to produce a fresh backup and aborts before gateway changes if any sandbox is skipped or fails. When strict mode reports a skipped sandbox, start that sandbox or its container and rerun the installer or `$$nemoclaw backup-all`. -A running sandbox whose in-sandbox SSH endpoint does not answer fails its backup and aborts the run. +A running sandbox whose OpenShell sandbox exec endpoint does not answer fails its backup and aborts the run. For a standalone `$$nemoclaw backup-all` run, set `NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1` exactly to skip such sandboxes instead of failing. Other values such as `true`, `yes`, or `0` are not accepted. This variable does not weaken the installer's strict pre-upgrade requirement. @@ -3568,7 +3568,7 @@ The following flags change defaults for commands that manage existing sandboxes. | `NEMOCLAW_DISABLE_SUPERVISOR_RELAUNCH` | `1` to enable | Skips the automatic trusted container recreation during `$$nemoclaw recover` when two managed scans find no supervisor while PID 1 remains stable. Use only as a troubleshooting escape hatch; recovery then falls back to the rebuild or re-onboard guidance. | | `NEMOCLAW_SHIELDS_ACCEPT_LEGACY_BASELINE` | `1` to opt in | Allows advanced immutable-config verification to trust the current on-disk bytes for older or partial content baselines. Use only after you have rebuilt or manually inspected the sandbox state and accepted that the baseline is operator-approved. | | `NEMOCLAW_SHIELDS_SETTLE_MS` | milliseconds (default `750`, clamped to `0` to `10000`) | Settle window NemoClaw waits after re-applying a config lockdown (during shields auto-restore and `$$nemoclaw shields up` drift remediation) before re-confirming the lock still holds. Detects when an in-sandbox reconciler changes config file permissions after lockdown and re-applies the lock; if NemoClaw cannot re-confirm the lock within the retry budget, shields stay down. This narrows the window in which a reconciler can revert permissions rather than eliminating it. The best-effort `chattr +i` immutable bit remains the only fully durable lock. Raise it on hosts where the gateway settles slowly. | -| `NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP` | Exactly `1` to opt in (`true`, `yes`, `0` are not accepted) | Applies to standalone `$$nemoclaw backup-all` runs. Skips running sandboxes whose in-sandbox SSH endpoint does not answer. It does not relax the installer's strict pre-upgrade backup, which still aborts if any registered sandbox is skipped or fails. Any uncommitted state since the last successful backup is not included in the skipped backup. | +| `NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP` | Exactly `1` to opt in (`true`, `yes`, `0` are not accepted) | Applies to standalone `$$nemoclaw backup-all` runs. Skips running sandboxes whose OpenShell sandbox exec endpoint does not answer. It does not relax the installer's strict pre-upgrade backup, which still aborts if any registered sandbox is skipped or fails. Any uncommitted state since the last successful backup is not included in the skipped backup. | | `NEMOCLAW_UNINSTALL_DESTROY_USER_DATA` | `1` to opt in | Acknowledges data loss during `$$nemoclaw uninstall` and removes the otherwise-preserved entries (`rebuild-backups/`, `backups/`, `sandboxes.json`) under `~/.nemoclaw/`. Equivalent to passing the `--destroy-user-data` flag; the global `Proceed?` confirmation still applies unless `--yes` is also passed. | diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index c80751432e3..eae81ab3217 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -58,9 +58,10 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/state/openclaw-config-restore-input.ts", "ssh-command", 1], ["src/lib/state/openclaw-plugin-restore.ts", "ssh-command", 2], ["src/lib/state/openclaw-plugin-restore.ts", "ssh-temp-config", 1], + ["src/lib/state/sandbox.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/state/sandbox.ts", "openshell-ssh-config", 1], - ["src/lib/state/sandbox.ts", "ssh-command", 8], - ["src/lib/state/sandbox.ts", "ssh-temp-config", 2], + ["src/lib/state/sandbox.ts", "ssh-command", 4], + ["src/lib/state/sandbox.ts", "ssh-temp-config", 1], ["src/lib/state/state-file-restore.ts", "ssh-command", 1], ["src/lib/state/user-managed-files-probe.ts", "grpc-cli-read-only-fallback", 1], ["src/lib/tunnel/sandbox-gateway-stop.ts", "docker-exec-command", 2], diff --git a/src/lib/actions/maintenance.test.ts b/src/lib/actions/maintenance.test.ts index 7d81b71cbba..2813b6fb1ce 100644 --- a/src/lib/actions/maintenance.test.ts +++ b/src/lib/actions/maintenance.test.ts @@ -494,7 +494,7 @@ describe("backupAll", () => { }); it("re-throws non-orphan-manifest errors so the installer aborts the upgrade", async () => { - // Real failures (disk full, SSH timeout, permission denied, programming + // Real failures (disk full, exec timeout, permission denied, programming // bugs) must propagate. Counting them as 'skipped' and returning exit 0 // would let the installer march forward with a corrupt or absent backup // and silently lose state on restore. @@ -562,7 +562,7 @@ describe("backupAll", () => { await expect(backupAll()).rejects.toThrow(/binary/); }); - it("skips a running but SSH-unreachable sandbox when NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1", async () => { + it("skips a running sandbox with unreachable exec when the waiver is enabled", async () => { mocks.listSandboxes.mockReturnValue({ sandboxes: [{ name: "sb-bad" }, { name: "sb-good" }], defaultSandbox: null, @@ -664,6 +664,7 @@ describe("backupAll", () => { await expect(backupAll()).rejects.toThrow("exit:1"); const errorOutput = errorSpy.mock.calls.map((c) => c[0]).join("\n"); + expect(errorOutput).toContain("OpenShell sandbox exec endpoint"); expect(errorOutput.includes("NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1")).toBe( expectSkipGuidance, ); diff --git a/src/lib/actions/maintenance.ts b/src/lib/actions/maintenance.ts index e1d8446022e..fc629713b4b 100644 --- a/src/lib/actions/maintenance.ts +++ b/src/lib/actions/maintenance.ts @@ -84,7 +84,7 @@ export async function backupAll(): Promise { try { result = startedForBackup ? await backupStartedSandboxState(sb.name) - : sandboxState.backupSandboxState(sb.name); + : await sandboxState.backupSandboxState(sb.name); } catch (err: unknown) { // Source-of-truth review (#5734 / #5819): // @@ -153,7 +153,7 @@ export async function backupAll(): Promise { if (result.unreachable) { if (skipUnreachable) { console.log( - ` ${YW}⚠${R} Skipped '${sb.name}' (running but SSH-unreachable; NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 set). Any uncommitted state since the last successful backup will be lost.`, + ` ${YW}⚠${R} Skipped '${sb.name}' (sandbox exec unreachable; NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 set). Any uncommitted state since the last successful backup will be lost.`, ); skipped++; continue; @@ -177,7 +177,7 @@ export async function backupAll(): Promise { if (unreachableRunning > 0) { console.error(""); console.error( - ` ${unreachableRunning} running sandbox(es) could not be backed up because their in-sandbox SSH endpoint did not answer.`, + ` ${unreachableRunning} running sandbox(es) could not be backed up because their OpenShell sandbox exec endpoint did not answer.`, ); if (requireAll) { console.error( diff --git a/src/lib/actions/sandbox/rebuild-backup-phase.test.ts b/src/lib/actions/sandbox/rebuild-backup-phase.test.ts index 5f33475e81a..14f94200251 100644 --- a/src/lib/actions/sandbox/rebuild-backup-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-backup-phase.test.ts @@ -65,8 +65,8 @@ describe("rebuild web-search policy normalization", () => { ).toEqual(["npm"]); }); - it("keeps a finalized custom-only built-in selection empty instead of resetting it", () => { - const result = runRebuildBackupPhase({ + it("keeps a finalized custom-only built-in selection empty instead of resetting it", async () => { + const result = await runRebuildBackupPhase({ sandboxName: "alpha", sandboxEntry: { name: "alpha", @@ -94,10 +94,10 @@ describe("rebuild web-search policy normalization", () => { expect(result?.backupWasForceSkipped).toBe(false); }); - it("records when --force skips a total backup failure", () => { + it("records when --force skips a total backup failure", async () => { vi.spyOn(console, "warn").mockImplementation(() => undefined); vi.spyOn(console, "log").mockImplementation(() => undefined); - vi.spyOn(sandboxState, "backupSandboxState").mockReturnValue({ + vi.spyOn(sandboxState, "backupSandboxState").mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -105,7 +105,7 @@ describe("rebuild web-search policy normalization", () => { failedFiles: ["openclaw.json"], }); - const result = runRebuildBackupPhase({ + const result = await runRebuildBackupPhase({ sandboxName: "alpha", sandboxEntry: { name: "alpha", agent: "openclaw", policies: [] }, staleRecovery: false, @@ -227,12 +227,12 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { } as RebuildBackupPhaseInput; } - it("blocks a live custom image with missing registry provenance before backup", () => { + it("blocks a live custom image with missing registry provenance before backup", async () => { const backupStateForRebuild = vi.fn(); const input = customOpenClawInput(); const errorLog = vi.spyOn(console, "error").mockImplementation(() => undefined); - expect(() => runRebuildBackupPhase(input, backupStateForRebuild)).toThrow( + await expect(runRebuildBackupPhase(input, backupStateForRebuild)).rejects.toThrow( "Custom-image OpenClaw plugin provenance is unavailable.", ); @@ -245,17 +245,17 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { errorLog.mockRestore(); }); - it("uses a marked prepared manifest when registry provenance is missing", () => { + it("uses a marked prepared manifest when registry provenance is missing", async () => { const backupStateForRebuild = vi.fn(); const input = customOpenClawInput({ preparedRecoveryManifest: completeMarkedManifest }); - const result = runRebuildBackupPhase(input, backupStateForRebuild); + const result = await runRebuildBackupPhase(input, backupStateForRebuild); expect(result?.backupManifest).toBe(completeMarkedManifest); expect(backupStateForRebuild).not.toHaveBeenCalled(); }); - it("blocks an unmarked legacy prepared manifest before deletion", () => { + it("blocks an unmarked legacy prepared manifest before deletion", async () => { const backupStateForRebuild = vi.fn(); const input = customOpenClawInput({ preparedRecoveryManifest: { @@ -266,15 +266,15 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { }, }); - expect(() => runRebuildBackupPhase(input, backupStateForRebuild)).toThrow( + await expect(runRebuildBackupPhase(input, backupStateForRebuild)).rejects.toThrow( "Custom-image OpenClaw plugin provenance is unavailable.", ); expect(backupStateForRebuild).not.toHaveBeenCalled(); }); - it("revalidates a newly generated backup manifest before deletion", () => { - const backupStateForRebuild = vi.fn(() => ({ + it("revalidates a newly generated backup manifest before deletion", async () => { + const backupStateForRebuild = vi.fn(async () => ({ agentType: "openclaw", dir: "/sandbox/.openclaw", backupPath: "/tmp/incomplete-custom-openclaw-backup", @@ -289,7 +289,7 @@ describe("custom OpenClaw plugin provenance rebuild guard (#6108)", () => { }, }); - expect(() => runRebuildBackupPhase(input, backupStateForRebuild as never)).toThrow( + await expect(runRebuildBackupPhase(input, backupStateForRebuild as never)).rejects.toThrow( "Custom-image OpenClaw plugin provenance is unavailable.", ); diff --git a/src/lib/actions/sandbox/rebuild-backup-phase.ts b/src/lib/actions/sandbox/rebuild-backup-phase.ts index 8bb24655873..d3aca1d68bd 100644 --- a/src/lib/actions/sandbox/rebuild-backup-phase.ts +++ b/src/lib/actions/sandbox/rebuild-backup-phase.ts @@ -20,7 +20,7 @@ import type { RebuildBail, RebuildLog } from "./rebuild-credential-preflight"; import { backupSandboxStateForRebuild, type RebuildSandboxEntry } from "./rebuild-flow-helpers"; export type RebuildBackupManifest = Exclude< - ReturnType, + Awaited>, undefined >; @@ -144,10 +144,10 @@ export function normalizeRebuildTargetPolicyPresets( ); } -export function runRebuildBackupPhase( +export async function runRebuildBackupPhase( input: RebuildBackupPhaseInput, backupStateForRebuild: typeof backupSandboxStateForRebuild = backupSandboxStateForRebuild, -): RebuildBackupPhaseResult | null { +): Promise { const customOpenClaw = Boolean(input.sandboxEntry.fromDockerfile) && (!input.sandboxEntry.agent || input.sandboxEntry.agent === "openclaw"); @@ -174,7 +174,7 @@ export function runRebuildBackupPhase( } const backupManifest = preparedRecoveryManifest ?? - backupStateForRebuild( + (await backupStateForRebuild( input.sandboxName, input.sandboxEntry, input.staleRecovery, @@ -182,7 +182,7 @@ export function runRebuildBackupPhase( input.relockShieldsIfNeeded, input.bail, { force: input.force }, - ); + )); if (backupManifest === undefined) return null; if ( backupManifest && diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts index 5e39bc84ffa..77470656d66 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.test.ts @@ -16,7 +16,7 @@ import { warnUnpreservedUserManagedFiles, } from "./rebuild-flow-helpers"; -function makeBackupResult(): ReturnType { +function makeBackupResult(): Awaited> { return { success: true, backedUpDirs: [".state"], @@ -38,7 +38,7 @@ function makeBackupResult(): ReturnType blueprintDigest: null, policyPresets: [], customPolicies: [], - } as ReturnType["manifest"], + } as Awaited>["manifest"], }; } @@ -227,8 +227,8 @@ describe("backupSandboxStateForRebuild with --force", () => { vi.restoreAllMocks(); }); - it("returns null (skip) when backup fails completely and force is set", () => { - backupSpy.mockReturnValue({ + it("returns null (skip) when backup fails completely and force is set", async () => { + backupSpy.mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -236,7 +236,7 @@ describe("backupSandboxStateForRebuild with --force", () => { failedFiles: ["config.toml"], manifest: null, }); - const result = backupSandboxStateForRebuild( + const result = await backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), false, @@ -251,8 +251,8 @@ describe("backupSandboxStateForRebuild with --force", () => { expect(warnLines.some((line: string) => line.includes("--force was specified"))).toBe(true); }); - it("aborts with hint when backup fails completely without force", () => { - backupSpy.mockReturnValue({ + it("aborts with hint when backup fails completely without force", async () => { + backupSpy.mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -260,7 +260,7 @@ describe("backupSandboxStateForRebuild with --force", () => { failedFiles: [], manifest: null, }); - expect(() => + await expect( backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), @@ -269,14 +269,14 @@ describe("backupSandboxStateForRebuild with --force", () => { () => true, makeBail(), ), - ).toThrow("bail: Failed to back up sandbox state."); + ).rejects.toThrow("bail: Failed to back up sandbox state."); const errorLines = errorSpy.mock.calls.map((args: unknown[]) => String(args[0])); expect(errorLines.some((line: string) => line.includes("rebuild --force"))).toBe(true); }); - it("aborts without force even when force option is explicitly false", () => { - backupSpy.mockReturnValue({ + it("aborts without force even when force option is explicitly false", async () => { + backupSpy.mockResolvedValue({ success: false, backedUpDirs: [], backedUpFiles: [], @@ -284,7 +284,7 @@ describe("backupSandboxStateForRebuild with --force", () => { failedFiles: [], manifest: null, }); - expect(() => + await expect( backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), @@ -294,7 +294,7 @@ describe("backupSandboxStateForRebuild with --force", () => { makeBail(), { force: false }, ), - ).toThrow("bail: Failed to back up sandbox state."); + ).rejects.toThrow("bail: Failed to back up sandbox state."); }); }); @@ -310,7 +310,7 @@ describe("warnUnpreservedUserManagedFiles", () => { logSpy = vi.spyOn(console, "log").mockImplementation(() => undefined); errorSpy = vi.spyOn(console, "error").mockImplementation(() => undefined); - backupSpy = vi.spyOn(sandboxState, "backupSandboxState").mockReturnValue(makeBackupResult()); + backupSpy = vi.spyOn(sandboxState, "backupSandboxState").mockResolvedValue(makeBackupResult()); probeSpy = vi.spyOn(userManagedFilesProbe, "probeUserManagedFiles").mockResolvedValue({ declared: [], existing: [], @@ -365,8 +365,8 @@ describe("warnUnpreservedUserManagedFiles", () => { expect(warnLines.some((line: string) => line.includes("will not be preserved"))).toBe(false); }); - it("skips probe when staleRecovery short-circuits the backup", () => { - const result = backupSandboxStateForRebuild( + it("skips probe when staleRecovery short-circuits the backup", async () => { + const result = await backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), true, @@ -380,8 +380,8 @@ describe("warnUnpreservedUserManagedFiles", () => { expect(probeSpy).not.toHaveBeenCalled(); }); - it("does not probe during backup before managed MCP adapter entries are scrubbed", () => { - const result = backupSandboxStateForRebuild( + it("does not probe during backup before managed MCP adapter entries are scrubbed", async () => { + const result = await backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), false, @@ -414,8 +414,8 @@ describe("warnUnpreservedUserManagedFiles", () => { expect(errorSpy).not.toHaveBeenCalled(); }); - it("surfaces the backup failure reason before aborting", () => { - backupSpy.mockReturnValue({ + it("surfaces the backup failure reason before aborting", async () => { + backupSpy.mockResolvedValue({ ...makeBackupResult(), success: false, backedUpDirs: [], @@ -425,7 +425,7 @@ describe("warnUnpreservedUserManagedFiles", () => { error: "Pre-backup audit rejected an unsafe symlink", }); - expect(() => + await expect( backupSandboxStateForRebuild( "alpha", makeSandboxEntry(), @@ -434,7 +434,7 @@ describe("warnUnpreservedUserManagedFiles", () => { () => true, makeBail(), ), - ).toThrow("bail: Failed to back up sandbox state."); + ).rejects.toThrow("bail: Failed to back up sandbox state."); const errorLines = errorSpy.mock.calls.map((args: unknown[]) => String(args[0])); expect(errorLines).toContain(" Reason: Pre-backup audit rejected an unsafe symlink"); diff --git a/src/lib/actions/sandbox/rebuild-flow-helpers.ts b/src/lib/actions/sandbox/rebuild-flow-helpers.ts index d6a5be57b43..ed12a2821d5 100644 --- a/src/lib/actions/sandbox/rebuild-flow-helpers.ts +++ b/src/lib/actions/sandbox/rebuild-flow-helpers.ts @@ -258,7 +258,7 @@ export function pinRebuildAgentBaseImageForRecreate( }; } -export function backupSandboxStateForRebuild( +export async function backupSandboxStateForRebuild( sandboxName: string, sb: RebuildSandboxEntry, staleRecovery: boolean, @@ -266,12 +266,12 @@ export function backupSandboxStateForRebuild( relockShieldsIfNeeded: (sandboxStillExists: boolean) => boolean, bail: (msg: string, code?: number) => never, options?: { force?: boolean }, -): sandboxState.RebuildManifest | null | undefined { +): Promise { if (staleRecovery) return null; console.log(" Backing up sandbox state..."); log(`Agent type: ${sb.agent || "openclaw"}, stateDirs from manifest`); - const backup = sandboxState.backupSandboxState(sandboxName); + const backup = await sandboxState.backupSandboxState(sandboxName); log( `Backup result: success=${backup.success}, backed=${backup.backedUpDirs.join(",")}; files=${backup.backedUpFiles.join(",")}, failed=${backup.failedDirs.join(",")}; failedFiles=${backup.failedFiles.join(",")}`, ); diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index c3c2a87042c..20e5e57eaf9 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -150,7 +150,7 @@ async function rebuildSandboxUnlocked( recoveryManifest = preDeleteRecovery.manifest; recoveryRegistrySnapshot = preDeleteRecovery.registrySnapshot; - const backup = runRebuildBackupPhase({ + const backup = await runRebuildBackupPhase({ sandboxName, // The requested observability bit is replacement intent, not a // preflight mutation of the old registry row. Use a copy only for diff --git a/src/lib/actions/sandbox/snapshot.test.ts b/src/lib/actions/sandbox/snapshot.test.ts index 903eadee680..52b189a727b 100644 --- a/src/lib/actions/sandbox/snapshot.test.ts +++ b/src/lib/actions/sandbox/snapshot.test.ts @@ -199,6 +199,7 @@ vi.mock("../../shields", () => ({ vi.mock("../../shields/timer-bound-lock", () => ({ withTimerBoundShieldsMutationLock: lifecycleMock.withTimerBoundMock, + withTimerBoundShieldsMutationLockAsync: lifecycleMock.withTimerBoundMock, })); vi.mock("../../shields/timer-control", () => ({ @@ -346,39 +347,39 @@ describe("runSandboxSnapshot", () => { ); }); - it("creates a named snapshot after gateway, liveness, and shields checks pass", async () => { - const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {}); - const manifest = { - timestamp: "2026-06-15T00:00:00.000Z", - backupPath: "/tmp/backup-alpha", - name: "before-upgrade", - }; - backupSandboxStateMock.mockReturnValue({ + it("keeps a named snapshot and its shields lock pending until backup completes", async () => { + const manifest = { ...latestBackupFixture, name: "before-upgrade" }; + const backupResult = { success: true, backedUpDirs: ["workspace"], backedUpFiles: ["openclaw.json"], failedDirs: [], failedFiles: [], manifest, - }); - findBackupMock.mockReturnValue({ - match: { ...manifest, snapshotVersion: 7, name: "before-upgrade" }, - }); + }; + let resolveBackup!: (result: typeof backupResult) => void; + backupSandboxStateMock.mockReturnValue( + new Promise((resolve) => { + resolveBackup = resolve; + }), + ); const { runSandboxSnapshot } = await import("./snapshot"); - - await runSandboxSnapshot("alpha", { + const snapshotPromise = runSandboxSnapshot("alpha", { kind: "create", name: "before-upgrade", }); - + const lockCallbackPromise = lifecycleMock.withTimerBoundMock.mock.results[0] + ?.value as Promise; + const settled = vi.fn(); + void snapshotPromise.then(() => settled("snapshot")); + void lockCallbackPromise.then(() => settled("lock callback")); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + resolveBackup(backupResult); + await Promise.all([snapshotPromise, lockCallbackPromise]); expect(backupSandboxStateMock).toHaveBeenCalledWith("alpha", { name: "before-upgrade", }); - expect(findBackupMock).toHaveBeenCalledWith("alpha", manifest.timestamp); - const output = consoleLog.mock.calls.flat().join("\n"); - expect(output).toContain("Creating snapshot of 'alpha' (--name before-upgrade)"); - expect(output).toContain("Snapshot v7 name=before-upgrade created"); - expect(output).toContain("/tmp/backup-alpha"); }); it("refuses snapshot creation before backup when a dcode task is active", async () => { diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 13f4d003979..f48fe61d496 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -46,7 +46,10 @@ import { ROOT, run, validateName } from "../../runner"; import { parseLiveSandboxNames } from "../../runtime-recovery"; import { streamSandboxCreate } from "../../sandbox/create-stream"; import * as shields from "../../shields"; -import { withTimerBoundShieldsMutationLock } from "../../shields/timer-bound-lock"; +import { + withTimerBoundShieldsMutationLock, + withTimerBoundShieldsMutationLockAsync, +} from "../../shields/timer-bound-lock"; import { readTimerMarker } from "../../shields/timer-control"; import { isSandboxReady } from "../../state/gateway"; import { withSandboxMutationLock } from "../../state/mcp-lifecycle-lock"; @@ -553,10 +556,10 @@ function isSnapshotCreationAllowedByDcodeActivity(sandboxName: string): boolean return false; } -function runSnapshotCreate( +async function runSnapshotCreate( sandboxName: string, request: Extract, -): void { +): Promise { const liveNames = requireLiveSandboxesOnSandboxGateway( sandboxName, " Failed to query live sandbox state from OpenShell.", @@ -565,50 +568,54 @@ function runSnapshotCreate( console.error(` Sandbox '${sandboxName}' is not running. Cannot create snapshot.`); snapshotExit(1); } - return withTimerBoundShieldsMutationLock(sandboxName, "create sandbox snapshot", () => { - // Keep the shields check and backup in one timer-bound interval. Normal - // auto-restore waits; at the absolute deadline it may preempt this process - // and reclaim the token rather than changing policy/config mid-copy. - if (!isSnapshotCreationAllowedByShields(sandboxName)) { - console.error(" Cannot create snapshot while shields are up."); - console.error(` Run \`${CLI_NAME} ${sandboxName} shields down\` first, then retry.`); - snapshotExit(1); - } - if ( - shouldCheckDcodeActivity(sandboxName) && - !isSnapshotCreationAllowedByDcodeActivity(sandboxName) - ) { - snapshotExit(1); - } - const label = request.name ? ` (--name ${request.name})` : ""; - console.log(` Creating snapshot of '${sandboxName}'${label}...`); - const result = sandboxState.backupSandboxState(sandboxName, { - name: request.name ?? null, - }); - if (result.success) { - const manifest = result.manifest!; - const entry = sandboxState.findBackup(sandboxName, manifest.timestamp).match ?? manifest; - const v = formatSnapshotVersion(entry); - const nameSuffix = entry.name ? ` name=${entry.name}` : ""; - const itemSummary = `${result.backedUpDirs.length} directories, ${result.backedUpFiles.length} files`; - console.log(` ${G}✓${R} Snapshot ${v}${nameSuffix} created (${itemSummary})`); - console.log(` ${manifest.backupPath}`); - return; - } - if (result.error) { - console.error(` ${result.error}`); - } else { - console.error(" Snapshot failed."); - if (result.failedDirs.length > 0) { - const failedDirs = formatFailedBackupItems(result.failedDirs, result.failedDirReasons); - console.error(` Failed directories: ${failedDirs}`); + return withTimerBoundShieldsMutationLockAsync( + sandboxName, + "create sandbox snapshot", + async () => { + // Keep the shields check and backup in one timer-bound interval. Normal + // auto-restore waits; at the absolute deadline it may preempt this process + // and reclaim the token rather than changing policy/config mid-copy. + if (!isSnapshotCreationAllowedByShields(sandboxName)) { + console.error(" Cannot create snapshot while shields are up."); + console.error(` Run \`${CLI_NAME} ${sandboxName} shields down\` first, then retry.`); + snapshotExit(1); } - if (result.failedFiles.length > 0) { - console.error(` Failed files: ${result.failedFiles.join(", ")}`); + if ( + shouldCheckDcodeActivity(sandboxName) && + !isSnapshotCreationAllowedByDcodeActivity(sandboxName) + ) { + snapshotExit(1); } - } - snapshotExit(1); - }); + const label = request.name ? ` (--name ${request.name})` : ""; + console.log(` Creating snapshot of '${sandboxName}'${label}...`); + const result = await sandboxState.backupSandboxState(sandboxName, { + name: request.name ?? null, + }); + if (result.success) { + const manifest = result.manifest!; + const entry = sandboxState.findBackup(sandboxName, manifest.timestamp).match ?? manifest; + const v = formatSnapshotVersion(entry); + const nameSuffix = entry.name ? ` name=${entry.name}` : ""; + const itemSummary = `${result.backedUpDirs.length} directories, ${result.backedUpFiles.length} files`; + console.log(` ${G}✓${R} Snapshot ${v}${nameSuffix} created (${itemSummary})`); + console.log(` ${manifest.backupPath}`); + return; + } + if (result.error) { + console.error(` ${result.error}`); + } else { + console.error(" Snapshot failed."); + if (result.failedDirs.length > 0) { + const failedDirs = formatFailedBackupItems(result.failedDirs, result.failedDirReasons); + console.error(` Failed directories: ${failedDirs}`); + } + if (result.failedFiles.length > 0) { + console.error(` Failed files: ${result.failedFiles.join(", ")}`); + } + } + snapshotExit(1); + }, + ); } function repairRestoredOpenClawConfigPerms( @@ -1107,7 +1114,7 @@ export async function runSandboxSnapshot( ) { switch (request.kind) { case "create": { - runSnapshotCreate(sandboxName, request); + await runSnapshotCreate(sandboxName, request); break; } case "list": { diff --git a/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts b/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts index b52442fd3ff..0b978d0e118 100644 --- a/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts +++ b/src/lib/actions/sandbox/stopped-sandbox-backup.test.ts @@ -2,6 +2,15 @@ // SPDX-License-Identifier: Apache-2.0 import { describe, expect, it, vi } from "vitest"; +import type { BackupResult } from "../../state/sandbox"; + +function deferred() { + let resolve!: (value: T | PromiseLike) => void; + const promise = new Promise((done) => { + resolve = done; + }); + return { promise, resolve }; +} vi.mock("../../state/registry", () => ({ getSandbox: vi.fn(), @@ -136,58 +145,108 @@ describe("returnSandboxContainerToStopped", () => { }); describe("backupStartedSandboxState", () => { - const ok = { + const ok: BackupResult = { success: true, backedUpDirs: [], failedDirs: [], backedUpFiles: [], failedFiles: [], }; - const unreachable = { ...ok, success: false, unreachable: true }; - const denied = { ...ok, success: false }; + const unreachable: BackupResult = { ...ok, success: false, unreachable: true }; + const denied: BackupResult = { ...ok, success: false }; - it("retries while the just-started container's SSH endpoint is unreachable (#6500)", async () => { + it("retries while the just-started container's exec endpoint is unreachable (#6500)", async () => { + const first = deferred(); + const second = deferred(); + const third = deferred(); const backup = vi .fn() - .mockReturnValueOnce(unreachable) - .mockReturnValueOnce(unreachable) - .mockReturnValueOnce(ok); + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + .mockReturnValueOnce(third.promise); const sleep = vi.fn().mockResolvedValue(undefined); - const result = await backupStartedSandboxState("my-sb", { + const resultPromise = backupStartedSandboxState("my-sb", { backup, sleep, attempts: 5, delayMs: 1, }); + + expect(backup).toHaveBeenCalledTimes(1); + expect(sleep).not.toHaveBeenCalled(); + first.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(2)); + expect(sleep).toHaveBeenCalledTimes(1); + second.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(3)); + expect(sleep).toHaveBeenCalledTimes(2); + const settled = vi.fn(); + void resultPromise.then(settled); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + third.resolve(ok); + + const result = await resultPromise; expect(result.success).toBe(true); expect(backup).toHaveBeenCalledTimes(3); expect(sleep).toHaveBeenCalledTimes(2); }); it("returns a non-transport failure without retrying", async () => { - const backup = vi.fn().mockReturnValue(denied); + const pending = deferred(); + const backup = vi.fn().mockReturnValue(pending.promise); const sleep = vi.fn().mockResolvedValue(undefined); - const result = await backupStartedSandboxState("my-sb", { + const resultPromise = backupStartedSandboxState("my-sb", { backup, sleep, attempts: 5, delayMs: 1, }); + + const settled = vi.fn(); + void resultPromise.then(settled); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + expect(sleep).not.toHaveBeenCalled(); + pending.resolve(denied); + + const result = await resultPromise; expect(result.success).toBe(false); expect(backup).toHaveBeenCalledTimes(1); expect(sleep).not.toHaveBeenCalled(); }); it("gives up after the attempt budget while still unreachable", async () => { - const backup = vi.fn().mockReturnValue(unreachable); + const first = deferred(); + const second = deferred(); + const third = deferred(); + const backup = vi + .fn() + .mockReturnValueOnce(first.promise) + .mockReturnValueOnce(second.promise) + .mockReturnValueOnce(third.promise); const sleep = vi.fn().mockResolvedValue(undefined); - const result = await backupStartedSandboxState("my-sb", { + const resultPromise = backupStartedSandboxState("my-sb", { backup, sleep, attempts: 3, delayMs: 1, }); + + expect(backup).toHaveBeenCalledTimes(1); + first.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(2)); + second.resolve(unreachable); + await vi.waitFor(() => expect(backup).toHaveBeenCalledTimes(3)); + const settled = vi.fn(); + void resultPromise.then(settled); + await Promise.resolve(); + expect(settled).not.toHaveBeenCalled(); + third.resolve(unreachable); + + const result = await resultPromise; expect(result.unreachable).toBe(true); expect(backup).toHaveBeenCalledTimes(3); + expect(sleep).toHaveBeenCalledTimes(2); }); }); diff --git a/src/lib/actions/sandbox/stopped-sandbox-backup.ts b/src/lib/actions/sandbox/stopped-sandbox-backup.ts index 04fef0e7bcb..b4db8ffe30b 100644 --- a/src/lib/actions/sandbox/stopped-sandbox-backup.ts +++ b/src/lib/actions/sandbox/stopped-sandbox-backup.ts @@ -104,7 +104,7 @@ export function returnSandboxContainerToStopped( } interface BackupRetryDeps { - backup: (name: string) => sandboxState.BackupResult; + backup: (name: string) => Promise; sleep: (ms: number) => Promise; attempts: number; delayMs: number; @@ -118,7 +118,7 @@ const defaultBackupRetryDeps: BackupRetryDeps = { }; /** - * Back up a sandbox whose container was just started. The container's SSH + * Back up a sandbox whose container was just started. Its sandbox exec * endpoint can take a few seconds to answer after `docker start`, so retry * while — and only while — the result is a transport-level `unreachable` * failure. Every other outcome (success, permission failure, precondition) @@ -129,14 +129,14 @@ export async function backupStartedSandboxState( depsOverride: Partial = {}, ): Promise { const deps: BackupRetryDeps = { ...defaultBackupRetryDeps, ...depsOverride }; - let result = deps.backup(sandboxName); + let result = await deps.backup(sandboxName); for ( let attempt = 1; attempt < deps.attempts && !result.success && result.unreachable; attempt++ ) { await deps.sleep(deps.delayMs); - result = deps.backup(sandboxName); + result = await deps.backup(sandboxName); } return result; } diff --git a/src/lib/actions/sandbox/upload.test.ts b/src/lib/actions/sandbox/upload.test.ts index ae26fcd4049..02f8de0974a 100644 --- a/src/lib/actions/sandbox/upload.test.ts +++ b/src/lib/actions/sandbox/upload.test.ts @@ -8,6 +8,10 @@ vi.mock("./gateway-state", () => ({ ensureLiveSandboxOrExit: vi.fn(async () => undefined), })); +vi.mock("./gateway-target", () => ({ + getSandboxTargetGatewayName: vi.fn(() => "nemoclaw-9090"), +})); + vi.mock("../../adapters/openshell/runtime", () => ({ runOpenshell: vi.fn(), })); @@ -25,6 +29,7 @@ beforeEach(() => { }); afterEach(() => { + vi.unstubAllEnvs(); vi.restoreAllMocks(); }); @@ -39,7 +44,16 @@ describe("uploadToSandbox", () => { const expectedHostPath = path.resolve(process.cwd(), "SOUL.md"); expect(ensureMock).toHaveBeenCalledWith("alpha", { allowNonReadyPhase: true }); expect(runMock).toHaveBeenCalledWith( - ["sandbox", "upload", "alpha", expectedHostPath, "/sandbox/.openclaw/workspace/SOUL.md"], + [ + "sandbox", + "upload", + "-g", + "nemoclaw-9090", + "--", + "alpha", + expectedHostPath, + "/sandbox/.openclaw/workspace/SOUL.md", + ], expect.objectContaining({ stdio: "inherit" }), ); expect(result).toEqual({ @@ -61,7 +75,7 @@ describe("uploadToSandbox", () => { sandboxDest: "/sandbox/etc/", }); const args = runMock.mock.calls[0]?.[0]; - expect(args?.[3]).toBe("/etc/hosts"); + expect(args?.[6]).toBe("/etc/hosts"); }); it("preserves a trailing separator on a relative host directory source", async () => { @@ -71,11 +85,33 @@ describe("uploadToSandbox", () => { sandboxDest: "/sandbox/work/", }); const args = runMock.mock.calls[0]?.[0]; - const hostPath = args?.[3] as string; + const hostPath = args?.[6] as string; expect(hostPath.endsWith(path.sep) || hostPath.endsWith("/")).toBe(true); expect(hostPath.slice(0, -1)).toBe(path.resolve(process.cwd(), "src")); }); + it("keeps a flag-shaped sandbox destination after the option terminator", async () => { + await uploadToSandbox({ + sandboxName: "alpha", + hostPath: "./SOUL.md", + sandboxDest: "--gateway-endpoint=https://other-gateway.example.test", + }); + + expect(runMock).toHaveBeenCalledWith( + [ + "sandbox", + "upload", + "-g", + "nemoclaw-9090", + "--", + "alpha", + path.resolve(process.cwd(), "SOUL.md"), + "--gateway-endpoint=https://other-gateway.example.test", + ], + expect.objectContaining({ stdio: "inherit" }), + ); + }); + it("throws (does not exit) when no host path is given", async () => { await expect(uploadToSandbox({ sandboxName: "alpha", hostPath: "" })).rejects.toThrow( /No host path provided/, @@ -83,4 +119,15 @@ describe("uploadToSandbox", () => { expect(ensureMock).not.toHaveBeenCalled(); expect(runMock).not.toHaveBeenCalled(); }); + + it("fails closed before liveness or upload when an endpoint override is set", async () => { + vi.stubEnv("OPENSHELL_GATEWAY_ENDPOINT", "https://other-gateway.example.test"); + + await expect(uploadToSandbox({ sandboxName: "alpha", hostPath: "./SOUL.md" })).rejects.toThrow( + /Unset OPENSHELL_GATEWAY_ENDPOINT/, + ); + + expect(ensureMock).not.toHaveBeenCalled(); + expect(runMock).not.toHaveBeenCalled(); + }); }); diff --git a/src/lib/actions/sandbox/upload.ts b/src/lib/actions/sandbox/upload.ts index a861931f68b..fd803d67223 100644 --- a/src/lib/actions/sandbox/upload.ts +++ b/src/lib/actions/sandbox/upload.ts @@ -3,7 +3,9 @@ import { runOpenshell } from "../../adapters/openshell/runtime"; import { CLI_NAME } from "../../cli/branding"; +import { assertNoOpenShellGatewayEndpointOverride } from "../../openshell-gateway-endpoint-guard"; import { ensureLiveSandboxOrExit } from "./gateway-state"; +import { getSandboxTargetGatewayName } from "./gateway-target"; import { resolveHostPathFromCwd } from "./host-path"; export interface SandboxUploadOptions { @@ -25,6 +27,11 @@ export async function uploadToSandbox(opts: SandboxUploadOptions): Promise [sandbox-dest]`, ); } + // The upload is a host-to-sandbox mutation. An ambient endpoint override can + // redirect both the liveness check and the upload away from the gateway the + // registry binds this sandbox to, so reject it before either command runs. + assertNoOpenShellGatewayEndpointOverride(); + const gatewayName = getSandboxTargetGatewayName(opts.sandboxName); const hostPath = resolveHostPathFromCwd(trimmedHostPath); const sandboxDest = (opts.sandboxDest ?? "").trim() || "/sandbox/"; @@ -32,9 +39,12 @@ export async function uploadToSandbox(opts: SandboxUploadOptions): Promise { } }); + it("preserves binary stdout without UTF-8 replacement", async () => { + const bytes = Buffer.from([0, 255, 128, 10]); + const fake = fakeApi({ + emit(stream) { + stream.emit("data", { stdout: { data: bytes.subarray(0, 2) } }); + stream.emit("data", { stdout: { data: bytes.subarray(2) } }); + stream.emit("data", { exit: { exitCode: 0 } }); + stream.emit("end"); + }, + }); + const control = createGrpcOpenShellSandboxControl( + { endpoint: "http://127.0.0.1:8080" }, + fake.api, + ); + + await expect( + control.exec({ + sandboxName: "alpha", + command: ["tar", "-cf", "-", "workspace"], + stdoutEncoding: "buffer", + }), + ).resolves.toEqual({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + }); + }); + it("returns lookup failures without starting exec", async () => { const error = serviceError("gateway unavailable"); const fake = fakeApi({ getError: error }); diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.ts b/src/lib/adapters/openshell/grpc-sandbox-control.ts index c4408c94821..1bfaf8d95e5 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.ts @@ -4,7 +4,6 @@ import type { EventEmitter } from "node:events"; import { isIP } from "node:net"; import path from "node:path"; -import { StringDecoder } from "node:string_decoder"; import * as grpc from "@grpc/grpc-js"; import * as protoLoader from "@grpc/proto-loader"; @@ -236,10 +235,8 @@ function execute( metadata, options, ); - const stdoutDecoder = new StringDecoder("utf8"); - const stderrDecoder = new StringDecoder("utf8"); - let stdout = ""; - let stderr = ""; + const stdoutChunks: Buffer[] = []; + const stderrChunks: Buffer[] = []; let retainedBytes = 0; let status: number | null = null; let settled = false; @@ -247,9 +244,11 @@ function execute( const finish = (error?: Error) => { if (settled) return; settled = true; - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); + const stdoutBytes = Buffer.concat(stdoutChunks); + const stdout = request.stdoutEncoding === "buffer" ? "" : stdoutBytes.toString("utf8"); + const stderr = Buffer.concat(stderrChunks).toString("utf8"); const result: SandboxExecResult = { status, stdout, stderr }; + if (request.stdoutEncoding === "buffer") result.stdoutBytes = stdoutBytes; if (error) result.error = error; resolve(result); }; @@ -258,8 +257,8 @@ function execute( const remaining = maxOutputBytes - retainedBytes; const retained = data.subarray(0, Math.max(0, remaining)); retainedBytes += retained.length; - if (destination === "stdout") stdout += stdoutDecoder.write(retained); - else stderr += stderrDecoder.write(retained); + if (destination === "stdout") stdoutChunks.push(retained); + else stderrChunks.push(retained); if (retained.length < data.length) { finish(new OpenShellExecOutputLimitError(maxOutputBytes)); stream.cancel(); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.test.ts b/src/lib/adapters/openshell/sandbox-control-routing.test.ts index e521f430605..a48592259ce 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.test.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.test.ts @@ -189,6 +189,52 @@ describe("read-only OpenShell sandbox control routing", () => { expect(test.close).toHaveBeenCalledOnce(); }); + it("preserves binary stdout across the direct route", async () => { + const bytes = Buffer.from([0, 255, 128, 10]); + const result = { status: 0, stdout: "", stdoutBytes: bytes, stderr: "" }; + const test = dependencies(result); + const stdin = "import sqlite3, sys\nsrc, dst = sys.argv[1], sys.argv[2]"; + const binaryRequest = { ...request, stdin, stdoutEncoding: "buffer" as const }; + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", binaryRequest, test.deps), + ).resolves.toEqual(result); + expect(test.grpcExec).toHaveBeenCalledWith({ + ...binaryRequest, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + }); + + it("preserves stdin and binary stdout across the pre-dispatch CLI fallback", async () => { + const stdin = "import sqlite3, sys\nsrc, dst = sys.argv[1], sys.argv[2]"; + const bytes = Buffer.from([0, 255, 128, 10]); + const grpcError = new Error("UNAVAILABLE"); + const cliResult = { status: 0, stdout: "", stdoutBytes: bytes, stderr: "" }; + const test = dependencies( + { + status: null, + stdout: "", + stderr: "", + error: new OpenShellGrpcPreDispatchError(grpcError), + }, + cliResult, + ); + const binaryRequest = { ...request, stdin, stdoutEncoding: "buffer" as const }; + + await expect( + execSandboxReadOnlyWithGrpcFallback("nemoclaw", binaryRequest, test.deps), + ).resolves.toEqual(cliResult); + + expect(test.grpcExec).toHaveBeenCalledWith({ + ...binaryRequest, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + expect(test.cliExec).toHaveBeenCalledWith({ + ...binaryRequest, + timeoutMs: OPENSHELL_OPERATION_TIMEOUT_MS, + }); + }); + it("does not replay a completed non-zero command through the CLI", async () => { const result = { status: 2, stdout: "", stderr: "unknown flag" }; const test = dependencies(result); diff --git a/src/lib/adapters/openshell/sandbox-control-routing.ts b/src/lib/adapters/openshell/sandbox-control-routing.ts index f6f356ad758..aa8bc47c308 100644 --- a/src/lib/adapters/openshell/sandbox-control-routing.ts +++ b/src/lib/adapters/openshell/sandbox-control-routing.ts @@ -81,12 +81,13 @@ export function selectOpenShellSandboxControlForMutation( * so NemoClaw cannot replace that path here. * * This migration contract is limited to the reviewed read-only callers (the - * session list, rebuild file probe, debug diagnostic probes, and version probe - * at this slice), not a general routing policy. Remove the CLI fallback when - * OpenShell's public client or bindings support the edge-tunnel auth and - * credential-refresh lifecycle. Every added caller requires a replay-semantics - * review; mutations must select one transport before dispatch and must never - * be replayed automatically. + * session list, rebuild file probe, debug diagnostic probes, version probe, + * and state backup probes, audits, and reads at this slice), not a general + * routing policy. + * Remove the CLI fallback when OpenShell's public client or bindings support + * the edge-tunnel auth and credential-refresh lifecycle. Every added caller + * requires a replay-semantics review; mutations must select one transport + * before dispatch and must never be replayed automatically. */ export async function execSandboxReadOnlyWithGrpcFallback( gatewayName: string, diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 0a5e3762fdc..55131e2ce1a 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -259,6 +259,38 @@ describe("CLI OpenShell sandbox control", () => { }); }); + it("projects raw stdout from the single bounded CLI capture", async () => { + const bytes = Buffer.from([0, 255, 128, 10]); + const capture = vi.fn( + (): CaptureOpenshellBinaryResult => ({ + status: 0, + stdout: bytes, + stderr: Buffer.from("warning"), + }), + ); + const control = createCliOpenShellSandboxControl(capture); + + await expect( + control.exec({ + sandboxName: "alpha", + command: ["tar", "-cf", "-", "workspace"], + stdin: "archive request", + maxOutputBytes: 1024, + stdoutEncoding: "buffer", + timeoutMs: 120_000, + }), + ).resolves.toEqual({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "warning", + }); + expect(capture).toHaveBeenCalledWith( + ["sandbox", "exec", "--name", "alpha", "--", "tar", "-cf", "-", "workspace"], + { input: "archive request", maxBuffer: 1024, timeout: 120_000 }, + ); + }); + it("preserves transport failures without throwing", async () => { const error = Object.assign(new Error("spawnSync openshell EIO"), { code: "EIO", diff --git a/src/lib/adapters/openshell/sandbox-control.ts b/src/lib/adapters/openshell/sandbox-control.ts index b4b1fe0d4cb..7f1d41177b2 100644 --- a/src/lib/adapters/openshell/sandbox-control.ts +++ b/src/lib/adapters/openshell/sandbox-control.ts @@ -17,11 +17,15 @@ export interface SandboxExecRequest { maxOutputBytes?: number; /** End-to-end lookup and execution deadline. Zero means no deadline. */ timeoutMs?: number; + /** Preserve stdout bytes instead of decoding them as UTF-8. */ + stdoutEncoding?: "utf8" | "buffer"; } export interface SandboxExecResult { status: number | null; stdout: string; + /** Present when stdoutEncoding is `buffer`; stdout remains an empty string. */ + stdoutBytes?: Buffer; stderr: string; error?: Error; signal?: NodeJS.Signals | null; @@ -312,14 +316,17 @@ function retainCombinedOutput( function normalizeExecResult( result: CaptureOpenshellBinaryResult, maxOutputBytes: number, + stdoutEncoding: SandboxExecRequest["stdoutEncoding"], ): SandboxExecResult { const retained = retainCombinedOutput(result.stdout, result.stderr, maxOutputBytes); - const stdout = retained.stdout.toString("utf8"); + const stdout = stdoutEncoding === "buffer" ? "" : retained.stdout.toString("utf8"); const stderr = retained.stderr.toString("utf8"); + const stdoutBytes = stdoutEncoding === "buffer" ? { stdoutBytes: retained.stdout } : {}; if (retained.truncated || isOutputLimitError(result.error)) { return { status: null, stdout, + ...stdoutBytes, stderr, error: new OpenShellExecOutputLimitError(maxOutputBytes), ...(result.signal !== undefined ? { signal: result.signal } : {}), @@ -328,6 +335,7 @@ function normalizeExecResult( const normalized: SandboxExecResult = { status: result.status, stdout, + ...stdoutBytes, stderr, }; if (result.error) normalized.error = result.error; @@ -366,7 +374,7 @@ function createCliSandboxControl( timeout: request.timeoutMs, }, ); - return normalizeExecResult(result, maxOutputBytes); + return normalizeExecResult(result, maxOutputBytes, request.stdoutEncoding); }, }; } diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index 2b197d9abfc..f8c8d01b2a8 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2574,7 +2574,7 @@ async function createSandboxWithBaseImageResolution( console.log(` Messaging credential(s) rotated: ${rotatedNames}`); console.log(" Rebuilding sandbox to propagate new credentials to the L7 proxy..."); if (!shouldSkipPreRecreateBackup(process.env)) { - const result = recreateProtection.backup(); + const result = await recreateProtection.backup(); if (!result.ok) { console.error( " Set NEMOCLAW_RECREATE_WITHOUT_BACKUP=1 to recreate without preserving state.", @@ -2642,7 +2642,7 @@ async function createSandboxWithBaseImageResolution( !shouldSkipPreRecreateBackup(process.env) ) { note(" Backing up workspace state before recreating sandbox..."); - const result = recreateProtection.backup(); + const result = await recreateProtection.backup(); if (!result.ok) { console.error( " Set NEMOCLAW_RECREATE_WITHOUT_BACKUP=1 to recreate without preserving state.", diff --git a/src/lib/onboard/sandbox-backup-on-recreate.test.ts b/src/lib/onboard/sandbox-backup-on-recreate.test.ts index 060e9443835..51c33300dc6 100644 --- a/src/lib/onboard/sandbox-backup-on-recreate.test.ts +++ b/src/lib/onboard/sandbox-backup-on-recreate.test.ts @@ -24,11 +24,11 @@ function makeBackup(overrides: Partial = {}): BackupResult { } describe("backupSandboxBeforeRecreate", () => { - it("returns ok with backup result on success", () => { + it("returns ok with backup result on success", async () => { const backup = makeBackup(); - const backupImpl = vi.fn().mockReturnValue(backup); + const backupImpl = vi.fn().mockResolvedValue(backup); const log = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", backupImpl, log, @@ -41,16 +41,16 @@ describe("backupSandboxBeforeRecreate", () => { expect(log).toHaveBeenCalledWith(expect.stringContaining("State backed up")); }); - it("rejects an unmarked custom OpenClaw backup before recreate deletion (#6108)", () => { + it("rejects an unmarked custom OpenClaw backup before recreate deletion (#6108)", async () => { const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", sandboxEntry: { name: "my-assistant", agent: "openclaw", fromDockerfile: "/tmp/Dockerfile.custom", }, - backupImpl: () => makeBackup(), + backupImpl: async () => makeBackup(), log: vi.fn(), errorLog, }); @@ -62,13 +62,13 @@ describe("backupSandboxBeforeRecreate", () => { ); }); - it("rejects an unmarked backup for an orphan custom OpenClaw target (#6108)", () => { + it("rejects an unmarked backup for an orphan custom OpenClaw target (#6108)", async () => { const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "orphan", sandboxEntry: null, requireOpenClawImagePluginProvenance: true, - backupImpl: () => makeBackup(), + backupImpl: async () => makeBackup(), log: vi.fn(), errorLog, }); @@ -81,7 +81,7 @@ describe("backupSandboxBeforeRecreate", () => { ); }); - it("returns ok:false with failureKind=partial when some entries failed", () => { + it("returns ok:false with failureKind=partial when some entries failed", async () => { const backup = makeBackup({ success: false, backedUpDirs: ["workspace"], @@ -90,9 +90,9 @@ describe("backupSandboxBeforeRecreate", () => { failedFiles: ["bad.bin"], }); const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => backup, + backupImpl: async () => backup, log: vi.fn(), errorLog, }); @@ -103,19 +103,19 @@ describe("backupSandboxBeforeRecreate", () => { expect(errorLog).toHaveBeenCalledWith(expect.stringContaining("Aborting recreate")); }); - it("rejects backup result missing manifest backupPath", () => { + it("rejects backup result missing manifest backupPath", async () => { const backup = makeBackup({ manifest: undefined }); const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => backup, + backupImpl: async () => backup, log: vi.fn(), errorLog, }); expect(result.ok).toBe(false); }); - it("returns ok:false with failureKind=empty when nothing was backed up", () => { + it("returns ok:false with failureKind=empty when nothing was backed up", async () => { const backup = makeBackup({ success: false, backedUpDirs: [], @@ -125,9 +125,9 @@ describe("backupSandboxBeforeRecreate", () => { error: "Pre-backup audit rejected an unsafe symlink", }); const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => backup, + backupImpl: async () => backup, errorLog, log: vi.fn(), }); @@ -138,11 +138,11 @@ describe("backupSandboxBeforeRecreate", () => { expect(errorLog).toHaveBeenCalledWith(" Reason: Pre-backup audit rejected an unsafe symlink"); }); - it("returns ok:false with failureKind=threw when backup throws", () => { + it("returns ok:false with failureKind=threw when backup throws", async () => { const errorLog = vi.fn(); - const result = backupSandboxBeforeRecreate({ + const result = await backupSandboxBeforeRecreate({ sandboxName: "my-assistant", - backupImpl: () => { + backupImpl: async () => { throw new Error("disk full"); }, errorLog, diff --git a/src/lib/onboard/sandbox-backup-on-recreate.ts b/src/lib/onboard/sandbox-backup-on-recreate.ts index bbbfda4dd99..b5102cd2058 100644 --- a/src/lib/onboard/sandbox-backup-on-recreate.ts +++ b/src/lib/onboard/sandbox-backup-on-recreate.ts @@ -5,7 +5,7 @@ import type { SandboxEntry } from "../state/registry"; import type { BackupResult } from "../state/sandbox"; import * as sandboxState from "../state/sandbox"; -export type SandboxBackupImpl = (sandboxName: string) => BackupResult; +export type SandboxBackupImpl = (sandboxName: string) => Promise; export interface PreRecreateBackupOptions { sandboxName: string; @@ -30,9 +30,9 @@ export interface PreRecreateBackupResult { errorMessage?: string; } -export function backupSandboxBeforeRecreate( +export async function backupSandboxBeforeRecreate( opts: PreRecreateBackupOptions, -): PreRecreateBackupResult { +): Promise { const log = opts.log ?? ((m: string) => console.log(m)); const errorLog = opts.errorLog ?? ((m: string) => console.error(m)); const backupImpl = opts.backupImpl ?? sandboxState.backupSandboxState; @@ -42,7 +42,7 @@ export function backupSandboxBeforeRecreate( (Boolean(sandboxEntry?.fromDockerfile) && (!sandboxEntry?.agent || sandboxEntry.agent === "openclaw")); try { - const backup = backupImpl(opts.sandboxName); + const backup = await backupImpl(opts.sandboxName); if (backup.success && backup.manifest?.backupPath) { if ( (customOpenClaw || backup.manifest.reconcileOpenClawImagePluginProvenance === true) && diff --git a/src/lib/onboard/sandbox-recreate-protection.test.ts b/src/lib/onboard/sandbox-recreate-protection.test.ts index 6da8b2b806f..de46c6a8429 100644 --- a/src/lib/onboard/sandbox-recreate-protection.test.ts +++ b/src/lib/onboard/sandbox-recreate-protection.test.ts @@ -5,7 +5,7 @@ import { describe, expect, it, vi } from "vitest"; import { createSandboxRecreateProtection } from "./sandbox-recreate-protection"; describe("createSandboxRecreateProtection", () => { - it("forwards one custom-image protection context to every recreation path (#6108)", () => { + it("forwards one custom-image protection context to every recreation path (#6108)", async () => { const note = vi.fn(); const sandboxEntry = { name: "my-assistant", @@ -22,7 +22,7 @@ describe("createSandboxRecreateProtection", () => { backup: null, failureKind: "none" as const, }; - const backupSandboxBeforeRecreate = vi.fn(() => backupResult); + const backupSandboxBeforeRecreate = vi.fn(async () => backupResult); const protection = createSandboxRecreateProtection( { sandboxName: "my-assistant", @@ -53,7 +53,7 @@ describe("createSandboxRecreateProtection", () => { }); expect(resolveNotReadyOutcome).toHaveBeenCalledWith("my-assistant", note, sandboxEntry, true); - expect(protection.backup()).toBe(backupResult); + await expect(protection.backup()).resolves.toBe(backupResult); expect(backupSandboxBeforeRecreate).toHaveBeenCalledWith({ sandboxName: "my-assistant", sandboxEntry, diff --git a/src/lib/onboard/sandbox-recreate-protection.ts b/src/lib/onboard/sandbox-recreate-protection.ts index 94df005ab27..0e632230055 100644 --- a/src/lib/onboard/sandbox-recreate-protection.ts +++ b/src/lib/onboard/sandbox-recreate-protection.ts @@ -48,7 +48,7 @@ export function createSandboxRecreateProtection( resolveNotReadyOutcome(): notReadyRecreate.NonInteractiveNotReadyOutcome { return deps.resolveNotReadyOutcome(sandboxName, note, sandboxEntry, customOpenClawImage); }, - backup(): PreRecreateBackupResult { + backup(): Promise { return deps.backupSandboxBeforeRecreate({ sandboxName, sandboxEntry, diff --git a/src/lib/state/sandbox-backup-grpc.test.ts b/src/lib/state/sandbox-backup-grpc.test.ts new file mode 100644 index 00000000000..8b684641f93 --- /dev/null +++ b/src/lib/state/sandbox-backup-grpc.test.ts @@ -0,0 +1,708 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; + +import { validateOpenShellExecRequest } from "../adapters/openshell/sandbox-control"; + +const mocks = vi.hoisted(() => ({ + captureSandboxSshConfigCommand: vi.fn(), + execSandboxReadOnlyWithGrpcFallback: vi.fn(), + getSandbox: vi.fn(), + loadAgent: vi.fn(), + resolveOpenshell: vi.fn(), +})); + +vi.mock("../adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: mocks.execSandboxReadOnlyWithGrpcFallback, +})); + +vi.mock("../adapters/openshell/client.js", async (importOriginal) => ({ + ...(await importOriginal()), + captureSandboxSshConfigCommand: mocks.captureSandboxSshConfigCommand, +})); + +vi.mock("../adapters/openshell/resolve.js", async (importOriginal) => ({ + ...(await importOriginal()), + resolveOpenshell: mocks.resolveOpenshell, +})); + +vi.mock("../agent/defs.js", async (importOriginal) => ({ + ...(await importOriginal()), + loadAgent: mocks.loadAgent, +})); + +vi.mock("./registry.js", async (importOriginal) => ({ + ...(await importOriginal()), + getSandbox: mocks.getSandbox, +})); + +const ORIGINAL_HOME = process.env.HOME; +const TEST_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-grpc-state-backup-")); +process.env.HOME = TEST_HOME; + +const { + backupSandboxState, + buildSandboxDirectoryAuditCommand, + buildSandboxDirectoryAuditInput, + buildSandboxDirectoryDiscoveryCommand, + buildSandboxDirectoryNameList, + MAX_SANDBOX_DIRECTORY_AUDIT_BYTES, + MAX_SANDBOX_DIRECTORY_AUDIT_ENTRIES, + MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES, + parseSandboxDirectoryAudit, + parseSandboxDirectoryNameList, +} = await import("./sandbox.js"); +const BACKUPS_ROOT = path.join(TEST_HOME, ".nemoclaw", "rebuild-backups"); +const STATE_DIR = "/sandbox/.fixture"; + +interface ExecResult { + status: number | null; + stdout: string; + stderr: string; + stdoutBytes?: Buffer; + error?: Error; + signal?: NodeJS.Signals; +} + +function completed(stdout = ""): ExecResult { + return { status: 0, stdout, stderr: "" }; +} + +function completedDirectoryProbe(names: readonly string[]): ExecResult { + const encoded = buildSandboxDirectoryNameList(names); + assert.ok(encoded.ok); + return { ...completed(), stdoutBytes: encoded.input }; +} + +function encodeAuditEntries( + entries: readonly (readonly [type: string, entryPath: string, linkTarget: string])[], +): Buffer { + return Buffer.from(entries.flatMap((entry) => [...entry, ""]).join("\0"), "utf8"); +} + +function completedAudit( + entries: readonly (readonly [type: string, entryPath: string, linkTarget: string])[] = [], +): ExecResult { + return { ...completed(), stdoutBytes: encodeAuditEntries(entries) }; +} + +function queueSuccessfulProbeAndAudit( + dirName: string | readonly string[] = "state", + auditEntries: readonly (readonly [type: string, entryPath: string, linkTarget: string])[] = [], +): void { + const names = typeof dirName === "string" ? [dirName] : dirName; + mocks.execSandboxReadOnlyWithGrpcFallback + .mockResolvedValueOnce(completedDirectoryProbe(names)) + .mockResolvedValueOnce(completedAudit(auditEntries)); +} + +function createBinaryTarArchive(dirName: string | readonly string[] = "state"): { + archive: Buffer; + payload: Buffer; +} { + const names = typeof dirName === "string" ? [dirName] : [...dirName]; + const source = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-grpc-state-source-")); + const payload = Buffer.from([0x53, 0x54, 0x41, 0x54, 0x45, 0x00, 0xff, 0xfe, 0x80, 0x0a]); + try { + for (const name of names) fs.mkdirSync(path.join(source, name), { recursive: true }); + fs.writeFileSync(path.join(source, names[0], "payload.bin"), payload); + const result = spawnSync("tar", ["-cf", "-", "-C", source, ...names], { + encoding: null, + maxBuffer: 4 * 1024 * 1024, + }); + assert.equal(result.status, 0, `Could not create test tar archive: ${String(result.stderr)}`); + assert(result.stdout, `Test tar archive was empty: ${String(result.stderr)}`); + return { archive: Buffer.from(result.stdout), payload }; + } finally { + fs.rmSync(source, { recursive: true, force: true }); + } +} + +function expectProbeAndAuditRequests(dirName = "state"): void { + const calls = mocks.execSandboxReadOnlyWithGrpcFallback.mock.calls; + const expectedNames = buildSandboxDirectoryNameList([dirName]); + assert.ok(expectedNames.ok); + const expectedAuditInput = buildSandboxDirectoryAuditInput(STATE_DIR, [dirName]); + assert.ok(expectedAuditInput.ok); + + expect(calls[0]).toEqual([ + "nemoclaw", + expect.objectContaining({ + sandboxName: "alpha", + command: ["sh", "-c", expect.stringContaining("xargs -0")], + stdin: expectedNames.input, + maxOutputBytes: MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES + 1, + stdoutEncoding: "buffer", + timeoutMs: 30_000, + }), + ]); + expect(calls[1]).toEqual([ + "nemoclaw", + expect.objectContaining({ + sandboxName: "alpha", + command: ["sh", "-c", expect.stringContaining("xargs -0 -r sh -c")], + stdin: expectedAuditInput.input, + maxOutputBytes: MAX_SANDBOX_DIRECTORY_AUDIT_BYTES + 1, + stdoutEncoding: "buffer", + timeoutMs: 30_000, + }), + ]); + + // Directory backup must not recreate the removed SSH-config transport. + expect(mocks.resolveOpenshell).not.toHaveBeenCalled(); + expect(mocks.captureSandboxSshConfigCommand).not.toHaveBeenCalled(); +} + +function expectProbeAuditAndBinaryTarRequests(dirName = "state"): void { + expect(mocks.execSandboxReadOnlyWithGrpcFallback).toHaveBeenCalledTimes(3); + expectProbeAndAuditRequests(dirName); + const calls = mocks.execSandboxReadOnlyWithGrpcFallback.mock.calls; + const expectedNames = buildSandboxDirectoryNameList([dirName]); + assert.ok(expectedNames.ok); + expect(calls[2]).toEqual([ + "nemoclaw", + { + sandboxName: "alpha", + command: [ + "sh", + "-c", + `tar -cf - -C '${STATE_DIR}' --null --verbatim-files-from --files-from=-`, + ], + stdin: expectedNames.input, + timeoutMs: 120_000, + maxOutputBytes: 256 * 1024 * 1024, + stdoutEncoding: "buffer", + }, + ]); +} + +afterAll(() => { + void (ORIGINAL_HOME === undefined + ? Reflect.deleteProperty(process.env, "HOME") + : Reflect.set(process.env, "HOME", ORIGINAL_HOME)); + fs.rmSync(TEST_HOME, { recursive: true, force: true }); +}); + +beforeEach(() => { + fs.rmSync(BACKUPS_ROOT, { recursive: true, force: true }); + vi.clearAllMocks(); + mocks.getSandbox.mockReturnValue({ + name: "alpha", + agent: "fixture", + policies: [], + }); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_DIR }, + expectedVersion: null, + stateDirs: ["state"], + stateFiles: [], + }); +}); + +describe("backupSandboxState OpenShell directory transport", () => { + it("fails closed before dispatch when the persisted gateway binding is invalid", async () => { + mocks.getSandbox.mockReturnValue({ + name: "alpha", + agent: "fixture", + policies: [], + gatewayName: "untrusted-gateway", + }); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_DIR }, + expectedVersion: null, + stateDirs: ["state", "workspace"], + stateFiles: [ + { path: "SOUL.md", strategy: "copy" }, + { path: "runtime/state.db", strategy: "sqlite_backup" }, + ], + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + backedUpDirs: [], + failedDirs: ["state", "workspace"], + backedUpFiles: [], + failedFiles: ["SOUL.md", "runtime/state.db"], + error: expect.stringContaining("Invalid persisted sandbox gateway binding"), + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).not.toHaveBeenCalled(); + expect(mocks.resolveOpenshell).not.toHaveBeenCalled(); + expect(mocks.captureSandboxSshConfigCommand).not.toHaveBeenCalled(); + }); + + it("probes, audits, and extracts binary tar bytes through the reviewed read-only route", async () => { + const { archive, payload } = createBinaryTarArchive(); + expect(Buffer.from(archive.toString("utf8"), "utf8")).not.toEqual(archive); + queueSuccessfulProbeAndAudit(); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + ...completed(), + stdoutBytes: archive, + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: true, + unreachable: false, + backedUpDirs: ["state"], + failedDirs: [], + backedUpFiles: [], + failedFiles: [], + }); + expect(result.manifest?.backedUpDirs).toEqual(["state"]); + expect(fs.readFileSync(path.join(result.manifest!.backupPath, "state", "payload.bin"))).toEqual( + payload, + ); + expectProbeAuditAndBinaryTarRequests(); + }); + + it.each([ + ["unterminated NUL list", Buffer.from("state", "utf8"), "truncated name list"], + ["empty element", Buffer.from("state\0\0", "utf8"), "empty path"], + ["invalid UTF-8", Buffer.from([0xff, 0]), "invalid UTF-8"], + ["traversal", Buffer.from("../state\0", "utf8"), "unsafe path"], + ])("rejects directory discovery output with an %s", (_kind, output, expectedError) => { + expect(parseSandboxDirectoryNameList(output)).toEqual({ + ok: false, + error: expect.stringContaining(expectedError), + }); + }); + + it("accepts a directory name list exactly at the byte budget", () => { + const name = "x".repeat(MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES - 1); + const encoded = buildSandboxDirectoryNameList([name]); + assert.ok(encoded.ok); + expect(encoded.input).toHaveLength(MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES); + + const parsed = parseSandboxDirectoryNameList(encoded.input); + assert.ok(parsed.ok); + expect(parsed.names).toEqual([name]); + }); + + it.each([ + ["symlink", ["l", `${STATE_DIR}/state/leak`, "/etc/passwd"]], + ["hard link", ["f", `${STATE_DIR}/state/shared.db`, ""]], + ["special file", ["p", `${STATE_DIR}/state/control.fifo`, ""]], + ] as const)("rejects an unsafe %s audit row before requesting a tar archive", async (_kind, row) => { + queueSuccessfulProbeAndAudit("state", [row]); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + backedUpDirs: [], + failedDirs: ["state"], + error: expect.stringContaining("Pre-backup audit rejected"), + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).toHaveBeenCalledTimes(2); + expectProbeAndAuditRequests(); + }); + + it("parses newline-bearing paths as one NUL-framed audit record", () => { + const entry = ["p", `${STATE_DIR}/state/line\nfeed`, ""] as const; + + expect(parseSandboxDirectoryAudit(encodeAuditEntries([entry]), STATE_DIR, ["state"])).toEqual({ + ok: true, + entries: [{ type: "p", path: entry[1], linkTarget: "" }], + }); + expect(buildSandboxDirectoryAuditCommand()).toContain('-printf "%y\\0%p\\0%l\\0"'); + }); + + it.each([ + [ + "incomplete field count", + Buffer.from(`l\0${STATE_DIR}/state/leak\0/etc/passwd\0extra\0`, "utf8"), + "incomplete record", + ], + [ + "invalid UTF-8", + Buffer.concat([Buffer.from("l\0"), Buffer.from([0xff]), Buffer.from("\0/etc/passwd\0")]), + "invalid UTF-8", + ], + [ + "unterminated record", + Buffer.from(`l\0${STATE_DIR}/state/leak\0/etc/passwd`, "utf8"), + "truncated record", + ], + ["unexpected type", encodeAuditEntries([["d", `${STATE_DIR}/state`, ""]]), "invalid file type"], + ["outside root", encodeAuditEntries([["l", "/etc/passwd", "/tmp/x"]]), "outside its root"], + [ + "path traversal", + encodeAuditEntries([["l", `${STATE_DIR}/state/../config/leak`, "/tmp/x"]]), + "outside its root", + ], + [ + "outside expected directory", + encodeAuditEntries([["l", `${STATE_DIR}/config/leak`, "/tmp/x"]]), + "outside its expected state directories", + ], + [ + "non-link target", + encodeAuditEntries([["f", `${STATE_DIR}/state/shared.db`, "unexpected"]]), + "invalid link target field", + ], + ])("rejects an audit with %s", (_kind, output, expectedError) => { + expect(parseSandboxDirectoryAudit(output, STATE_DIR, ["state"])).toEqual({ + ok: false, + error: expect.stringContaining(expectedError), + }); + }); + + it("bounds audit bytes and record count before parsing fields", () => { + expect( + parseSandboxDirectoryAudit(Buffer.alloc(MAX_SANDBOX_DIRECTORY_AUDIT_BYTES + 1), STATE_DIR, [ + "state", + ]), + ).toEqual({ + ok: false, + error: expect.stringContaining("bytes"), + }); + expect( + parseSandboxDirectoryAudit( + Buffer.from("f\0\0\0".repeat(MAX_SANDBOX_DIRECTORY_AUDIT_ENTRIES + 1), "utf8"), + STATE_DIR, + ["state"], + ), + ).toEqual({ + ok: false, + error: expect.stringContaining("entries"), + }); + }); + + it.each([ + "error", + "signal", + ] as const)("fails closed when the audit returns status zero with a transport %s", async (failureKind) => { + mocks.execSandboxReadOnlyWithGrpcFallback + .mockResolvedValueOnce(completedDirectoryProbe(["state"])) + .mockResolvedValueOnce({ + ...completed(), + ...(failureKind === "error" + ? { error: new Error("audit stream reset") } + : { signal: "SIGTERM" }), + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + backedUpDirs: [], + failedDirs: ["state"], + error: expect.stringContaining( + failureKind === "error" ? "audit stream reset" : "signal SIGTERM", + ), + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).toHaveBeenCalledTimes(2); + }); + + it.each([ + "agents", + "extensions", + ])("fails closed when an OpenClaw %s subtree cannot be audited", async (dirName) => { + mocks.getSandbox.mockReturnValue({ + name: "alpha", + agent: "openclaw", + policies: [], + }); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_DIR }, + expectedVersion: null, + stateDirs: [dirName], + stateFiles: [], + }); + mocks.execSandboxReadOnlyWithGrpcFallback + .mockResolvedValueOnce(completedDirectoryProbe([dirName])) + .mockResolvedValueOnce({ + status: 1, + stdout: "", + stderr: `find: '${STATE_DIR}/${dirName}/image-owned': Permission denied`, + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + unreachable: false, + backedUpDirs: [], + failedDirs: [dirName], + error: expect.stringContaining("Pre-backup audit failed"), + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).toHaveBeenCalledTimes(2); + expectProbeAndAuditRequests(dirName); + const auditCommand = mocks.execSandboxReadOnlyWithGrpcFallback.mock.calls[1][1].command[2]; + expect(auditCommand).toContain("xargs -0 -r sh -c"); + expect(auditCommand).toContain('find "$root"'); + expect(auditCommand).not.toContain("-files0-from"); + expect(auditCommand).not.toContain("|| true"); + expect(auditCommand).not.toContain("-prune"); + }); + + it("accepts the reviewed image symlink audit row before downloading the archive", async () => { + mocks.getSandbox.mockReturnValue({ + name: "alpha", + agent: "openclaw", + policies: [], + }); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_DIR }, + expectedVersion: null, + stateDirs: ["extensions"], + stateFiles: [], + }); + const { archive, payload } = createBinaryTarArchive("extensions"); + const allowedAuditRow = [ + "l", + `${STATE_DIR}/extensions/openclaw-weixin/node_modules/.bin/qrcode-terminal`, + "../qrcode-terminal/bin/qrcode-terminal.js", + ] as const; + queueSuccessfulProbeAndAudit("extensions", [allowedAuditRow]); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + ...completed(), + stdoutBytes: archive, + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: true, + backedUpDirs: ["extensions"], + failedDirs: [], + }); + expect( + fs.readFileSync(path.join(result.manifest!.backupPath, "extensions", "payload.bin")), + ).toEqual(payload); + expectProbeAuditAndBinaryTarRequests("extensions"); + const auditCommand = mocks.execSandboxReadOnlyWithGrpcFallback.mock.calls[1][1].command[2]; + expect(auditCommand).toContain("xargs -0 -r sh -c"); + expect(auditCommand).not.toContain("-files0-from"); + expect(auditCommand).not.toContain("|| true"); + expect(auditCommand).not.toContain("-prune"); + }); + + it("marks a binary tar transport failure unreachable and does not restore partial state", async () => { + queueSuccessfulProbeAndAudit(); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + status: null, + stdout: "", + stderr: "", + error: new Error("sandbox exec stream reset"), + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + unreachable: true, + backedUpDirs: [], + failedDirs: ["state"], + }); + expect(result.manifest?.backedUpDirs).toEqual([]); + expect(fs.existsSync(path.join(result.manifest!.backupPath, "state"))).toBe(false); + expectProbeAuditAndBinaryTarRequests(); + }); + + it.each([ + ["error", { error: new Error("sandbox exec stream reset") }], + ["signal", { signal: "SIGTERM" as const }], + ])("rejects tar bytes returned with a transport %s even when tar reports success", async (_failureKind, transportFailure) => { + const { archive } = createBinaryTarArchive(); + queueSuccessfulProbeAndAudit(); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + ...completed(), + stdoutBytes: archive, + ...transportFailure, + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + unreachable: true, + backedUpDirs: [], + failedDirs: ["state"], + }); + expect(result.manifest?.backedUpDirs).toEqual([]); + expect(fs.existsSync(path.join(result.manifest!.backupPath, "state"))).toBe(false); + expectProbeAuditAndBinaryTarRequests(); + }); + + it("fails closed when a clean tar result omits binary stdout", async () => { + queueSuccessfulProbeAndAudit(); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + status: 0, + stdout: "", + stderr: "", + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + backedUpDirs: [], + failedDirs: ["state"], + }); + expect(result.manifest?.backedUpDirs).toEqual([]); + expect(fs.existsSync(path.join(result.manifest!.backupPath, "state"))).toBe(false); + expectProbeAuditAndBinaryTarRequests(); + }); + + it("fails closed without claiming unreachable for a completed nonzero tar result", async () => { + queueSuccessfulProbeAndAudit(); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + status: 13, + stdout: "", + stderr: "tar: state: Permission denied", + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + unreachable: false, + backedUpDirs: [], + failedDirs: ["state"], + }); + expect(result.manifest?.backedUpDirs).toEqual([]); + expect(fs.existsSync(path.join(result.manifest!.backupPath, "state"))).toBe(false); + expectProbeAuditAndBinaryTarRequests(); + }); + + it.each([ + ["LF", "workspace-line\nfeed"], + ["CR", "workspace-carriage\rreturn"], + ])("fails closed when discovery returns a directory name containing %s", async (_kind, name) => { + const discoveryOutput = Buffer.from(`state\0${name}\0`, "utf8"); + expect(parseSandboxDirectoryNameList(discoveryOutput)).toEqual({ + ok: false, + error: "sandbox directory name list contains an unsafe CR/LF path", + }); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + ...completed(), + stdoutBytes: discoveryOutput, + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + backedUpDirs: [], + failedDirs: ["state"], + error: "sandbox directory name list contains an unsafe CR/LF path", + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).toHaveBeenCalledOnce(); + }); + + it("executes discovery successfully when a declared directory is absent", () => { + const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-directory-discovery-")); + try { + fs.mkdirSync(path.join(root, "present")); + fs.mkdirSync(path.join(root, "workspace-dynamic")); + const input = buildSandboxDirectoryNameList(["present", "missing"]); + expect(input).toMatchObject({ ok: true }); + assert.ok(input.ok); + + const result = spawnSync("sh", ["-c", buildSandboxDirectoryDiscoveryCommand(root)], { + input: input.input, + encoding: null, + }); + + expect(result.status).toBe(0); + expect(parseSandboxDirectoryNameList(Buffer.from(result.stdout ?? ""))).toMatchObject({ + ok: true, + names: ["present", "workspace-dynamic"], + }); + } finally { + fs.rmSync(root, { recursive: true, force: true }); + } + }); + + it("backs up 95 long workspace directories without oversized gRPC argv", async () => { + const names = Array.from({ length: 95 }, (_, index) => { + const prefix = `workspace-${String(index).padStart(3, "0")}-`; + return `${prefix}${"x".repeat(200 - prefix.length)}`; + }); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_DIR }, + expectedVersion: null, + stateDirs: names, + stateFiles: [], + }); + const { archive } = createBinaryTarArchive(names); + queueSuccessfulProbeAndAudit(names); + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + ...completed(), + stdoutBytes: archive, + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: true, + backedUpDirs: names, + failedDirs: [], + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).toHaveBeenCalledTimes(3); + const calls = mocks.execSandboxReadOnlyWithGrpcFallback.mock.calls; + for (const [, request] of calls) { + expect(validateOpenShellExecRequest(request)).toBeNull(); + } + const encoded = buildSandboxDirectoryNameList(names); + expect(encoded).toMatchObject({ ok: true }); + assert.ok(encoded.ok); + const auditInput = buildSandboxDirectoryAuditInput(STATE_DIR, names); + expect(auditInput).toMatchObject({ ok: true }); + assert.ok(auditInput.ok); + expect(encoded.input.length).toBeLessThanOrEqual(MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES); + expect(calls[0][1].stdin).toEqual(encoded.input); + expect(calls[1][1].stdin).toEqual(auditInput.input); + expect(calls[2][1].stdin).toEqual(encoded.input); + }); + + it("fails closed before discovery when the declared NUL list exceeds the request budget", async () => { + const names = Array.from({ length: 5_500 }, (_, index) => { + const prefix = `state-${String(index).padStart(4, "0")}-`; + return `${prefix}${"x".repeat(200 - prefix.length)}`; + }); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_DIR }, + expectedVersion: null, + stateDirs: names, + stateFiles: [], + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + backedUpDirs: [], + failedDirs: names, + error: expect.stringContaining("directory name list exceeds"), + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).not.toHaveBeenCalled(); + }); + + it("fails closed before audit when the discovered NUL list exceeds the request budget", async () => { + mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ + ...completed(), + stdoutBytes: Buffer.alloc(MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES + 1, 0x61), + }); + + const result = await backupSandboxState("alpha"); + + expect(result).toMatchObject({ + success: false, + backedUpDirs: [], + failedDirs: ["state"], + error: expect.stringContaining("directory name list exceeds"), + }); + expect(mocks.execSandboxReadOnlyWithGrpcFallback).toHaveBeenCalledOnce(); + }); +}); diff --git a/src/lib/state/sandbox-state-file-backup.test.ts b/src/lib/state/sandbox-state-file-backup.test.ts new file mode 100644 index 00000000000..bed1677fba1 --- /dev/null +++ b/src/lib/state/sandbox-state-file-backup.test.ts @@ -0,0 +1,221 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; +import { findMultilineExecArg } from "../actions/sandbox/exec"; + +const execReadOnly = vi.hoisted(() => vi.fn()); +const getSandbox = vi.hoisted(() => vi.fn()); +const loadAgent = vi.hoisted(() => vi.fn()); + +vi.mock("../adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: execReadOnly, +})); +vi.mock("./registry.js", () => ({ getSandbox })); +vi.mock("../agent/defs.js", () => ({ loadAgent })); + +const ORIGINAL_HOME = process.env.HOME; +const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-file-backup-")); +process.env.HOME = TMP_HOME; + +const { + backupSandboxState, + buildStateFileBackupExecRequest, + classifyStateFileBackupExecResult, + isSandboxExecTransportFailure, + SQLITE_BACKUP_PY, +} = await import("./sandbox"); + +afterAll(() => { + ORIGINAL_HOME === undefined + ? Reflect.deleteProperty(process.env, "HOME") + : Reflect.set(process.env, "HOME", ORIGINAL_HOME); + fs.rmSync(TMP_HOME, { force: true, recursive: true }); +}); + +beforeEach(() => { + vi.clearAllMocks(); + fs.rmSync(path.join(TMP_HOME, ".nemoclaw"), { force: true, recursive: true }); + getSandbox.mockReturnValue({ + name: "hermes", + agent: "hermes", + policies: [], + gatewayName: "nemoclaw", + }); + loadAgent.mockReturnValue({ + configPaths: { dir: "/sandbox/.hermes" }, + expectedVersion: null, + stateDirs: [], + stateFiles: [{ path: "runtime/state.db", strategy: "copy" }], + }); +}); + +describe("state-file backup exec request", () => { + it("streams the SQLite program through stdin and keeps every command argument single-line", () => { + const request = buildStateFileBackupExecRequest("hermes", "/sandbox/.hermes", { + path: "runtime/state.db", + strategy: "sqlite_backup", + }); + + expect(request.command).toEqual([ + "sh", + "-c", + expect.stringContaining('python3 - "$src" "$tmp"'), + ]); + expect(request.command.every((argument) => !/[\r\n]/.test(argument))).toBe(true); + expect(findMultilineExecArg(request.command)).toBe(-1); + expect(request.command.join("\n")).not.toContain("sqlite3.connect"); + expect(request.command.join("\n")).toContain('python3 - "$src" "$tmp" || exit $?'); + expect(request.stdin).toBe(SQLITE_BACKUP_PY); + expect(SQLITE_BACKUP_PY).toContain("sqlite3.connect"); + expect(SQLITE_BACKUP_PY).toContain("src_conn.backup(dst_conn)"); + expect(SQLITE_BACKUP_PY).toContain("PRAGMA quick_check"); + expect(request).toMatchObject({ + sandboxName: "hermes", + timeoutMs: 120_000, + maxOutputBytes: 256 * 1024 * 1024, + stdoutEncoding: "buffer", + }); + }); + + it("does not attach the SQLite program to copy requests", () => { + const request = buildStateFileBackupExecRequest("hermes", "/sandbox/.hermes", { + path: "SOUL.md", + strategy: "copy", + }); + + expect(request.command).toEqual(["sh", "-c", expect.stringContaining('cat -- "$src"')]); + expect(request).not.toHaveProperty("stdin"); + }); + + it("does not emit a temporary database when the streamed Python backup fails", () => { + const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-sqlite-backup-failure-")); + try { + fs.writeFileSync(path.join(tempDir, "state.db"), "source"); + const request = buildStateFileBackupExecRequest("hermes", tempDir, { + path: "state.db", + strategy: "sqlite_backup", + }); + const failingProgram = [ + "import pathlib, sys", + "pathlib.Path(sys.argv[2]).write_bytes(b'partial-backup')", + "raise SystemExit(41)", + ].join("\n"); + + const result = spawnSync("sh", request.command.slice(1), { + encoding: "utf8", + input: failingProgram, + }); + + expect(result.status).toBe(41); + expect(result.stdout).toBe(""); + expect(result.stderr).toBe(""); + } finally { + fs.rmSync(tempDir, { force: true, recursive: true }); + } + }); + + it("accepts only an error-free binary result as a completed backup", () => { + const bytes = Buffer.from([0, 255, 128, 10]); + expect( + classifyStateFileBackupExecResult({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + }), + ).toBe("backed_up"); + expect( + classifyStateFileBackupExecResult({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + error: new Error("stream failed"), + }), + ).toBe("failed"); + expect( + classifyStateFileBackupExecResult({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + signal: "SIGTERM", + }), + ).toBe("failed"); + expect( + classifyStateFileBackupExecResult({ + status: 2, + stdout: "", + stderr: "", + error: new Error("lookup failed"), + }), + ).toBe("failed"); + expect(classifyStateFileBackupExecResult({ status: 0, stdout: "", stderr: "" })).toBe("failed"); + }); + + it("does not classify terminal local validation and output limits as unreachable", () => { + const outputLimit = Object.assign(new Error("output limit"), { code: "ENOBUFS" }); + const invalidRequest = Object.assign(new Error("invalid request"), { + code: "OPENSHELL_EXEC_INVALID_ARGUMENT", + }); + + expect(isSandboxExecTransportFailure({ status: null, error: outputLimit })).toBe(false); + expect(isSandboxExecTransportFailure({ status: null, error: invalidRequest })).toBe(false); + expect(isSandboxExecTransportFailure({ status: null, error: new Error("UNAVAILABLE") })).toBe( + true, + ); + expect(isSandboxExecTransportFailure({ status: null, signal: "SIGKILL" })).toBe(true); + }); + + it("persists binary state-file bytes with private mode and complete backup bookkeeping", async () => { + const bytes = Buffer.from([0x53, 0x51, 0x4c, 0x00, 0xff, 0xfe, 0x80, 0x0a]); + execReadOnly.mockResolvedValue({ + status: 0, + stdout: "", + stdoutBytes: bytes, + stderr: "", + }); + + const result = await backupSandboxState("hermes", { name: "binary-state" }); + + expect(result).toMatchObject({ + success: true, + backedUpDirs: [], + failedDirs: [], + backedUpFiles: ["runtime/state.db"], + failedFiles: [], + }); + expect(result.manifest?.stateFiles).toEqual([{ path: "runtime/state.db", strategy: "copy" }]); + const persistedPath = path.join(result.manifest!.backupPath, "runtime", "state.db"); + expect(fs.readFileSync(persistedPath)).toEqual(bytes); + expect(fs.statSync(persistedPath).mode & 0o777).toBe(0o600); + expect(execReadOnly).toHaveBeenCalledWith( + "nemoclaw", + expect.objectContaining({ + sandboxName: "hermes", + stdoutEncoding: "buffer", + }), + ); + }); + + it("fails closed when a successful state-file exec omits binary stdout", async () => { + execReadOnly.mockResolvedValue({ status: 0, stdout: "", stderr: "" }); + + const result = await backupSandboxState("hermes", { name: "missing-binary-state" }); + + expect(result).toMatchObject({ + success: false, + backedUpFiles: [], + failedFiles: ["runtime/state.db"], + unreachable: false, + }); + expect(fs.existsSync(path.join(result.manifest!.backupPath, "runtime", "state.db"))).toBe( + false, + ); + }); +}); diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index 09aa0c7d5e7..6bb4057afe0 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -27,6 +27,12 @@ import { spawnSync } from "child_process"; import { captureSandboxSshConfigCommand } from "../adapters/openshell/client.js"; import { resolveOpenshell } from "../adapters/openshell/resolve.js"; +import { + type SandboxExecRequest, + type SandboxExecResult, + validateOpenShellExecRequest, +} from "../adapters/openshell/sandbox-control.js"; +import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing.js"; import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts.js"; import type { AgentStateFile } from "../agent/defs.js"; import { loadAgent } from "../agent/defs.js"; @@ -35,6 +41,7 @@ import { BACKUP_FAILURE_ABSENT_AFTER_EXTRACTION, classifyFailedDirsFromTarStderr, } from "../domain/backup-failure.js"; +import { resolveSandboxGatewayName } from "../onboard/gateway-binding.js"; import { shellQuote } from "../runner.js"; import { createTempSshConfig } from "../sandbox/temp-ssh-config.js"; import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; @@ -52,13 +59,17 @@ import { } from "./openclaw-plugin-restore.js"; import type { CustomPolicyEntry } from "./registry.js"; import * as registry from "./registry.js"; -import { isSshTransportFailure } from "./ssh-transport.js"; import { restoreStateFile } from "./state-file-restore.js"; import { runTarListing } from "./tar-listing.js"; const HOME_DIR = path.resolve(process.env.HOME || os.homedir()); const REBUILD_BACKUPS_DIR = path.join(HOME_DIR, ".nemoclaw", "rebuild-backups"); +/** Conservative budget below v0.0.72's decoded ExecSandbox request limit. */ +export const MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES = 512 * 1024; +/** Bound diagnostics emitted by the pre-backup filesystem audit. */ +export const MAX_SANDBOX_DIRECTORY_AUDIT_BYTES = 4 * 1024 * 1024; +export const MAX_SANDBOX_DIRECTORY_AUDIT_ENTRIES = 16 * 1024; const MANIFEST_VERSION = 1; export const OPENCLAW_IMAGE_PLUGIN_PROVENANCE_RESTORE_ERROR = "custom-image OpenClaw plugin provenance is missing or invalid"; @@ -147,9 +158,8 @@ export interface BackupResult { error?: string; backedUpFiles: string[]; failedFiles: string[]; - // Set when a failure stems from an SSH transport failure against a running - // sandbox (see isSshTransportFailure), as opposed to an audit rejection or - // a partial tar read error. + // Set when a failure stems from a sandbox exec transport failure against a + // running sandbox, as opposed to an audit rejection or partial tar read. unreachable?: boolean; } @@ -683,6 +693,268 @@ function isSafeStateDirPath(dirPath: string): boolean { ); } +export type SandboxDirectoryNameListResult = + | { ok: true; names: string[]; input: Buffer } + | { ok: false; error: string }; + +export function buildSandboxDirectoryNameList( + names: readonly string[], +): SandboxDirectoryNameListResult { + const uniqueNames: string[] = []; + const chunks: Buffer[] = []; + const seen = new Set(); + let totalBytes = 0; + for (const name of names) { + if (seen.has(name)) continue; + if (name.includes("\r") || name.includes("\n")) { + return { + ok: false, + error: "sandbox directory name list contains an unsafe CR/LF path", + }; + } + if (!isSafeStateDirPath(name)) { + return { ok: false, error: "sandbox directory discovery returned an unsafe path" }; + } + const encodedName = Buffer.from(name, "utf8"); + if (encodedName.toString("utf8") !== name) { + return { ok: false, error: "sandbox directory discovery returned invalid UTF-8" }; + } + totalBytes += encodedName.length + 1; + if (totalBytes > MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES) { + return { + ok: false, + error: `sandbox directory name list exceeds ${String(MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES)} bytes`, + }; + } + seen.add(name); + uniqueNames.push(name); + chunks.push(encodedName, Buffer.from([0])); + } + return { ok: true, names: uniqueNames, input: Buffer.concat(chunks, totalBytes) }; +} + +export function parseSandboxDirectoryNameList(output: Buffer): SandboxDirectoryNameListResult { + if (output.length > MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES) { + return { + ok: false, + error: `sandbox directory name list exceeds ${String(MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES)} bytes`, + }; + } + if (output.length === 0) return { ok: true, names: [], input: Buffer.alloc(0) }; + if (output.at(-1) !== 0) { + return { ok: false, error: "sandbox directory discovery returned a truncated name list" }; + } + + const decoder = new TextDecoder("utf-8", { fatal: true }); + const names: string[] = []; + let start = 0; + try { + for (let index = 0; index < output.length; index += 1) { + if (output[index] !== 0) continue; + if (index === start) { + return { ok: false, error: "sandbox directory discovery returned an empty path" }; + } + names.push(decoder.decode(output.subarray(start, index))); + start = index + 1; + } + } catch { + return { ok: false, error: "sandbox directory discovery returned invalid UTF-8" }; + } + return buildSandboxDirectoryNameList(names); +} + +export function buildSandboxDirectoryDiscoveryCommand(dir: string): string { + const root = shellQuote(dir); + const declared = + "xargs -0 -r sh -c 'for name do " + + 'if [ -d "$root/$name" ]; then printf "%s\\0" "$name"; fi; done\' sh'; + const workspaces = + 'for d in "$root"/workspace-*/; do ' + + '[ -d "$d" ] || continue; d="${d%/}"; printf \'%s\\0\' "${d##*/}"; done 2>/dev/null'; + return `root=${root}; export root; ${declared} || exit $?; ${workspaces}`; +} + +export type SandboxDirectoryAuditInputResult = + | { ok: true; input: Buffer } + | { ok: false; error: string }; + +export interface SandboxDirectoryAuditEntry { + type: "l" | "f" | "b" | "c" | "p" | "s" | "D"; + path: string; + linkTarget: string; +} + +export type SandboxDirectoryAuditResult = + | { ok: true; entries: SandboxDirectoryAuditEntry[] } + | { ok: false; error: string }; + +const SANDBOX_DIRECTORY_AUDIT_TYPES = new Set([ + "l", + "f", + "b", + "c", + "p", + "s", + "D", +]); + +function normalizedAbsoluteSandboxRoot(root: string): string | null { + if (!root || root.includes("\0") || !path.posix.isAbsolute(root)) return null; + const withoutTrailingSlash = root === "/" ? root : root.replace(/\/+$/, ""); + const normalized = path.posix.normalize(withoutTrailingSlash); + return normalized === withoutTrailingSlash ? normalized : null; +} + +export function buildSandboxDirectoryAuditInput( + root: string, + names: readonly string[], +): SandboxDirectoryAuditInputResult { + const normalizedRoot = normalizedAbsoluteSandboxRoot(root); + if (!normalizedRoot) { + return { ok: false, error: "sandbox directory audit has an invalid root" }; + } + + const chunks: Buffer[] = []; + let totalBytes = 0; + for (const name of names) { + if (!isSafeStateDirPath(name)) { + return { ok: false, error: "sandbox directory audit has an invalid state directory" }; + } + const absoluteName = `${normalizedRoot === "/" ? "" : normalizedRoot}/${name}`; + const encodedName = Buffer.from(absoluteName, "utf8"); + totalBytes += encodedName.length + 1; + if (totalBytes > MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES) { + return { + ok: false, + error: `sandbox directory audit input exceeds ${String(MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES)} bytes`, + }; + } + chunks.push(encodedName, Buffer.from([0])); + } + return { ok: true, input: Buffer.concat(chunks, totalBytes) }; +} + +export function parseSandboxDirectoryAudit( + output: Buffer, + root: string, + expectedDirs: readonly string[], +): SandboxDirectoryAuditResult { + if (output.length > MAX_SANDBOX_DIRECTORY_AUDIT_BYTES) { + return { + ok: false, + error: `sandbox directory audit exceeds ${String(MAX_SANDBOX_DIRECTORY_AUDIT_BYTES)} bytes`, + }; + } + if (output.length === 0) return { ok: true, entries: [] }; + if (output.at(-1) !== 0) { + return { ok: false, error: "sandbox directory audit returned a truncated record" }; + } + + let fieldCount = 0; + for (const byte of output) { + if (byte === 0) fieldCount += 1; + } + if (fieldCount % 3 !== 0) { + return { ok: false, error: "sandbox directory audit returned an incomplete record" }; + } + const entryCount = fieldCount / 3; + if (entryCount > MAX_SANDBOX_DIRECTORY_AUDIT_ENTRIES) { + return { + ok: false, + error: `sandbox directory audit exceeds ${String(MAX_SANDBOX_DIRECTORY_AUDIT_ENTRIES)} entries`, + }; + } + + const normalizedRoot = normalizedAbsoluteSandboxRoot(root); + if (!normalizedRoot || expectedDirs.some((dirName) => !isSafeStateDirPath(dirName))) { + return { ok: false, error: "sandbox directory audit has an invalid root contract" }; + } + const rootPrefix = normalizedRoot === "/" ? "/" : `${normalizedRoot}/`; + const decoder = new TextDecoder("utf-8", { fatal: true }); + const fields: string[] = []; + let fieldStart = 0; + try { + for (let index = 0; index < output.length; index += 1) { + if (output[index] !== 0) continue; + fields.push(decoder.decode(output.subarray(fieldStart, index))); + fieldStart = index + 1; + } + } catch { + return { ok: false, error: "sandbox directory audit returned invalid UTF-8" }; + } + + const entries: SandboxDirectoryAuditEntry[] = []; + for (let index = 0; index < fields.length; index += 3) { + const rawType = fields[index]; + const entryPath = fields[index + 1]; + const linkTarget = fields[index + 2]; + if (!SANDBOX_DIRECTORY_AUDIT_TYPES.has(rawType as SandboxDirectoryAuditEntry["type"])) { + return { ok: false, error: "sandbox directory audit returned an invalid file type" }; + } + if ( + !entryPath || + !entryPath.startsWith(rootPrefix) || + path.posix.normalize(entryPath) !== entryPath + ) { + return { ok: false, error: "sandbox directory audit returned a path outside its root" }; + } + const relativePath = entryPath.slice(rootPrefix.length); + if ( + !expectedDirs.some( + (dirName) => relativePath === dirName || relativePath.startsWith(`${dirName}/`), + ) + ) { + return { + ok: false, + error: "sandbox directory audit returned a path outside its expected state directories", + }; + } + if ((rawType === "l" && !linkTarget) || (rawType !== "l" && linkTarget)) { + return { ok: false, error: "sandbox directory audit returned an invalid link target field" }; + } + entries.push({ + type: rawType as SandboxDirectoryAuditEntry["type"], + path: entryPath, + linkTarget, + }); + } + return { ok: true, entries }; +} + +export function buildSandboxDirectoryAuditCommand(): string { + return ( + "xargs -0 -r sh -c 'for root do " + + 'find "$root" \\( -type l -o \\( -type f -a -links +1 \\) -o ' + + '\\( ! -type f -a ! -type d \\) \\) -printf "%y\\0%p\\0%l\\0" || exit $?; done\' sh' + ); +} + +export function buildSandboxDirectoryTarCommand(dir: string): string { + return `tar -cf - -C ${shellQuote(dir)} --null --verbatim-files-from --files-from=-`; +} + +type ReadOnlySandboxExecResult = Awaited>; + +function sandboxExecFailed(result: ReadOnlySandboxExecResult): boolean { + return result.status !== 0 || Boolean(result.error) || Boolean(result.signal); +} + +function sandboxExecFailureDetail(result: ReadOnlySandboxExecResult): string { + return ( + result.stderr.trim() || + result.error?.message || + (result.signal ? `signal ${result.signal}` : `exit ${String(result.status)}`) + ); +} + +function sandboxDirectoryRequestValidationError( + request: SandboxExecRequest, + operation: string, +): string | null { + const error = validateOpenShellExecRequest(request); + return error ? `${operation}: ${error.message}` : null; +} + function isStateDirArray(value: unknown): value is string[] { return isStringArray(value) && value.every(isSafeStateDirPath); } @@ -743,7 +1015,8 @@ function stateFileRemotePath(dir: string, filePath: string): string { return `${dir.replace(/\/+$/, "")}/${filePath}`; } -const SQLITE_BACKUP_PY = [ +/** @internal Exported so the transport-boundary test can pin the exact stdin payload. */ +export const SQLITE_BACKUP_PY = [ "import sqlite3, sys", "src, dst = sys.argv[1], sys.argv[2]", "src_conn = sqlite3.connect('file:' + src + '?mode=ro', uri=True, timeout=30)", @@ -771,7 +1044,7 @@ function buildStateFileBackupCommand(dir: string, spec: StateFileSpec): string { '[ "${hardlink_count:-0}" = "0" ] || { echo "hard-linked sqlite state file rejected: $src" >&2; exit 11; }', 'tmp="$(mktemp /tmp/nemoclaw-sqlite-backup.XXXXXX)"', "trap 'rm -f \"$tmp\"' EXIT", - `python3 -c ${shellQuote(SQLITE_BACKUP_PY)} "$src" "$tmp"`, + 'python3 - "$src" "$tmp" || exit $?', 'cat -- "$tmp"', ].join("; "); } @@ -786,41 +1059,83 @@ function buildStateFileBackupCommand(dir: string, spec: StateFileSpec): string { ].join("; "); } -type StateFileBackupOutcome = "backed_up" | "missing" | "failed"; +/** @internal Exported to pin the state-file transport contract in focused tests. */ +export function buildStateFileBackupExecRequest( + sandboxName: string, + dir: string, + spec: StateFileSpec, +): SandboxExecRequest { + return { + sandboxName, + command: ["sh", "-c", buildStateFileBackupCommand(dir, spec)], + ...(spec.strategy === "sqlite_backup" ? { stdin: SQLITE_BACKUP_PY } : {}), + timeoutMs: 120_000, + maxOutputBytes: 256 * 1024 * 1024, + stdoutEncoding: "buffer", + }; +} + +export type StateFileBackupOutcome = "backed_up" | "missing" | "failed"; interface StateFileBackupResult { outcome: StateFileBackupOutcome; - // Set on "failed" when the SSH probe itself failed at the transport level - // (exit 255, signal-killed, spawn error). The caller (backupSandboxState) - // propagates this into BackupResult.unreachable so that + // Set on "failed" when sandbox exec itself failed at the transport level. + // The caller propagates this into BackupResult.unreachable so that // NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 activates for state-file // failures too, not only the initial dir probe. See #6188. unreachable: boolean; } -function backupStateFile( - configFile: string, +/** @internal Distinguish remote reachability failures from terminal local request failures. */ +export function isSandboxExecTransportFailure(result: { + status: number | null; + error?: Error; + signal?: NodeJS.Signals | null; +}): boolean { + const code = (result.error as NodeJS.ErrnoException | undefined)?.code; + // Both transports use ENOBUFS for the shared raw-output cap. The canonical + // request validator uses OPENSHELL_EXEC_INVALID_ARGUMENT. Neither can be + // repaired by retrying or by treating the sandbox as unreachable. + if (code === "ENOBUFS" || code === "OPENSHELL_EXEC_INVALID_ARGUMENT") return false; + return Boolean(result.error || result.signal || result.status === null); +} + +/** @internal Pin the binary state-file result contract independently of filesystem writes. */ +export function classifyStateFileBackupExecResult( + result: SandboxExecResult, +): StateFileBackupOutcome { + if (result.error || result.signal) return "failed"; + if (result.status === 2) return "missing"; + if (result.status !== 0 || !result.stdoutBytes) return "failed"; + return "backed_up"; +} + +async function backupStateFile( + gatewayName: string, sandboxName: string, dir: string, spec: StateFileSpec, backupPath: string, -): StateFileBackupResult { - const command = buildStateFileBackupCommand(dir, spec); +): Promise { _log(`Backing up state file ${spec.path} (${spec.strategy})`); - const result = spawnSync("ssh", [...sshArgs(configFile, sandboxName), command], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 120000, - maxBuffer: 256 * 1024 * 1024, - }); + const result = await execSandboxReadOnlyWithGrpcFallback( + gatewayName, + buildStateFileBackupExecRequest(sandboxName, dir, spec), + ); - if (result.status === 2) return { outcome: "missing", unreachable: false }; - if (result.status !== 0 || result.error || result.signal || !result.stdout) { + const outcome = classifyStateFileBackupExecResult(result); + if (outcome === "missing") return { outcome, unreachable: false }; + if (outcome === "failed") { const detail = - (result.stderr?.toString() || "").trim() || + result.stderr.trim() || result.error?.message || - (result.signal ? `signal ${result.signal}` : `exit ${String(result.status)}`); + (result.signal + ? `signal ${result.signal}` + : result.status === 0 + ? "binary stdout was not preserved" + : `exit ${String(result.status)}`); _log(`FAILED: state file backup ${spec.path}: ${detail.substring(0, 200)}`); - return { outcome: "failed", unreachable: isSshTransportFailure(result) }; + return { outcome: "failed", unreachable: isSandboxExecTransportFailure(result) }; } const localPath = path.join(backupPath, spec.path); @@ -828,7 +1143,12 @@ function backupStateFile( rejectSymlinksOnPath(parent); mkdirSync(parent, { recursive: true, mode: 0o700 }); rejectSymlinksOnPath(localPath); - writeFileSync(localPath, result.stdout); + const stdoutBytes = result.stdoutBytes; + if (!stdoutBytes) { + _log(`FAILED: state file backup ${spec.path}: binary stdout was not preserved`); + return { outcome: "failed", unreachable: false }; + } + writeFileSync(localPath, stdoutBytes); chmodSync(localPath, 0o600); return { outcome: "backed_up", unreachable: false }; } @@ -840,13 +1160,13 @@ function backupStateFile( * Uses the agent manifest to determine which directories contain state. */ +export { isSshTransportFailure } from "./ssh-transport.js"; export { buildStateFileRestoreCommand } from "./state-file-restore.js"; -// isSshTransportFailure lives in ./ssh-transport now. Re-exported here for -// backwards compatibility with callers that used to import it from this -// module. Prefer importing directly from ./ssh-transport in new code. -export { isSshTransportFailure }; -export function backupSandboxState(sandboxName: string, options: BackupOptions = {}): BackupResult { +export async function backupSandboxState( + sandboxName: string, + options: BackupOptions = {}, +): Promise { const sb = registry.getSandbox(sandboxName); const agentName = sb?.agent || "openclaw"; const agent = loadAgent(agentName); @@ -969,15 +1289,12 @@ export function backupSandboxState(sandboxName: string, options: BackupOptions = return { success: true, manifest, backedUpDirs, failedDirs, backedUpFiles, failedFiles }; } - // SSH+tar single-roundtrip download - _log("Getting SSH config via openshell sandbox ssh-config"); - const sshConfig = getSshConfig(sandboxName); - if (!sshConfig) { - _log("FAILED: Could not get SSH config"); - // For a sandbox the registry reported as running, an unreachable - // `openshell sandbox ssh-config` lookup is a transport-level failure — - // treat it the same as the initial dir probe and propagate `unreachable` - // so NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 can activate. (#6188) + let gatewayName: string; + try { + gatewayName = resolveSandboxGatewayName(sb); + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + _log(`FAILED: Could not resolve sandbox gateway: ${detail}`); return { success: false, manifest, @@ -985,250 +1302,325 @@ export function backupSandboxState(sandboxName: string, options: BackupOptions = failedDirs: [...stateDirs], backedUpFiles, failedFiles: stateFiles.map((f) => f.path), - unreachable: true, + error: detail, }; } - _log(`SSH config obtained (${sshConfig.length} bytes)`); - const tempSshConfig = createTempSshConfig(sshConfig, "nemoclaw-state-"); - const configFile = tempSshConfig.file; - try { - if (stateDirs.length > 0) { - // Build tar command that only includes existing directories. - // First, check which declared state dirs actually exist in the sandbox, - // then additionally discover per-agent `workspace-*` directories produced - // by multi-agent OpenClaw deployments (see issue #1260) so they get - // snapshotted alongside the manifest-declared dirs. `awk '!seen[$0]++'` - // dedupes while preserving order. - const existCheckCmd = stateDirs - .map((d) => `[ -d ${shellQuote(`${dir}/${d}`)} ] && printf '%s\\n' ${shellQuote(d)}`) - .join("; "); - const workspaceGlobCmd = `for d in ${shellQuote(dir)}/workspace-*/; do [ -d "$d" ] && basename "$d"; done 2>/dev/null`; - const fullCheckCmd = `{ ${existCheckCmd}; ${workspaceGlobCmd}; } 2>/dev/null | awk '!seen[$0]++'`; - _log(`Checking existing dirs via SSH: ${fullCheckCmd.substring(0, 100)}...`); - const existResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), fullCheckCmd], { - encoding: "utf-8", - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - }); - _log( - `Dir check: exit=${existResult.status}, stdout=${(existResult.stdout || "").trim().substring(0, 200)}, stderr=${(existResult.stderr || "").trim().substring(0, 200)}`, - ); - const existingDirs = (existResult.stdout || "") - .trim() - .split("\n") - .filter((d) => d.length > 0); - _log( - `Existing dirs in sandbox: [${existingDirs.join(",")}] (${existingDirs.length}/${stateDirs.length})`, - ); + if (stateDirs.length > 0) { + // Keep sandbox-controlled names out of argv. The same bounded NUL list is + // reused by discovery and tar so high-cardinality backups have constant + // command size and names containing CR/LF cannot alter shell syntax. + const declaredDirectoryNames = buildSandboxDirectoryNameList(stateDirs); + if (!declaredDirectoryNames.ok) { + _log(`FAILED: ${declaredDirectoryNames.error}`); + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...stateDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: declaredDirectoryNames.error, + }; + } + const fullCheckCmd = buildSandboxDirectoryDiscoveryCommand(dir); + const discoveryRequest: SandboxExecRequest = { + sandboxName, + command: ["sh", "-c", fullCheckCmd], + stdin: declaredDirectoryNames.input, + timeoutMs: 30_000, + maxOutputBytes: MAX_SANDBOX_DIRECTORY_NAME_LIST_BYTES + 1, + stdoutEncoding: "buffer", + }; + const discoveryValidationError = sandboxDirectoryRequestValidationError( + discoveryRequest, + "sandbox directory discovery request", + ); + if (discoveryValidationError) { + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...stateDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: discoveryValidationError, + }; + } + _log(`Checking existing dirs via OpenShell: ${fullCheckCmd.substring(0, 100)}...`); + const existResult = await execSandboxReadOnlyWithGrpcFallback(gatewayName, discoveryRequest); + _log( + `Dir check: exit=${existResult.status}, stdout=${String(existResult.stdoutBytes?.length ?? 0)} bytes, stderr=${existResult.stderr.trim().substring(0, 200)}`, + ); - if (existResult.status !== 0) { - _log( - `FAILED: SSH dir check exited ${existResult.status} — cannot determine which dirs exist`, - ); + if (sandboxExecFailed(existResult) || !existResult.stdoutBytes) { + const detail = sandboxExecFailureDetail(existResult); + _log(`FAILED: sandbox dir check failed (${detail}) — cannot determine which dirs exist`); + return { + success: false, + unreachable: isSandboxExecTransportFailure(existResult), + manifest, + backedUpDirs, + failedDirs: [...stateDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + }; + } + + const parsedDirectoryNames = parseSandboxDirectoryNameList(existResult.stdoutBytes); + if (!parsedDirectoryNames.ok) { + _log(`FAILED: ${parsedDirectoryNames.error}`); + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...stateDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: parsedDirectoryNames.error, + }; + } + const existingDirs = parsedDirectoryNames.names; + const directoryNameInput = parsedDirectoryNames.input; + _log( + `Existing dirs in sandbox: [${existingDirs.join(",")}] (${existingDirs.length}/${stateDirs.length})`, + ); + + if (existingDirs.length === 0) { + _log("No state dirs found in sandbox (all empty)"); + } else { + // NC-2227-04: Pre-backup audit — reject symlinks, hardlinks, and special + // files inside state dirs. A compromised agent could plant a symlink like + // workspace/copy -> ../openclaw.json to exfiltrate config via backup. + // + // The audit is a bounded NUL protocol of , , and + // triples. Filesystem names may contain tabs or newlines, + // so a text line protocol is not safe at this trust boundary. xargs + // turns the separate absolute-path NUL list into positional parameters, + // keeping names out of shell syntax while remaining compatible with + // sandbox images whose GNU find predates -files0-from. Each find failure + // aborts the audit before any archive is requested. + const auditInput = buildSandboxDirectoryAuditInput(dir, existingDirs); + if (!auditInput.ok) { return { success: false, - unreachable: isSshTransportFailure(existResult), manifest, backedUpDirs, - failedDirs: [...stateDirs], + failedDirs: [...existingDirs], backedUpFiles, failedFiles: stateFiles.map((f) => f.path), + error: auditInput.error, }; } - - if (existingDirs.length === 0) { - _log("No state dirs found in sandbox (all empty)"); - } else { - // NC-2227-04: Pre-backup audit — reject symlinks, hardlinks, and special - // files inside state dirs. A compromised agent could plant a symlink like - // workspace/copy -> ../openclaw.json to exfiltrate config via backup. - // - // The printf format emits "\t\t" — %l is - // empty for non-symlinks but always present, so the field count is - // stable. Tab separator assumes state-dir paths don't contain tabs, - // matching the wider convention in this file. - // Per-dir `find` invocations are joined with `;` (not `&&`) and each - // is tolerant of its own exit code via `|| true`. The base image bakes - // a few state subdirs as root-owned (e.g. `extensions/`, - // `agents/`) and `find` walking those from the sandbox-user SSH - // session exits 1 on permission denied. The audit's real signal is - // stdout (the printf-emitted symlink/hardlink/special-file rows); - // letting one perm-denied subdir abort the whole chain blocks legitimate - // rebuilds. - const auditCmd = existingDirs - .map( - (d) => - `{ find ${shellQuote(`${dir}/${d}`)} \\( -type l -o \\( -type f -a -links +1 \\) -o \\( ! -type f -a ! -type d \\) \\) -printf "%y\\t%p\\t%l\\n" 2>/dev/null || true; }`, - ) - .join("; "); - _log(`Pre-backup audit: checking for symlinks, hard links, and special files`); - const auditResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), auditCmd], { - encoding: "utf-8", - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - }); - if (auditResult.status !== 0) { - const stderr = (auditResult.stderr || "").trim(); - const detail = - stderr || auditResult.error?.message || `exit ${String(auditResult.status)}`; - _log(`FAILED: Pre-backup audit command failed — ${detail}`); + const auditCmd = buildSandboxDirectoryAuditCommand(); + const auditRequest: SandboxExecRequest = { + sandboxName, + command: ["sh", "-c", auditCmd], + stdin: auditInput.input, + timeoutMs: 30_000, + maxOutputBytes: MAX_SANDBOX_DIRECTORY_AUDIT_BYTES + 1, + stdoutEncoding: "buffer", + }; + const auditValidationError = sandboxDirectoryRequestValidationError( + auditRequest, + "sandbox directory audit request", + ); + if (auditValidationError) { + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...existingDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: auditValidationError, + }; + } + _log(`Pre-backup audit: checking for symlinks, hard links, and special files`); + const auditResult = await execSandboxReadOnlyWithGrpcFallback(gatewayName, auditRequest); + if (sandboxExecFailed(auditResult)) { + const detail = sandboxExecFailureDetail(auditResult); + _log(`FAILED: Pre-backup audit command failed — ${detail}`); + return { + success: false, + unreachable: isSandboxExecTransportFailure(auditResult), + manifest, + backedUpDirs, + failedDirs: [...existingDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: `Pre-backup audit failed: ${detail}`, + }; + } + if (!auditResult.stdoutBytes) { + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...existingDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: "Pre-backup audit failed: binary stdout was not preserved", + }; + } + const parsedAudit = parseSandboxDirectoryAudit(auditResult.stdoutBytes, dir, existingDirs); + if (!parsedAudit.ok) { + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...existingDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: `Pre-backup audit rejected malformed output: ${parsedAudit.error}`, + }; + } + if (parsedAudit.entries.length > 0) { + const whitelisted: string[] = []; + const violations: string[] = []; + const dirPrefix = `${dir}/`; + for (const entry of parsedAudit.entries) { + const relPath = entry.path.slice(dirPrefix.length); + const description = `type=${entry.type} path=${JSON.stringify(entry.path)} target=${JSON.stringify(entry.linkTarget)}`; + if (entry.type === "l" && isAllowedStateSymlink(relPath, entry.linkTarget)) { + whitelisted.push(description); + } else { + violations.push(description); + } + } + if (whitelisted.length > 0) { + _log( + `Pre-backup audit whitelisted ${whitelisted.length} entries (image npm symlinks): ${whitelisted.slice(0, 5).join("; ")}`, + ); + } + if (violations.length > 0) { + // Non-whitelisted symlinks / hard links / special files — reject + _log( + `SECURITY: Pre-backup audit found ${violations.length} unsafe entries: ${violations.slice(0, 5).join("; ")}`, + ); return { success: false, - unreachable: isSshTransportFailure(auditResult), manifest, backedUpDirs, failedDirs: [...existingDirs], backedUpFiles, failedFiles: stateFiles.map((f) => f.path), - error: `Pre-backup audit failed: ${detail}`, + error: `Pre-backup audit rejected: symlinks, hard links, or special files found in state dirs: ${violations.slice(0, 3).join("; ")}`, }; } - const auditOutput = (auditResult.stdout || "").trim(); - if (auditOutput.length > 0) { - const allEntries = auditOutput.split("\n").filter((l) => l.length > 0); - const whitelisted: string[] = []; - const violations: string[] = []; - const dirPrefix = `${dir}/`; - for (const entry of allEntries) { - // find -printf "%y\t%p\t%l\n" → "\t\t" - // (linkTarget is empty for non-symlinks). - const parts = entry.split("\t"); - const type = parts[0] || ""; - const absPath = parts[1] || entry; - const linkTarget = parts[2] || ""; - const relPath = absPath.startsWith(dirPrefix) - ? absPath.slice(dirPrefix.length) - : absPath; - if (type === "l" && isAllowedStateSymlink(relPath, linkTarget)) { - whitelisted.push(entry); - } else { - violations.push(entry); - } - } - if (whitelisted.length > 0) { - _log( - `Pre-backup audit whitelisted ${whitelisted.length} entries (image npm symlinks): ${whitelisted.slice(0, 5).join("; ")}`, - ); - } - if (violations.length > 0) { - // Non-whitelisted symlinks / hard links / special files — reject - _log( - `SECURITY: Pre-backup audit found ${violations.length} unsafe entries: ${violations.slice(0, 5).join("; ")}`, - ); - return { - success: false, - manifest, - backedUpDirs, - failedDirs: [...existingDirs], - backedUpFiles, - failedFiles: stateFiles.map((f) => f.path), - error: `Pre-backup audit rejected: symlinks, hard links, or special files found in state dirs: ${violations.slice(0, 3).join("; ")}`, - }; - } - } - _log("Pre-backup audit passed — no unsafe symlinks, hard links, or special files found"); - - // Download via SSH+tar - // NC-2227-04: Removed -h flag (was following symlinks). State dirs are - // now agent-writable and co-located with config — a compromised agent - // could create symlinks to exfiltrate config contents via backup. - const tarCmd = `tar -cf - -C ${shellQuote(dir)} -- ${existingDirs.map(shellQuote).join(" ")}`; - _log(`Downloading via SSH+tar: ${tarCmd}`); - const result = spawnSync("ssh", [...sshArgs(configFile, sandboxName), tarCmd], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 120000, - maxBuffer: 256 * 1024 * 1024, - }); + } + _log("Pre-backup audit passed — no unsafe symlinks, hard links, or special files found"); + + // Download through OpenShell's binary-safe sandbox exec stream. + // NC-2227-04: Removed -h flag (was following symlinks). State dirs are + // now agent-writable and co-located with config — a compromised agent + // could create symlinks to exfiltrate config contents via backup. + const tarCmd = buildSandboxDirectoryTarCommand(dir); + const tarRequest: SandboxExecRequest = { + sandboxName, + command: ["sh", "-c", tarCmd], + stdin: directoryNameInput, + timeoutMs: 120_000, + maxOutputBytes: 256 * 1024 * 1024, + stdoutEncoding: "buffer", + }; + const tarValidationError = sandboxDirectoryRequestValidationError( + tarRequest, + "sandbox directory archive request", + ); + if (tarValidationError) { + return { + success: false, + manifest, + backedUpDirs, + failedDirs: [...existingDirs], + backedUpFiles, + failedFiles: stateFiles.map((f) => f.path), + error: tarValidationError, + }; + } + _log(`Downloading via OpenShell+tar: ${tarCmd}`); + const result = await execSandboxReadOnlyWithGrpcFallback(gatewayName, tarRequest); + _log( + `OpenShell+tar download: exit=${result.status}, stdout=${result.stdoutBytes ? result.stdoutBytes.length + " bytes" : "null"}, stderr=${result.stderr.substring(0, 200)}`, + ); + if (isSandboxExecTransportFailure(result)) unreachable = true; + + // GNU tar exit codes: 0 = success, 1 = files changed during archive, + // 2 = errors (e.g. permission denied) but archive still written to stdout. + // Accept exit 0, 1, or 2 when stdout has data — extract what tar produced + // and determine per-dir success from tar's reported read errors. + const tarExitedWithData = + Boolean(result.stdoutBytes?.length) && + !result.error && + !result.signal && + (result.status === 0 || result.status === 1 || result.status === 2); + + if (result.status !== 0 && result.stdoutBytes && result.stdoutBytes.length > 0) { _log( - `SSH+tar download: exit=${result.status}, stdout=${result.stdout ? result.stdout.length + " bytes" : "null"}, stderr=${(result.stderr?.toString() || "").substring(0, 200)}`, + `tar exited ${result.status} but produced ${result.stdoutBytes.length} bytes — attempting partial extraction`, ); - if (isSshTransportFailure(result)) unreachable = true; - - // GNU tar exit codes: 0 = success, 1 = files changed during archive, - // 2 = errors (e.g. permission denied) but archive still written to stdout. - // Accept exit 0, 1, or 2 when stdout has data — extract what tar produced - // and determine per-dir success from tar's reported read errors. - const tarExitedWithData = - result.stdout && - result.stdout.length > 0 && - (result.status === 0 || result.status === 1 || result.status === 2); - - if (result.status !== 0 && result.stdout && result.stdout.length > 0) { - _log( - `tar exited ${result.status} but produced ${result.stdout.length} bytes — attempting partial extraction`, - ); - } + } - if (tarExitedWithData) { - // SECURITY: Validate tar entries, extract safely, audit symlinks - const extractResult = safeTarExtract(result.stdout, backupPath); - if (extractResult.success) { - const extractedDirs = new Set(existingBackupDirs(backupPath, existingDirs)); - if (result.status === 0) { + if (tarExitedWithData && result.stdoutBytes) { + // SECURITY: Validate tar entries, extract safely, audit symlinks + const extractResult = safeTarExtract(result.stdoutBytes, backupPath); + if (extractResult.success) { + const extractedDirs = new Set(existingBackupDirs(backupPath, existingDirs)); + if (result.status === 0) { + for (const d of existingDirs) { + if (extractedDirs.has(d)) { + backedUpDirs.push(d); + } else { + _log(`Dir ${d} missing from clean tar extraction — marking failed`); + failedDirs.push(d); + failedDirReasons[d] = BACKUP_FAILURE_ABSENT_AFTER_EXTRACTION; + } + } + } else { + const tarFailedDirs = classifyFailedDirsFromTarStderr(result.stderr, existingDirs); + if (tarFailedDirs.size === 0) { + _log( + `tar exited ${result.status} without attributable failed dirs — marking all dirs failed`, + ); + failedDirs.push(...existingDirs); + } else { for (const d of existingDirs) { - if (extractedDirs.has(d)) { - backedUpDirs.push(d); - } else { - _log(`Dir ${d} missing from clean tar extraction — marking failed`); + const tarFailureReason = tarFailedDirs.get(d); + if (tarFailureReason !== undefined) { + _log(`Dir ${d} had tar read errors (${tarFailureReason}) — marking failed`); + failedDirs.push(d); + failedDirReasons[d] = tarFailureReason; + } else if (!extractedDirs.has(d)) { + _log(`Dir ${d} missing from partial tar extraction — marking failed`); failedDirs.push(d); failedDirReasons[d] = BACKUP_FAILURE_ABSENT_AFTER_EXTRACTION; - } - } - } else { - const tarFailedDirs = classifyFailedDirsFromTarStderr( - result.stderr?.toString() || "", - existingDirs, - ); - if (tarFailedDirs.size === 0) { - _log( - `tar exited ${result.status} without attributable failed dirs — marking all dirs failed`, - ); - failedDirs.push(...existingDirs); - } else { - for (const d of existingDirs) { - const tarFailureReason = tarFailedDirs.get(d); - if (tarFailureReason !== undefined) { - _log(`Dir ${d} had tar read errors (${tarFailureReason}) — marking failed`); - failedDirs.push(d); - failedDirReasons[d] = tarFailureReason; - } else if (!extractedDirs.has(d)) { - _log(`Dir ${d} missing from partial tar extraction — marking failed`); - failedDirs.push(d); - failedDirReasons[d] = BACKUP_FAILURE_ABSENT_AFTER_EXTRACTION; - } else { - backedUpDirs.push(d); - } + } else { + backedUpDirs.push(d); } } } - } else { - _log(`SECURITY: tar extraction blocked: ${extractResult.error}`); - failedDirs.push(...existingDirs); } } else { + _log(`SECURITY: tar extraction blocked: ${extractResult.error}`); failedDirs.push(...existingDirs); } + } else { + failedDirs.push(...existingDirs); } } + } - for (const spec of stateFiles) { - const result = backupStateFile(configFile, sandboxName, dir, spec, backupPath); - if (result.outcome === "backed_up") { - backedUpFiles.push(spec.path); - } else if (result.outcome === "failed") { - failedFiles.push(spec.path); - // Any transport-level failure at the state-file phase must promote to - // the sandbox-level unreachable flag so the skip flag can activate - // for state-file failures — not only the initial dir probe. (#6188) - if (result.unreachable) unreachable = true; - } - } - } finally { - try { - tempSshConfig.cleanup(); - } catch { - /* ignore */ + for (const spec of stateFiles) { + const result = await backupStateFile(gatewayName, sandboxName, dir, spec, backupPath); + if (result.outcome === "backed_up") { + backedUpFiles.push(spec.path); + } else if (result.outcome === "failed") { + failedFiles.push(spec.path); + // Any transport-level failure at the state-file phase must promote to + // the sandbox-level unreachable flag so the skip flag can activate + // for state-file failures — not only the initial dir probe. (#6188) + if (result.unreachable) unreachable = true; } } diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index 772b15a47a2..5f49b2327bd 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -161,6 +161,11 @@ describe("legacy sandbox transport inventory", () => { kind: "grpc-cli-read-only-fallback", calls: 1, }, + { + relativePath: "src/lib/state/sandbox.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, { relativePath: "src/lib/state/user-managed-files-probe.ts", kind: "grpc-cli-read-only-fallback", diff --git a/test/openclaw-config-snapshot.test.ts b/test/openclaw-config-snapshot.test.ts index c3ea863f892..ca46258751d 100644 --- a/test/openclaw-config-snapshot.test.ts +++ b/test/openclaw-config-snapshot.test.ts @@ -4,8 +4,38 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; -import { afterAll, describe, expect, it } from "vitest"; +import { afterAll, describe, expect, it, vi } from "vitest"; + +vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: async ( + _gatewayName: string, + request: { + command: readonly string[]; + stdin?: string | Buffer; + maxOutputBytes?: number; + timeoutMs?: number; + stdoutEncoding?: "utf8" | "buffer"; + }, + ) => { + const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: request.stdoutEncoding === "buffer" ? undefined : "utf8", + }); + const binary = request.stdoutEncoding === "buffer"; + return { + status: result.status, + stdout: binary ? "" : String(result.stdout ?? ""), + ...(binary ? { stdoutBytes: Buffer.from(result.stdout ?? "") } : {}), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + }, +})); // sandbox-state computes its backup root from HOME at module load time. const ORIGINAL_HOME = process.env.HOME; @@ -167,7 +197,7 @@ describe("OpenClaw durable config file (#5027)", () => { process.env.NEMOCLAW_OPENSHELL_BIN = path.join(binDir, "openshell"); process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.backedUpFiles).toEqual(["openclaw.json"]); expect(backup.manifest?.stateFiles).toEqual([{ path: "openclaw.json", strategy: "copy" }]); @@ -298,7 +328,7 @@ describe("OpenClaw durable config file (#5027)", () => { process.env.NEMOCLAW_OPENSHELL_BIN = path.join(binDir, "openshell"); process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); // Local backup keeps non-secret tuning + mcp.servers; secrets are stripped. diff --git a/test/sandbox-download-upload-cli.test.ts b/test/sandbox-download-upload-cli.test.ts index 322ff1229e6..24ecf6fb641 100644 --- a/test/sandbox-download-upload-cli.test.ts +++ b/test/sandbox-download-upload-cli.test.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; +import { describe, expect, it } from "vitest"; import { runWithEnv, writeSandboxRegistry } from "./cli/helpers"; @@ -91,7 +91,7 @@ describe("sandbox download/upload CLI wrappers", () => { const calls = fs.readFileSync(openshellLog, "utf8"); const expectedHostPath = path.resolve(process.cwd(), "SOUL.md"); expect(calls).toContain( - `sandbox upload alpha ${expectedHostPath} /sandbox/.openclaw/workspace/SOUL.md`, + `sandbox upload -g nemoclaw -- alpha ${expectedHostPath} /sandbox/.openclaw/workspace/SOUL.md`, ); } finally { fs.rmSync(home, { recursive: true, force: true }); @@ -113,7 +113,7 @@ describe("sandbox download/upload CLI wrappers", () => { const calls = fs.readFileSync(openshellLog, "utf8"); const expectedHostPath = path.resolve(process.cwd(), "x"); - expect(calls).toContain(`sandbox upload alpha ${expectedHostPath} /sandbox/`); + expect(calls).toContain(`sandbox upload -g nemoclaw -- alpha ${expectedHostPath} /sandbox/`); } finally { fs.rmSync(home, { recursive: true, force: true }); } diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index 856c61fa731..8db7f94c3f0 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -121,10 +121,11 @@ function makeHealthyVmGatewayEnv(prefix: string): Record { // VM-driver snapshots should trust gateway metadata, not the legacy cluster // container probe. writeExecutable(path.join(localBin, "openshell"), [ + 'if [ "$1 $2 $3 $4" = "--gateway nemoclaw sandbox exec" ]; then shift 2; fi', 'case "$1 $2" in', ' "gateway info") printf "Gateway Info\\n\\nGateway: nemoclaw\\nGateway endpoint: https://127.0.0.1:8080/\\n"; exit 0 ;;', ' "sandbox list") printf "NAME STATUS\\nalpha Ready\\n"; exit 0 ;;', - ' "sandbox exec") printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n"; exit 0 ;;', + ' "sandbox exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; exit 0 ;;', ' "sandbox ssh-config") printf "Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n"; exit 0 ;;', "esac", 'if [ "$1" = "status" ]; then exit 0; fi', @@ -160,11 +161,12 @@ function makeVmRestoreToEnv( const cloneReadyMarker = path.join(home, "clone-1-ready"); writeExecutable(path.join(localBin, "openshell"), [ + 'if [ "$1 $2 $3 $4" = "--gateway nemoclaw sandbox exec" ]; then shift 2; fi', 'case "$1 $2" in', ' "gateway info") printf "Gateway Info\\n\\nGateway: nemoclaw\\nGateway endpoint: https://127.0.0.1:8080/\\n"; exit 0 ;;', ' "sandbox get") printf "{\\"name\\":\\"%s\\"}\\n" "$3"; exit 0 ;;', ` "sandbox list") if [ -f ${JSON.stringify(cloneReadyMarker)} ]; then printf "NAME STATUS\\nalpha Ready\\nclone-1 Ready\\n"; else printf "NAME STATUS\\nalpha Ready\\n"; fi; exit 0 ;;`, - ' "sandbox exec") printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n"; exit 0 ;;', + ' "sandbox exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; exit 0 ;;', ' "sandbox ssh-config") printf "Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n"; exit 0 ;;', ` "sandbox create") touch ${JSON.stringify(cloneReadyMarker)}; printf "created clone-1\\n"; exit 0 ;;`, "esac", diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts index 12fcec71749..e37dfe5e957 100644 --- a/test/snapshot.test.ts +++ b/test/snapshot.test.ts @@ -5,11 +5,42 @@ // - validateSnapshotName accepts/rejects names // - listBackups computes virtual v versions by timestamp-ascending position // - findBackup resolves selectors (v, name, exact timestamp) + +import { spawnSync } from "node:child_process"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { pathToFileURL } from "node:url"; -import { afterAll, beforeEach, describe, expect, it } from "vitest"; +import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; + +vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => ({ + execSandboxReadOnlyWithGrpcFallback: async ( + _gatewayName: string, + request: { + command: readonly string[]; + stdin?: string | Buffer; + maxOutputBytes?: number; + timeoutMs?: number; + stdoutEncoding?: "utf8" | "buffer"; + }, + ) => { + const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: request.stdoutEncoding === "buffer" ? undefined : "utf8", + }); + const binary = request.stdoutEncoding === "buffer"; + return { + status: result.status, + stdout: binary ? "" : String(result.stdout ?? ""), + ...(binary ? { stdoutBytes: Buffer.from(result.stdout ?? "") } : {}), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + }, +})); // Override HOME BEFORE importing sandbox-state — it reads process.env.HOME // at module-load time to compute REBUILD_BACKUPS_DIR. Captured original is @@ -441,12 +472,12 @@ describe("parseRestoreArgs", () => { }); describe("sandbox directory backup semantics", () => { - it("rejects a custom OpenClaw backup with missing image-plugin provenance (#6108)", () => { + it("rejects a custom OpenClaw backup with missing image-plugin provenance (#6108)", async () => { writeOpenClawRegistry("custom-openclaw", { fromDockerfile: "/tmp/Dockerfile.custom", }); - const backup = sandboxState.backupSandboxState("custom-openclaw"); + const backup = await sandboxState.backupSandboxState("custom-openclaw"); expect(backup.success).toBe(false); expect(backup.manifest).toBeUndefined(); @@ -454,7 +485,7 @@ describe("sandbox directory backup semantics", () => { expect(fs.existsSync(path.join(BACKUPS_ROOT, "custom-openclaw"))).toBe(false); }); - it("treats empty state directories as backed up when tar exits cleanly", () => { + it("treats empty state directories as backed up when tar exits cleanly", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-empty-dirs-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -477,7 +508,7 @@ const fs = require("node:fs"); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("openclaw.json") && cmd.includes("cat --")) { @@ -505,7 +536,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}${path.delimiter}${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.failedDirs).toEqual([]); expect(backup.backedUpDirs).toEqual(existingDirs); @@ -523,7 +554,7 @@ process.exit(0); } }); - it("classifies tar-failed directories and excludes them from the restorable manifest", () => { + it("classifies tar-failed directories and excludes them from the restorable manifest", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-partial-tar-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -555,7 +586,7 @@ function readStdin() { } } if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("openclaw.json") && cmd.includes("cat --")) { @@ -590,7 +621,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.failedDirs).toEqual(["agents", "workspace"]); expect(backup.failedDirReasons).toEqual({ @@ -628,7 +659,7 @@ process.exit(0); } }); - it("accepts built-in and custom OpenClaw peer links during the pre-backup audit", () => { + it("accepts built-in and custom OpenClaw peer links during the pre-backup audit", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-whitelist-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -639,12 +670,15 @@ process.exit(0); fs.mkdirSync(binDir, { recursive: true }); for (const d of existingDirs) fs.mkdirSync(path.join(openclawDir, d), { recursive: true }); - const auditLines = [ - "l\t/sandbox/.openclaw/extensions/openclaw-weixin/node_modules/.bin/qrcode-terminal\t../qrcode-terminal/bin/qrcode-terminal.js", - "l\t/sandbox/.openclaw/extensions/openclaw-weixin/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", - "l\t/sandbox/.openclaw/extensions/slack/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", - "l\t/sandbox/.openclaw/extensions/weather/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", - ].join("\n"); + const auditLines = + [ + "l\t/sandbox/.openclaw/extensions/openclaw-weixin/node_modules/.bin/qrcode-terminal\t../qrcode-terminal/bin/qrcode-terminal.js", + "l\t/sandbox/.openclaw/extensions/openclaw-weixin/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", + "l\t/sandbox/.openclaw/extensions/slack/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", + "l\t/sandbox/.openclaw/extensions/weather/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", + ] + .map((entry) => entry.split("\t").join("\0")) + .join("\0") + "\0"; const openshell = writeFakeOpenshell(binDir); writeExecutable( @@ -655,11 +689,11 @@ const fs = require("node:fs"); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("find ")) { - process.stdout.write(${JSON.stringify(auditLines)} + "\\n"); + process.stdout.write(${JSON.stringify(auditLines)}); process.exit(0); } if (cmd.includes("tar -cf -")) { @@ -677,7 +711,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.backedUpDirs).toEqual(existingDirs); expect(backup.error).toBeUndefined(); @@ -692,7 +726,7 @@ process.exit(0); } }); - it("accepts extension npm .bin symlinks that resolve inside node_modules", () => { + it("accepts extension npm .bin symlinks that resolve inside node_modules", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-npm-bin-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -703,11 +737,14 @@ process.exit(0); fs.mkdirSync(binDir, { recursive: true }); fs.mkdirSync(path.join(openclawDir, "extensions"), { recursive: true }); - const auditLines = [ - "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/json5\t../json5/lib/cli.js", - "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/yaml\t../yaml/bin.mjs", - "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/node-which\t../which/bin/node-which", - ].join("\n"); + const auditLines = + [ + "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/json5\t../json5/lib/cli.js", + "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/yaml\t../yaml/bin.mjs", + "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/node-which\t../which/bin/node-which", + ] + .map((entry) => entry.split("\t").join("\0")) + .join("\0") + "\0"; const openshell = writeFakeOpenshell(binDir); writeExecutable( @@ -719,11 +756,11 @@ const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; const openclawDir = ${JSON.stringify(openclawDir)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("find ")) { - process.stdout.write(${JSON.stringify(auditLines)} + "\\n"); + process.stdout.write(${JSON.stringify(auditLines)}); process.exit(0); } if (cmd.includes("tar -cf -")) { @@ -741,7 +778,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(true); expect(backup.error).toBeUndefined(); } finally { @@ -755,7 +792,7 @@ process.exit(0); } }); - it("rejects extension npm .bin symlinks that escape node_modules", () => { + it("rejects extension npm .bin symlinks that escape node_modules", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-npm-bin-escape-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -766,9 +803,12 @@ process.exit(0); fs.mkdirSync(binDir, { recursive: true }); fs.mkdirSync(path.join(openclawDir, "extensions"), { recursive: true }); - const auditLines = [ - "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/leak\t../../../../openclaw.json", - ].join("\n"); + const auditLines = + [ + "l\t/sandbox/.openclaw/extensions/nemoclaw/node_modules/.bin/leak\t../../../../openclaw.json", + ] + .map((entry) => entry.split("\t").join("\0")) + .join("\0") + "\0"; const openshell = writeFakeOpenshell(binDir); writeExecutable( @@ -777,11 +817,11 @@ process.exit(0); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("find ")) { - process.stdout.write(${JSON.stringify(auditLines)} + "\\n"); + process.stdout.write(${JSON.stringify(auditLines)}); process.exit(0); } process.exit(0); @@ -792,7 +832,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.error).toMatch(/node_modules\/\.bin\/leak/); expect(backup.error).toMatch(/openclaw\.json/); @@ -807,7 +847,7 @@ process.exit(0); } }); - it("still rejects non-whitelisted symlinks alongside whitelisted ones", () => { + it("still rejects non-whitelisted symlinks alongside whitelisted ones", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-mixed-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -818,10 +858,13 @@ process.exit(0); fs.mkdirSync(binDir, { recursive: true }); for (const d of existingDirs) fs.mkdirSync(path.join(openclawDir, d), { recursive: true }); - const auditLines = [ - "l\t/sandbox/.openclaw/extensions/openclaw-weixin/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", - "l\t/sandbox/.openclaw/workspace/leak\t/etc/passwd", - ].join("\n"); + const auditLines = + [ + "l\t/sandbox/.openclaw/extensions/openclaw-weixin/node_modules/openclaw\t/usr/local/lib/node_modules/openclaw", + "l\t/sandbox/.openclaw/workspace/leak\t/etc/passwd", + ] + .map((entry) => entry.split("\t").join("\0")) + .join("\0") + "\0"; const openshell = writeFakeOpenshell(binDir); writeExecutable( @@ -830,11 +873,11 @@ process.exit(0); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("find ")) { - process.stdout.write(${JSON.stringify(auditLines)} + "\\n"); + process.stdout.write(${JSON.stringify(auditLines)}); process.exit(0); } process.exit(0); @@ -845,7 +888,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.error).toMatch(/workspace\/leak/); expect(backup.error).not.toMatch(/openclaw-weixin/); @@ -863,7 +906,7 @@ process.exit(0); it.each([ "weather", "slack", - ])("rejects a generic %s OpenClaw peer link with a tampered target", (extensionName) => { + ])("rejects a generic %s OpenClaw peer link with a tampered target", async (extensionName) => { // The generic peer path is valid, but its target must remain the exact // global OpenClaw install rather than an arbitrary absolute path. const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-target-tampered-")); @@ -876,9 +919,10 @@ process.exit(0); fs.mkdirSync(binDir, { recursive: true }); for (const d of existingDirs) fs.mkdirSync(path.join(openclawDir, d), { recursive: true }); - const auditLines = [ - `l\t/sandbox/.openclaw/extensions/${extensionName}/node_modules/openclaw\t/etc/passwd`, - ].join("\n"); + const auditLines = + [`l\t/sandbox/.openclaw/extensions/${extensionName}/node_modules/openclaw\t/etc/passwd`] + .map((entry) => entry.split("\t").join("\0")) + .join("\0") + "\0"; const openshell = writeFakeOpenshell(binDir); writeExecutable( @@ -887,11 +931,11 @@ process.exit(0); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("find ")) { - process.stdout.write(${JSON.stringify(auditLines)} + "\\n"); + process.stdout.write(${JSON.stringify(auditLines)}); process.exit(0); } process.exit(0); @@ -902,7 +946,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.error).toContain(`extensions/${extensionName}`); expect(backup.error).toMatch(/\/etc\/passwd/); @@ -917,7 +961,7 @@ process.exit(0); } }); - it("marks non-attributed directories failed when they are missing from partial extraction", () => { + it("marks non-attributed directories failed when they are missing from partial extraction", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-missing-partial-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -939,7 +983,7 @@ const { spawnSync } = require("node:child_process"); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("find ")) { @@ -962,7 +1006,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); expect(backup.backedUpDirs).toEqual(["extensions"]); expect(backup.failedDirs).toEqual(["agents", "workspace"]); @@ -983,134 +1027,103 @@ process.exit(0); } }); - it("treats audit-find exit 1 with empty stdout as a successful audit", () => { + it("fails closed when OpenClaw image subtrees cannot be audited", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-perm-denied-")); const oldPath = process.env.PATH; - const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; try { const binDir = path.join(fixture, "bin"); - const openclawDir = path.join(fixture, "sandbox-root", ".openclaw"); + const archiveAttempt = path.join(fixture, "archive-attempted"); const existingDirs = ["agents", "extensions", "workspace"]; fs.mkdirSync(binDir, { recursive: true }); - for (const d of existingDirs) fs.mkdirSync(path.join(openclawDir, d), { recursive: true }); - const openshell = writeFakeOpenshell(binDir); writeExecutable( path.join(binDir, "ssh"), `#!/usr/bin/env node -const { spawnSync } = require("node:child_process"); const fs = require("node:fs"); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } -if (cmd.includes("openclaw.json")) { - // No openclaw.json in this fixture: the state-file backup command's - // \`[ ! -e "$src" ] && exit 2\` fires (missing, not a failure). Handled - // before the generic \`find \` matcher below, which would otherwise catch - // the command's internal hardlink-check find. - process.exit(2); -} if (cmd.includes("find ")) { - // Simulate a permission-denied subdir: when the audit cmd lacks the - // \`|| true\` tolerance wrapper (pre-fix shape), exit non-zero so the - // caller treats it as audit failure. The post-fix shape wraps each - // \`find\` with \`|| true\` and joins with \`;\`, so the audit cmd as a - // whole exits 0 even though a remote \`find\` would have exited 1. - if (!cmd.includes("|| true")) { - process.stderr.write("find: '/sandbox/.openclaw/extensions/nemoclaw': Permission denied\\n"); - process.exit(1); + if (cmd.includes("-prune") || cmd.includes("|| true")) { + process.stderr.write("unsafe audit suppression\\n"); + process.exit(90); } - process.exit(0); + if (!cmd.includes("xargs -0 -r sh -c") || cmd.includes("-files0-from")) { + process.stderr.write("missing bounded audit input\\n"); + process.exit(91); + } + process.stderr.write("find: '/sandbox/.openclaw/agents/main': Permission denied\\n"); + process.exit(1); } if (cmd.includes("tar -cf -")) { - const r = spawnSync("tar", ["-cf", "-", "-C", ${JSON.stringify(openclawDir)}, ...existingDirs], { - stdio: ["ignore", "pipe", "pipe"], - }); - if (r.stdout) fs.writeSync(1, r.stdout); - process.exit(r.status || 0); + fs.writeFileSync(${JSON.stringify(archiveAttempt)}, "attempted"); + process.exit(92); } process.exit(0); `, ); writeOpenClawRegistry("alpha"); - process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); - expect(backup.success).toBe(true); - expect(backup.error).toBeUndefined(); - expect(backup.backedUpDirs).toEqual(existingDirs); + const backup = await sandboxState.backupSandboxState("alpha"); + expect(backup.success).toBe(false); + expect(backup.backedUpDirs).toEqual([]); + expect(backup.failedDirs).toEqual(existingDirs); + expect(backup.error).toMatch(/agents\/main.*Permission denied/); + expect(fs.existsSync(archiveAttempt)).toBe(false); } finally { - if (oldOpenshell === undefined) { - delete process.env.NEMOCLAW_OPENSHELL_BIN; - } else { - process.env.NEMOCLAW_OPENSHELL_BIN = oldOpenshell; - } process.env.PATH = oldPath; fs.rmSync(fixture, { recursive: true, force: true }); } }); - it("still rejects violations from readable dirs even if a sibling find exits non-zero", () => { + it("retains a traversal failure when a readable sibling reports a violation", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-audit-mixed-perm-")); const oldPath = process.env.PATH; - const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; try { const binDir = path.join(fixture, "bin"); - const openclawDir = path.join(fixture, "sandbox-root", ".openclaw"); const existingDirs = ["agents", "workspace"]; fs.mkdirSync(binDir, { recursive: true }); - for (const d of existingDirs) fs.mkdirSync(path.join(openclawDir, d), { recursive: true }); - // `agents` simulates perm-denied (no rows emitted); `workspace` emits - // a symlink that is not in the audit allow-list, which must still be - // caught even when a sibling find exits non-zero. - const auditLines = ["l\t/sandbox/.openclaw/workspace/leak\t../openclaw.json"].join("\n"); + // `agents` simulates permission denial while `workspace` emits a symlink. + // The aggregate command must preserve the traversal failure. + const auditLines = ["l", "/sandbox/.openclaw/workspace/leak", "../openclaw.json", ""].join( + "\0", + ); - const openshell = writeFakeOpenshell(binDir); writeExecutable( path.join(binDir, "ssh"), `#!/usr/bin/env node const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; if (cmd.includes("[ -d ")) { - process.stdout.write(existingDirs.join("\\n") + "\\n"); + process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); } if (cmd.includes("find ")) { - // Match real-shell behaviour: without the \`|| true\` tolerance wrapper - // the perm-denied sibling \`find\` would have aborted the chain. The - // post-fix audit cmd still emits the violation stdout because \`;\` - // joins each per-dir block so the readable sibling's output is - // preserved. - if (!cmd.includes("|| true")) { - process.stderr.write("find: '/sandbox/.openclaw/agents/main': Permission denied\\n"); - process.exit(1); + if (cmd.includes("-prune") || cmd.includes("|| true")) { + process.stderr.write("unsafe audit suppression\\n"); + process.exit(90); } - process.stdout.write(${JSON.stringify(auditLines)} + "\\n"); - process.exit(0); + process.stdout.write(${JSON.stringify(auditLines)}); + process.stderr.write("find: '/sandbox/.openclaw/agents/main': Permission denied\\n"); + process.exit(1); } process.exit(0); `, ); writeOpenClawRegistry("alpha"); - process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("alpha"); + const backup = await sandboxState.backupSandboxState("alpha"); expect(backup.success).toBe(false); - expect(backup.error).toMatch(/workspace\/leak/); + expect(backup.error).toMatch(/agents\/main.*Permission denied/); } finally { - if (oldOpenshell === undefined) { - delete process.env.NEMOCLAW_OPENSHELL_BIN; - } else { - process.env.NEMOCLAW_OPENSHELL_BIN = oldOpenshell; - } process.env.PATH = oldPath; fs.rmSync(fixture, { recursive: true, force: true }); } @@ -1118,7 +1131,7 @@ process.exit(0); }); describe("Deep Agents Code durable state files", () => { - it("backs up manifest-declared state while excluding credential-bearing files", () => { + it("backs up manifest-declared state while excluding credential-bearing files", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-deepagents-snapshot-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -1188,7 +1201,7 @@ if (cmd.includes(".env") || cmd.includes(".mcp.json")) { process.exit(99); } if (cmd.includes("[ -d ")) { - process.stdout.write(".state\\nskills\\nagent/skills\\n"); + process.stdout.write(".state\\0skills\\0agent/skills\\0"); process.exit(0); } if (cmd.includes("find ")) { @@ -1218,7 +1231,9 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}${path.delimiter}${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("deepagents", { name: "deepagents-state" }); + const backup = await sandboxState.backupSandboxState("deepagents", { + name: "deepagents-state", + }); expect(backup.success).toBe(true); expect(backup.backedUpDirs).toEqual([".state", "skills", "agent/skills"]); expect(backup.backedUpFiles).toEqual(["config.toml"]); @@ -1270,7 +1285,7 @@ process.exit(0); }); describe("Hermes durable state files", () => { - it("backs up and restores SOUL.md plus the SQLite state database without credential files", () => { + it("backs up and restores SOUL.md plus the SQLite state database without credential files", async () => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-hermes-snapshot-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -1280,11 +1295,22 @@ describe("Hermes durable state files", () => { const hermesDir = path.join(fakeRoot, ".hermes"); const runtimeDir = path.join(hermesDir, "runtime"); const sshLog = path.join(fixture, "ssh-log.jsonl"); + const stateDbPayload = Buffer.from([0x53, 0x51, 0x4c, 0x00, 0xff, 0xfe, 0x80, 0x0a]); fs.mkdirSync(binDir, { recursive: true }); fs.mkdirSync(runtimeDir, { recursive: true }); fs.writeFileSync(path.join(hermesDir, "SOUL.md"), "original soul\n"); fs.writeFileSync(path.join(hermesDir, ".hermes_history"), "original history\n"); - fs.writeFileSync(path.join(runtimeDir, "state.db"), "original sqlite backup\n"); + const stateDbPath = path.join(runtimeDir, "state.db"); + const seededDatabase = spawnSync( + "python3", + [ + "-c", + "import sqlite3,sys; db=sqlite3.connect(sys.argv[1]); db.execute('CREATE TABLE payload (data BLOB NOT NULL)'); db.execute('INSERT INTO payload VALUES (?)', (sys.stdin.buffer.read(),)); db.commit(); db.close()", + stateDbPath, + ], + { input: stateDbPayload }, + ); + expect(seededDatabase.status, String(seededDatabase.stderr)).toBe(0); fs.writeFileSync(path.join(hermesDir, "config.yaml"), "token: should-not-copy\n"); fs.writeFileSync(path.join(hermesDir, ".env"), "API_TOKEN=should-not-copy\n"); fs.writeFileSync(path.join(hermesDir, "auth.json"), '{"token":"should-not-copy"}\n'); @@ -1307,6 +1333,7 @@ process.exit(0); `#!/usr/bin/env node const fs = require("fs"); const path = require("path"); +const { spawnSync } = require("child_process"); const root = ${JSON.stringify(fakeRoot)}; const log = ${JSON.stringify(sshLog)}; const cmd = process.argv[process.argv.length - 1] || ""; @@ -1326,8 +1353,18 @@ if (cmd.includes("[ -d ")) { process.exit(0); } if (cmd.includes("nemoclaw-sqlite-backup")) { - process.stdout.write(fs.readFileSync(path.join(hermesDir, "runtime", "state.db"))); - process.exit(0); + const backupScript = readStdin(); + if (backupScript.toString("utf8") !== ${JSON.stringify(sandboxState.SQLITE_BACKUP_PY)}) { + process.stderr.write("unexpected sqlite backup script on stdin\\n"); + process.exit(97); + } + const result = spawnSync("sh", ["-c", cmd.replaceAll("/sandbox/.hermes", hermesDir)], { + encoding: null, + input: backupScript, + }); + if (result.stdout) fs.writeSync(1, result.stdout); + if (result.stderr) fs.writeSync(2, result.stderr); + process.exit(result.status === null ? 1 : result.status); } if (cmd.includes("SOUL.md") && cmd.includes("cat --")) { process.stdout.write(fs.readFileSync(path.join(hermesDir, "SOUL.md"))); @@ -1375,7 +1412,7 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const backup = sandboxState.backupSandboxState("hermes", { name: "hermes-state" }); + const backup = await sandboxState.backupSandboxState("hermes", { name: "hermes-state" }); expect(backup.success).toBe(true); expect(backup.backedUpFiles).toEqual(["SOUL.md", ".hermes_history", "runtime/state.db"]); expect(backup.failedFiles).toEqual([]); @@ -1390,9 +1427,22 @@ process.exit(0); expect( fs.readFileSync(path.join(backup.manifest!.backupPath, ".hermes_history"), "utf-8"), ).toBe("original history\n"); - expect( - fs.readFileSync(path.join(backup.manifest!.backupPath, "runtime", "state.db"), "utf-8"), - ).toBe("original sqlite backup\n"); + const backedUpStateDbPath = path.join(backup.manifest!.backupPath, "runtime", "state.db"); + const backedUpStateDbBytes = fs.readFileSync(backedUpStateDbPath); + expect(Buffer.from(backedUpStateDbBytes.toString("utf8"), "utf8")).not.toEqual( + backedUpStateDbBytes, + ); + const backedUpPayload = spawnSync( + "python3", + [ + "-c", + "import sqlite3,sys; db=sqlite3.connect(sys.argv[1]); sys.stdout.buffer.write(db.execute('SELECT data FROM payload').fetchone()[0]); db.close()", + backedUpStateDbPath, + ], + { encoding: null }, + ); + expect(backedUpPayload.status, String(backedUpPayload.stderr)).toBe(0); + expect(backedUpPayload.stdout).toEqual(stateDbPayload); expect(fs.existsSync(path.join(backup.manifest!.backupPath, "config.yaml"))).toBe(false); expect(fs.existsSync(path.join(backup.manifest!.backupPath, ".env"))).toBe(false); expect(fs.existsSync(path.join(backup.manifest!.backupPath, "auth.json"))).toBe(false); @@ -1407,14 +1457,20 @@ process.exit(0); expect(fs.readFileSync(path.join(hermesDir, ".hermes_history"), "utf-8")).toBe( "original history\n", ); - expect(fs.readFileSync(path.join(runtimeDir, "state.db"), "utf-8")).toBe( - "original sqlite backup\n", - ); + expect(fs.readFileSync(path.join(runtimeDir, "state.db"))).toEqual(backedUpStateDbBytes); - const loggedCommands = fs.readFileSync(sshLog, "utf-8"); - expect(loggedCommands).toContain("sqlite3.connect"); - expect(loggedCommands).toContain("src_conn.backup(dst_conn)"); - expect(loggedCommands).toContain("PRAGMA quick_check"); + const loggedCommands = fs + .readFileSync(sshLog, "utf-8") + .trim() + .split("\n") + .map((line) => JSON.parse(line).cmd as string); + const sqliteBackupCommand = loggedCommands.find((command) => + command.includes("nemoclaw-sqlite-backup"), + ); + expect(sqliteBackupCommand).toBeDefined(); + expect(sqliteBackupCommand).toContain('python3 - "$src" "$tmp"'); + expect(sqliteBackupCommand).not.toMatch(/[\u0000\r\n]/); + expect(Buffer.byteLength(sqliteBackupCommand!, "utf8")).toBeLessThanOrEqual(32_768); } finally { if (oldOpenshell === undefined) { delete process.env.NEMOCLAW_OPENSHELL_BIN;