From 6f5e4156a1a324137e147b0855da137787834154 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 15:18:21 -0700 Subject: [PATCH 01/14] refactor(openshell): remove state restore SSH Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 7 - src/lib/actions/sandbox/rebuild-pipeline.ts | 2 +- .../rebuild-restore-forwarding.test.ts | 6 +- .../sandbox/rebuild-restore-phase.test.ts | 74 +++---- .../actions/sandbox/rebuild-restore-phase.ts | 6 +- src/lib/actions/sandbox/snapshot.ts | 92 ++++---- src/lib/onboard.ts | 10 +- .../created-sandbox-finalization.test.ts | 102 ++++++--- .../onboard/created-sandbox-finalization.ts | 12 +- .../openclaw-config-restore-input.test.ts | 9 +- .../state/openclaw-config-restore-input.ts | 38 ++-- src/lib/state/openclaw-plugin-restore.ts | 78 +++---- .../sandbox-openclaw-plugin-restore.test.ts | 95 ++++---- ...sandbox-recreated-openclaw-restore.test.ts | 60 ++++- ...andbox-state-file-restore-contract.test.ts | 20 +- src/lib/state/sandbox.ts | 208 ++++++++---------- .../state-file-restore-custom-image.test.ts | 46 ++-- src/lib/state/state-file-restore.ts | 25 ++- test/openclaw-config-restore.test.ts | 22 +- test/openclaw-config-snapshot.test.ts | 38 ++-- ...apshot-openclaw-managed-extensions.test.ts | 62 +++++- test/snapshot-recovery-validation.test.ts | 6 +- test/snapshot.test.ts | 50 +++-- 23 files changed, 582 insertions(+), 486 deletions(-) diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index 91f2a2ae934..fc4090bd724 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -49,13 +49,6 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/share-command.ts", "sshfs-command", 1], ["src/lib/shields/index.ts", "privileged-sandbox-exec", 4], ["src/lib/shields/mutable-config-repair.ts", "privileged-sandbox-exec", 2], - ["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", "openshell-ssh-config", 1], - ["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/tunnel/sandbox-gateway-stop.ts", "docker-exec-command", 2], ] as const satisfies readonly ReviewedSiteTuple[]; diff --git a/src/lib/actions/sandbox/rebuild-pipeline.ts b/src/lib/actions/sandbox/rebuild-pipeline.ts index 20e5e57eaf9..773a1f41f65 100644 --- a/src/lib/actions/sandbox/rebuild-pipeline.ts +++ b/src/lib/actions/sandbox/rebuild-pipeline.ts @@ -297,7 +297,7 @@ async function rebuildSandboxUnlocked( durableConfig.webSearchConfig, ); - const restored = runRebuildRestorePhase({ + const restored = await runRebuildRestorePhase({ sandboxName, targetAgentType: rebuildAgent || "openclaw", targetImageIsCustom: Boolean(fromDockerfile), diff --git a/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts b/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts index baeef9340ca..0ca949ffef2 100644 --- a/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts +++ b/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts @@ -11,11 +11,11 @@ afterEach(() => { }); describe("rebuild restore target forwarding", () => { - it("forwards the recreated target identity and explicit custom-image capability", () => { + it("forwards the recreated target identity and explicit custom-image capability", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const restoreRecreatedSandboxState = vi .spyOn(sandboxState, "restoreRecreatedSandboxState") - .mockReturnValue({ + .mockResolvedValue({ success: true, restoredDirs: [], restoredFiles: [], @@ -23,7 +23,7 @@ describe("rebuild restore target forwarding", () => { failedFiles: [], }); - runRebuildRestorePhase({ + await runRebuildRestorePhase({ sandboxName: "alpha", targetAgentType: "langchain-deepagents-code", targetImageIsCustom: true, diff --git a/src/lib/actions/sandbox/rebuild-restore-phase.test.ts b/src/lib/actions/sandbox/rebuild-restore-phase.test.ts index dbde96ca34f..08792c91481 100644 --- a/src/lib/actions/sandbox/rebuild-restore-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-restore-phase.test.ts @@ -40,11 +40,11 @@ describe("rebuild policy restore fidelity", () => { vi.restoreAllMocks(); }); - it("surfaces a fresh OpenClaw plugin registry precondition failure", () => { + it("surfaces a fresh OpenClaw plugin registry precondition failure", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const consoleError = vi.spyOn(console, "error").mockImplementation(() => undefined); const log = vi.fn(); - vi.spyOn(sandboxState, "restoreRecreatedSandboxState").mockReturnValue({ + vi.spyOn(sandboxState, "restoreRecreatedSandboxState").mockResolvedValue({ success: false, restoredDirs: [], restoredFiles: [], @@ -53,7 +53,7 @@ describe("rebuild policy restore fidelity", () => { error: "could not read fresh OpenClaw plugin install registry", }); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: { agentType: "openclaw", backupPath: "/tmp/rebuild-backup" } as never, policyPresets: [], @@ -71,13 +71,13 @@ describe("rebuild policy restore fidelity", () => { ); }); - it("replays custom web-policy names from exact content instead of same-name built-ins", () => { + it("replays custom web-policy names from exact content instead of same-name built-ins", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); const parsePresetPolicyKeys = vi.spyOn(policies, "parsePresetPolicyKeys"); const restoreRecreatedSandboxState = vi .spyOn(sandboxState, "restoreRecreatedSandboxState") - .mockReturnValue({ + .mockResolvedValue({ success: true, restoredDirs: [], restoredFiles: [], @@ -91,7 +91,7 @@ describe("rebuild policy restore fidelity", () => { content: `network_policies:\n ${name}-custom:\n name: ${name}-custom\n`, sourcePath: `/tmp/${name}.yaml`, })); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: { agentType: "openclaw", @@ -122,9 +122,9 @@ describe("rebuild policy restore fidelity", () => { expect(parsePresetPolicyKeys).not.toHaveBeenCalled(); }); - it("replays captured registry custom policies during stale recovery without a backup", () => { + it("replays captured registry custom policies during stale recovery without a backup", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); - vi.spyOn(sandboxState, "restoreSandboxState").mockReturnValue({ + vi.spyOn(sandboxState, "restoreSandboxState").mockResolvedValue({ success: true, restoredDirs: [], restoredFiles: [], @@ -139,7 +139,7 @@ describe("rebuild policy restore fidelity", () => { sourcePath: "/tmp/custom-egress.yaml", }, ]; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -158,7 +158,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.finalPresets).toEqual(["custom-egress"]); }); - it("leaves generated MCP policy replay exclusively to MCP restoration", () => { + it("leaves generated MCP policy replay exclusively to MCP restoration", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const applyPresetContent = vi.spyOn(policies, "applyPresetContent").mockReturnValue(true); const genuineCustomPolicy = { @@ -172,7 +172,7 @@ describe("rebuild policy restore fidelity", () => { "network_policies:\n mcp-bridge-search:\n endpoints:\n - host: mcp.example.com\n allowed_ips: [203.0.113.10]\n", sourcePath: MCP_BRIDGE_POLICY_SOURCE, }; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -192,7 +192,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.failedPresets).toEqual([]); }); - it("removes an observability preset introduced while rebuilding a restricted sandbox", () => { + it("removes an observability preset introduced while rebuilding a restricted sandbox", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); @@ -201,7 +201,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce("absent"); const removePreset = vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["npm"], @@ -218,7 +218,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("retains an observed exact built-in when post-removal verification is unavailable", () => { + it("retains an observed exact built-in when post-removal verification is unavailable", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); vi.spyOn(policies, "getPresetContentGatewayState") @@ -226,7 +226,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce(null); vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["npm"], @@ -239,7 +239,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("accounts for known failed additions without treating a narrower live set as unverified", () => { + it("accounts for known failed additions without treating a narrower live set as unverified", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset") @@ -256,7 +256,7 @@ describe("rebuild policy restore fidelity", () => { throw new Error("apply failed"); }); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["npm", "bad", "throw"], @@ -272,12 +272,12 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("keeps reconciliation unverified when a reported successful addition is missing live", () => { + it("keeps reconciliation unverified when a reported successful addition is missing live", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -292,13 +292,13 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("retains target built-in attribution when exact post-apply verification is unavailable", () => { + it("retains target built-in attribution when exact post-apply verification is unavailable", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); vi.spyOn(console, "error").mockImplementation(() => undefined); vi.spyOn(policies, "applyPreset").mockReturnValue(true); vi.spyOn(policies, "getPresetContentGatewayState").mockReturnValue(null); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -311,10 +311,10 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("does not remove or persist DCode base-policy keys detected as broad presets", () => { + it("does not remove or persist DCode base-policy keys detected as broad presets", async () => { const removePreset = vi.spyOn(policies, "removePreset"); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -329,7 +329,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("leaves a same-name custom observability policy outside built-in narrowing", () => { + it("leaves a same-name custom observability policy outside built-in narrowing", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const applyPresetContent = vi.spyOn(policies, "applyPresetContent").mockReturnValue(true); const removePreset = vi.spyOn(policies, "removePreset"); @@ -339,7 +339,7 @@ describe("rebuild policy restore fidelity", () => { sourcePath: "/tmp/operator-collector.yaml", }; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -359,7 +359,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("leaves a differently named custom policy owning observability egress outside built-in narrowing", () => { + it("leaves a differently named custom policy owning observability egress outside built-in narrowing", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const applyPresetContent = vi.spyOn(policies, "applyPresetContent").mockReturnValue(true); const exactState = vi.spyOn(policies, "getPresetContentGatewayState").mockReturnValue("match"); @@ -371,7 +371,7 @@ describe("rebuild policy restore fidelity", () => { sourcePath: "/tmp/corp-otel.yaml", }; - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -392,7 +392,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("removes an exact inner built-in behind a same-name custom with a different key", () => { + it("removes an exact inner built-in behind a same-name custom with a different key", async () => { vi.spyOn(console, "log").mockImplementation(() => undefined); const customPolicy = { name: "observability-otlp-local", @@ -405,7 +405,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce("absent"); const removePreset = vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -421,7 +421,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("removes an exact inner built-in when overlapping custom replay fails", () => { + it("removes an exact inner built-in when overlapping custom replay fails", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); const customPolicy = { name: "corp-otel", @@ -434,7 +434,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce("absent"); const removePreset = vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -451,7 +451,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(true); }); - it("leaves drift untouched and unverified when successful custom ownership is not exact", () => { + it("leaves drift untouched and unverified when successful custom ownership is not exact", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); const customPolicy = { name: "corp-otel", @@ -462,7 +462,7 @@ describe("rebuild policy restore fidelity", () => { vi.spyOn(policies, "getPresetContentGatewayState").mockReturnValue("drift"); const removePreset = vi.spyOn(policies, "removePreset"); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: [], @@ -476,7 +476,7 @@ describe("rebuild policy restore fidelity", () => { expect(result.policyPresetReconciliationVerified).toBe(false); }); - it("retains separate built-in attribution when same-name custom removal is unverified", () => { + it("retains separate built-in attribution when same-name custom removal is unverified", async () => { vi.spyOn(console, "error").mockImplementation(() => undefined); const customPolicy = { name: "observability-otlp-local", @@ -489,7 +489,7 @@ describe("rebuild policy restore fidelity", () => { .mockReturnValueOnce(null); vi.spyOn(policies, "removePreset").mockReturnValue(true); - const result = runStandardRebuildRestorePhase({ + const result = await runStandardRebuildRestorePhase({ sandboxName: "alpha", backupManifest: null, policyPresets: ["observability-otlp-local"], @@ -514,7 +514,7 @@ describe("rebuild policy restore fidelity", () => { }); }); - it("keeps finalized custom-only policy state empty after exact replay", () => { + it("keeps finalized custom-only policy state empty after exact replay", async () => { expect(resolveRestoredPolicyRegistryState({ policyPresetsFinalized: true }, [], [])).toEqual({ policies: [], policyPresetsFinalized: true, @@ -525,7 +525,7 @@ describe("rebuild policy restore fidelity", () => { ).toBeUndefined(); }); - it("retains the force-skipped backup warning in the successful final summary", () => { + it("retains the force-skipped backup warning in the successful final summary", async () => { const writeLine = vi.fn(); printSuccessfulRebuildSummary( diff --git a/src/lib/actions/sandbox/rebuild-restore-phase.ts b/src/lib/actions/sandbox/rebuild-restore-phase.ts index 809865a5089..7d8df368e85 100644 --- a/src/lib/actions/sandbox/rebuild-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-restore-phase.ts @@ -175,7 +175,9 @@ function reconcileFinalManagedObservability( * Boundary coverage: rebuild-flow.test.ts exercises full/partial state restore, * stale recovery, successful presets, and incomplete preset recovery reporting. */ -export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): RebuildRestorePhaseResult { +export async function runRebuildRestorePhase( + input: RebuildRestorePhaseInput, +): Promise { const { sandboxName, targetAgentType, @@ -191,7 +193,7 @@ export function runRebuildRestorePhase(input: RebuildRestorePhaseInput): Rebuild console.log(""); console.log(" Restoring workspace state..."); log(`Restoring from: ${backupManifest.backupPath} into sandbox: ${sandboxName}`); - const restore = sandboxState.restoreRecreatedSandboxState( + const restore = await sandboxState.restoreRecreatedSandboxState( sandboxName, backupManifest.backupPath, { diff --git a/src/lib/actions/sandbox/snapshot.ts b/src/lib/actions/sandbox/snapshot.ts index 2cdb94262c8..e254ee20640 100644 --- a/src/lib/actions/sandbox/snapshot.ts +++ b/src/lib/actions/sandbox/snapshot.ts @@ -515,7 +515,7 @@ async function runSnapshotCreate( function repairRestoredOpenClawConfigPerms( targetSandbox: string, - result: ReturnType, + result: Awaited>, ): void { if (!result.restoredFiles.includes("openclaw.json")) return; try { @@ -942,51 +942,55 @@ async function runSnapshotRestoreUnlocked( ); }); } - withTimerBoundShieldsMutationLock(targetSandbox, "restore sandbox snapshot", () => { - // Serialize filesystem restore, mutable-permission repair, and policy - // reconciliation under the active timer generation. Normal auto-restore - // waits; the absolute deadline may preempt this process and reclaim the - // token, preventing policy/config mutation after lockdown resumes. - if (targetSandbox !== sandboxName) { - console.log(` Restoring snapshot from '${sandboxName}' into '${targetSandbox}'...`); - } else { - console.log(` Restoring snapshot into '${sandboxName}'...`); - } - const result = sandboxState.restoreSandboxState(targetSandbox, backupPath); - if (result.success) { - console.log( - ` ${G}\u2713${R} Restored ${result.restoredDirs.length} directories, ${result.restoredFiles.length} files`, - ); - } else { - console.error(` Restore failed.`); - if (result.restoredDirs.length > 0) { - console.error(` Partial: ${result.restoredDirs.join(", ")}`); - } - if (result.failedDirs.length > 0) { - console.error(` Failed: ${result.failedDirs.join(", ")}`); + await withTimerBoundShieldsMutationLockAsync( + targetSandbox, + "restore sandbox snapshot", + async () => { + // Serialize filesystem restore, mutable-permission repair, and policy + // reconciliation under the active timer generation. Normal auto-restore + // waits; the absolute deadline may preempt this process and reclaim the + // token, preventing policy/config mutation after lockdown resumes. + if (targetSandbox !== sandboxName) { + console.log(` Restoring snapshot from '${sandboxName}' into '${targetSandbox}'...`); + } else { + console.log(` Restoring snapshot into '${sandboxName}'...`); } - if (result.failedFiles.length > 0) { - console.error(` Failed files: ${result.failedFiles.join(", ")}`); + const result = await sandboxState.restoreSandboxState(targetSandbox, backupPath); + if (result.success) { + console.log( + ` ${G}\u2713${R} Restored ${result.restoredDirs.length} directories, ${result.restoredFiles.length} files`, + ); + } else { + console.error(` Restore failed.`); + if (result.restoredDirs.length > 0) { + console.error(` Partial: ${result.restoredDirs.join(", ")}`); + } + if (result.failedDirs.length > 0) { + console.error(` Failed: ${result.failedDirs.join(", ")}`); + } + if (result.failedFiles.length > 0) { + console.error(` Failed files: ${result.failedFiles.join(", ")}`); + } + snapshotExit(1); } - snapshotExit(1); - } - // Post-restore security-state reconciliation is best-effort by design: the - // filesystem restore succeeded and old snapshots may target hosts where policy - // providers or mutable-config repair are temporarily unavailable. Surface every - // failure as a warning, but keep the restore result tied to state restoration. - // #5027/#4538: openclaw.json restores via the generic copy strategy, which - // lands it at 0640. Repair the mutable config contract when needed. - repairRestoredOpenClawConfigPerms(targetSandbox, result); - // Reconcile custom policy presets (applied via --from-file/--from-dir). - // Skipped for legacy snapshots that predate the `customPolicies` field. - reconcileSnapshotCustomPolicies(targetSandbox, resolvedSnapshot); - // Reconcile built-in presets after custom content so same-name custom - // policies are never transiently substituted with a built-in. The current - // target observability bit and tier override historical built-in OTLP state. - // Legacy snapshots skip unrelated generic presets but still reconcile the - // managed observability binding from current target state. - reconcileSnapshotPolicyPresets(targetSandbox, resolvedSnapshot); - }); + // Post-restore security-state reconciliation is best-effort by design: the + // filesystem restore succeeded and old snapshots may target hosts where policy + // providers or mutable-config repair are temporarily unavailable. Surface every + // failure as a warning, but keep the restore result tied to state restoration. + // #5027/#4538: openclaw.json restores via the generic copy strategy, which + // lands it at 0640. Repair the mutable config contract when needed. + repairRestoredOpenClawConfigPerms(targetSandbox, result); + // Reconcile custom policy presets (applied via --from-file/--from-dir). + // Skipped for legacy snapshots that predate the `customPolicies` field. + reconcileSnapshotCustomPolicies(targetSandbox, resolvedSnapshot); + // Reconcile built-in presets after custom content so same-name custom + // policies are never transiently substituted with a built-in. The current + // target observability bit and tier override historical built-in OTLP state. + // Legacy snapshots skip unrelated generic presets but still reconcile the + // managed observability binding from current target state. + reconcileSnapshotPolicyPresets(targetSandbox, resolvedSnapshot); + }, + ); } export async function runSandboxSnapshot( diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index f8c8d01b2a8..dffcdc89753 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2884,7 +2884,7 @@ async function createSandboxWithBaseImageResolution( buildContext.extractBuiltImageRef(`${firstCreateOutput}\n${createResult.output}`) ?? resolveSandboxImageTagFromCreateOutput(`${firstCreateOutput}\n${createResult.output}`, buildId); const sandboxRuntimeFields = getSandboxRuntimeRegistryFields(effectiveSandboxGpuConfig); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName, restoreBackupPath, @@ -2899,8 +2899,12 @@ async function createSandboxWithBaseImageResolution( }, { // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. - discoverFreshOpenClawImagePluginInstalls: (name) => openClawPluginRestore.discoverFreshOpenClawImagePluginInstalls(name, sandboxState, agent?.configPaths.dir), - restoreRecreatedSandboxState: sandboxState.restoreRecreatedSandboxState, + discoverFreshOpenClawImagePluginInstalls: (name) => openClawPluginRestore.discoverFreshOpenClawImagePluginInstalls(name, GATEWAY_NAME, agent?.configPaths.dir), + restoreRecreatedSandboxState: (name, backupPath, options) => + sandboxState.restoreRecreatedSandboxState(name, backupPath, { + ...options, + gatewayName: GATEWAY_NAME, + }), getDcodeSelectionDrift: (name, selectedProvider, selectedModel, selectedApi) => getDcodeSelectionDrift(name, selectedProvider, selectedModel, selectedApi, { runCaptureOpenshell, diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index f470719fa59..9792e1c3229 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -8,6 +8,44 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +vi.mock("../adapters/openshell/sandbox-control-routing", async () => { + const { spawnSync } = await import("node:child_process"); + const exec = async (request: { + command: readonly string[]; + stdin?: string | Buffer; + maxOutputBytes?: number; + timeoutMs?: number; + stdoutEncoding?: "utf8" | "buffer"; + }) => { + const binary = request.stdoutEncoding === "buffer"; + const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: binary ? undefined : "utf8", + }); + 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 } : {}), + }; + }; + return { + execSandboxReadOnlyWithGrpcFallback: async ( + _gateway: string, + request: Parameters[0], + ) => exec(request), + selectOpenShellSandboxControlForMutation: () => ({ + control: { exec }, + transport: "grpc", + close: () => {}, + }), + }; +}); + import * as sandboxState from "../state/sandbox"; import { finalizeCreatedSandbox } from "./created-sandbox-finalization"; import { getDcodeSelectionDrift } from "./dcode-selection-drift"; @@ -182,12 +220,12 @@ function identityFromConfig(config: string): string { } describe("created DCode sandbox finalization", () => { - it("merges stale backup preferences before live validation and registry publication (#6311)", () => { + it("merges stale backup preferences before live validation and registry publication (#6311)", async () => { const fixture = makeRestoreFixture(); const order: string[] = []; const registeredConfigs: string[] = []; try { - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "dcode", restoreBackupPath: fixture.backupPath, @@ -199,12 +237,12 @@ describe("created DCode sandbox finalization", () => { preferredInferenceApi: null, }, { - discoverFreshOpenClawImagePluginInstalls: () => ({ + discoverFreshOpenClawImagePluginInstalls: async () => ({ ok: true, extensionDirs: [], pluginInstalls: [], }), - restoreRecreatedSandboxState: (name, backup, options) => { + restoreRecreatedSandboxState: async (name, backup, options) => { order.push("restore"); expect(options.allowCustomImageWholeStateFileRestore).toBeUndefined(); return sandboxState.restoreRecreatedSandboxState(name, backup, options); @@ -239,10 +277,10 @@ describe("created DCode sandbox finalization", () => { } }); - it("does not publish registry metadata when live validation fails (#6311)", () => { + it("does not publish registry metadata when live validation fails (#6311)", async () => { const register = vi.fn(); const error = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "dcode", @@ -273,7 +311,7 @@ describe("created DCode sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(register).not.toHaveBeenCalled(); expect(error).toHaveBeenCalledWith(expect.stringContaining("sandbox still exists")); expect(error).toHaveBeenCalledWith(expect.stringContaining("rebuild is unsafe")); @@ -281,12 +319,12 @@ describe("created DCode sandbox finalization", () => { expect(error).toHaveBeenCalledWith(expect.stringContaining("nemoclaw onboard")); }); - it("warns but verifies and registers after a partial workspace restore (#6311)", () => { + it("warns but verifies and registers after a partial workspace restore (#6311)", async () => { const fixture = makeRestoreFixture(); const registeredConfigs: string[] = []; const error = vi.fn(); try { - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "dcode", restoreBackupPath: fixture.backupPath, @@ -299,8 +337,8 @@ describe("created DCode sandbox finalization", () => { }, { discoverFreshOpenClawImagePluginInstalls: vi.fn(), - restoreRecreatedSandboxState: (name, backup, options) => { - const restored = sandboxState.restoreRecreatedSandboxState(name, backup, options); + restoreRecreatedSandboxState: async (name, backup, options) => { + const restored = await sandboxState.restoreRecreatedSandboxState(name, backup, options); return { ...restored, success: false, failedDirs: ["skills"] }; }, getDcodeSelectionDrift: (name, provider, model, api) => @@ -332,11 +370,11 @@ describe("created DCode sandbox finalization", () => { } }); - it("keeps custom-image restores outside the managed config merge (#6311)", () => { + it("keeps custom-image restores outside the managed config merge (#6311)", async () => { const fixture = makeRestoreFixture(); const registeredConfigs: string[] = []; try { - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "custom-dcode", restoreBackupPath: fixture.backupPath, @@ -350,7 +388,7 @@ describe("created DCode sandbox finalization", () => { }, { discoverFreshOpenClawImagePluginInstalls: vi.fn(), - restoreRecreatedSandboxState: (name, backup, options) => { + restoreRecreatedSandboxState: async (name, backup, options) => { expect(options.allowCustomImageWholeStateFileRestore).toBe(true); return sandboxState.restoreRecreatedSandboxState(name, backup, options); }, @@ -384,11 +422,11 @@ describe("created OpenClaw sandbox finalization", () => { }, ]; - it("skips image-plugin discovery for a managed OpenClaw image", () => { + it("skips image-plugin discovery for a managed OpenClaw image", async () => { const discoverFreshOpenClawImagePluginInstalls = vi.fn(); const register = vi.fn(); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "openclaw", restoreBackupPath: null, @@ -416,12 +454,12 @@ describe("created OpenClaw sandbox finalization", () => { expect(register).toHaveBeenCalledWith(undefined); }); - it("captures and registers a fresh image plugin baseline without a restore", () => { + it("captures and registers a fresh image plugin baseline without a restore", async () => { const order: string[] = []; const restoreRecreatedSandboxState = vi.fn(); const register = vi.fn(() => order.push("register")); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "openclaw", restoreBackupPath: null, @@ -434,7 +472,7 @@ describe("created OpenClaw sandbox finalization", () => { preferredInferenceApi: "openai-completions", }, { - discoverFreshOpenClawImagePluginInstalls: () => { + discoverFreshOpenClawImagePluginInstalls: async () => { order.push("discover"); return { ok: true, extensionDirs: ["weather"], pluginInstalls }; }, @@ -454,10 +492,10 @@ describe("created OpenClaw sandbox finalization", () => { expect(register).toHaveBeenCalledWith(pluginInstalls); }); - it("preserves the fresh image plugin baseline across recreation before registration", () => { + it("preserves the fresh image plugin baseline across recreation before registration", async () => { const order: string[] = []; const register = vi.fn(() => order.push("register")); - const restoreRecreatedSandboxState = vi.fn(() => { + const restoreRecreatedSandboxState = vi.fn(async () => { order.push("restore"); return { success: true, @@ -468,7 +506,7 @@ describe("created OpenClaw sandbox finalization", () => { }; }); - finalizeCreatedSandbox( + await finalizeCreatedSandbox( { sandboxName: "openclaw", restoreBackupPath: "/tmp/openclaw-backup", @@ -481,7 +519,7 @@ describe("created OpenClaw sandbox finalization", () => { preferredInferenceApi: "openai-completions", }, { - discoverFreshOpenClawImagePluginInstalls: () => { + discoverFreshOpenClawImagePluginInstalls: async () => { order.push("discover"); return { ok: true, extensionDirs: ["weather"], pluginInstalls }; }, @@ -504,12 +542,12 @@ describe("created OpenClaw sandbox finalization", () => { expect(register).toHaveBeenCalledWith(pluginInstalls); }); - it("fails closed before restore and registration when provenance discovery fails", () => { + it("fails closed before restore and registration when provenance discovery fails", async () => { const restoreRecreatedSandboxState = vi.fn(); const register = vi.fn(); const error = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "openclaw", @@ -523,7 +561,7 @@ describe("created OpenClaw sandbox finalization", () => { preferredInferenceApi: "openai-completions", }, { - discoverFreshOpenClawImagePluginInstalls: () => ({ + discoverFreshOpenClawImagePluginInstalls: async () => ({ ok: false, error: "registry unreadable", }), @@ -537,7 +575,7 @@ describe("created OpenClaw sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(restoreRecreatedSandboxState).not.toHaveBeenCalled(); expect(register).not.toHaveBeenCalled(); @@ -552,11 +590,11 @@ describe("created OpenClaw sandbox finalization", () => { expect(error).toHaveBeenCalledWith(" Manual recovery: /tmp/openclaw-backup"); }); - it("does not register after a marked backup provenance mismatch", () => { + it("does not register after a marked backup provenance mismatch", async () => { const register = vi.fn(); const error = vi.fn(); - expect(() => + await expect( finalizeCreatedSandbox( { sandboxName: "openclaw", @@ -570,12 +608,12 @@ describe("created OpenClaw sandbox finalization", () => { preferredInferenceApi: "openai-completions", }, { - discoverFreshOpenClawImagePluginInstalls: () => ({ + discoverFreshOpenClawImagePluginInstalls: async () => ({ ok: true, extensionDirs: ["weather"], pluginInstalls, }), - restoreRecreatedSandboxState: () => ({ + restoreRecreatedSandboxState: async () => ({ success: false, restoredDirs: [], failedDirs: ["manifest"], @@ -592,7 +630,7 @@ describe("created OpenClaw sandbox finalization", () => { }, }, ), - ).toThrow("exit 1"); + ).rejects.toThrow("exit 1"); expect(register).not.toHaveBeenCalled(); expect(error).toHaveBeenCalledWith(expect.stringContaining("future rebuild would be unsafe")); diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index f95dc3c22ee..04a46f12e58 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -28,12 +28,12 @@ export type CreatedSandboxFinalizationOptions = { export type CreatedSandboxFinalizationDeps = { discoverFreshOpenClawImagePluginInstalls( sandboxName: string, - ): OpenClawManagedExtensionDiscoveryResult; + ): Promise; restoreRecreatedSandboxState( sandboxName: string, backupPath: string, options: RecreatedSandboxRestoreOptions, - ): RestoreResult; + ): Promise; getDcodeSelectionDrift( sandboxName: string, provider: string, @@ -47,13 +47,13 @@ export type CreatedSandboxFinalizationDeps = { }; /** Restore state and validate the live managed DCode route before registry publication. */ -export function finalizeCreatedSandbox( +export async function finalizeCreatedSandbox( options: CreatedSandboxFinalizationOptions, deps: CreatedSandboxFinalizationDeps, -): void { +): Promise { let freshOpenClawImagePluginInstalls: readonly OpenClawImagePluginInstall[] | undefined; if (options.discoverOpenClawImagePluginInstalls === true) { - const discovery = deps.discoverFreshOpenClawImagePluginInstalls(options.sandboxName); + const discovery = await deps.discoverFreshOpenClawImagePluginInstalls(options.sandboxName); if (!discovery.ok) { deps.error( ` OpenClaw image plugin discovery failed for sandbox '${options.sandboxName}': ${discovery.error}`, @@ -74,7 +74,7 @@ export function finalizeCreatedSandbox( ? " Restoring workspace state from pre-upgrade backup..." : " Restoring workspace state from pre-recreate backup...", ); - const restore = deps.restoreRecreatedSandboxState( + const restore = await deps.restoreRecreatedSandboxState( options.sandboxName, options.restoreBackupPath, { diff --git a/src/lib/state/openclaw-config-restore-input.test.ts b/src/lib/state/openclaw-config-restore-input.test.ts index 34c52f9e6e9..ec37db8d1cf 100644 --- a/src/lib/state/openclaw-config-restore-input.test.ts +++ b/src/lib/state/openclaw-config-restore-input.test.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; import { buildOpenClawConfigRestoreInput, @@ -96,8 +96,8 @@ describe("buildOpenClawConfigRestoreInput", () => { }); describe("buildOpenClawConfigRestoreInputFromSandbox", () => { - it("identifies incomplete previous image provenance before reading live state (#6108)", () => { - const result = buildOpenClawConfigRestoreInputFromSandbox({ + it("identifies incomplete previous image provenance before reading live state (#6108)", async () => { + const result = await buildOpenClawConfigRestoreInputFromSandbox({ backupContents: bufferJson({ plugins: { entries: {} } }), dir: "/sandbox/.openclaw", freshImagePluginInstalls: [], @@ -107,8 +107,9 @@ describe("buildOpenClawConfigRestoreInputFromSandbox", () => { installPath: "/sandbox/.openclaw/extensions/weather", }, ], + sandboxControl: { exec: vi.fn() }, + sandboxName: "alpha", specPath: "openclaw.json", - sshArgs: [], }); expect(result).toEqual({ diff --git a/src/lib/state/openclaw-config-restore-input.ts b/src/lib/state/openclaw-config-restore-input.ts index f518b8f017e..4375d02f5a6 100644 --- a/src/lib/state/openclaw-config-restore-input.ts +++ b/src/lib/state/openclaw-config-restore-input.ts @@ -1,8 +1,7 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "child_process"; - +import type { OpenShellSandboxControl } from "../adapters/openshell/sandbox-control.js"; import { shellQuote } from "../runner.js"; import { mergeOpenClawRestoredConfig, @@ -23,8 +22,9 @@ export interface OpenClawConfigRestoreFromSandboxOptions { freshImagePluginInstalls?: readonly OpenClawImagePluginInstall[]; log?: (message: string) => void; previousImagePluginInstalls?: readonly OpenClawImagePluginInstall[]; + sandboxControl: OpenShellSandboxControl; + sandboxName: string; specPath: string; - sshArgs: readonly string[]; } function openClawConfigRemotePath(dir: string, specPath: string): string { @@ -42,22 +42,27 @@ export function buildOpenClawConfigReadCommand(dir: string, specPath: string): s ].join("; "); } -function readCurrentOpenClawConfig( - sshArgs: readonly string[], +async function readCurrentOpenClawConfig( + sandboxControl: OpenShellSandboxControl, + sandboxName: string, dir: string, specPath: string, log: (message: string) => void, -): Buffer | null { +): Promise { const command = buildOpenClawConfigReadCommand(dir, specPath); - const result = spawnSync("ssh", [...sshArgs, command], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 120000, - maxBuffer: 256 * 1024 * 1024, + const result = await sandboxControl.exec({ + sandboxName, + command: ["sh", "-c", command], + timeoutMs: 120_000, + maxOutputBytes: 256 * 1024 * 1024, + stdoutEncoding: "buffer", }); - if (result.status === 0 && !result.error && !result.signal) return result.stdout; + if (result.status === 0 && !result.error && !result.signal && result.stdoutBytes) { + return result.stdoutBytes; + } if (result.status !== 2) { const detail = - (result.stderr?.toString() || "").trim() || + result.stderr.trim() || result.error?.message || (result.signal ? `signal ${result.signal}` : `exit ${String(result.status)}`); log(`WARNING: state file current read ${specPath} failed: ${detail.substring(0, 200)}`); @@ -88,15 +93,16 @@ export function buildOpenClawConfigRestoreInput( } } -export function buildOpenClawConfigRestoreInputFromSandbox({ +export async function buildOpenClawConfigRestoreInputFromSandbox({ backupContents, dir, freshImagePluginInstalls, log = () => {}, previousImagePluginInstalls, + sandboxControl, + sandboxName, specPath, - sshArgs, -}: OpenClawConfigRestoreFromSandboxOptions): OpenClawConfigRestoreInputResult { +}: OpenClawConfigRestoreFromSandboxOptions): Promise { if ((previousImagePluginInstalls === undefined) !== (freshImagePluginInstalls === undefined)) { return { ok: false, @@ -117,7 +123,7 @@ export function buildOpenClawConfigRestoreInputFromSandbox({ } return buildOpenClawConfigRestoreInput( backupContents, - readCurrentOpenClawConfig(sshArgs, dir, specPath, log), + await readCurrentOpenClawConfig(sandboxControl, sandboxName, dir, specPath, log), { freshImagePluginInstalls, previousImagePluginInstalls }, ); } diff --git a/src/lib/state/openclaw-plugin-restore.ts b/src/lib/state/openclaw-plugin-restore.ts index d78ee0d8dbf..51b7c84e16a 100644 --- a/src/lib/state/openclaw-plugin-restore.ts +++ b/src/lib/state/openclaw-plugin-restore.ts @@ -2,11 +2,10 @@ // SPDX-License-Identifier: Apache-2.0 import path from "node:path"; -import { spawnSync } from "child_process"; +import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing.js"; import { isObjectRecord } from "../core/json-types.js"; import { shellQuote } from "../core/shell-quote.js"; -import { createTempSshConfig } from "../sandbox/temp-ssh-config.js"; import { OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS, shouldPreserveOpenClawManagedExtensions, @@ -48,11 +47,6 @@ export type CompleteOpenClawImagePluginInstall = Omit { +): Promise>> { // OpenClaw 2026.6.10 moved install records into its shared SQLite state. // Fall back only when that database is absent so a corrupt/incomplete // canonical index cannot be masked by stale legacy JSON. - const sqliteResult = spawnSync( - "ssh", - [...deps.sshArgs(configFile, sandboxName), buildFreshOpenClawPluginIndexSqliteReadCommand(dir)], - { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - maxBuffer: OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES, - }, - ); + const sqliteResult = await execSandboxReadOnlyWithGrpcFallback(gatewayName, { + sandboxName, + command: ["sh", "-c", buildFreshOpenClawPluginIndexSqliteReadCommand(dir)], + timeoutMs: 30_000, + maxOutputBytes: OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES, + }); if (sqliteResult.status !== 2 || sqliteResult.error || sqliteResult.signal) return sqliteResult; - return spawnSync( - "ssh", - [...deps.sshArgs(configFile, sandboxName), buildLegacyOpenClawPluginIndexReadCommand(dir)], - { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - maxBuffer: OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES, - }, - ); + return execSandboxReadOnlyWithGrpcFallback(gatewayName, { + sandboxName, + command: ["sh", "-c", buildLegacyOpenClawPluginIndexReadCommand(dir)], + timeoutMs: 30_000, + maxOutputBytes: OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES, + }); } -export function discoverFreshOpenClawPluginExtensionDirs( - deps: OpenClawPluginDiscoveryDeps, - configFile: string, +export async function discoverFreshOpenClawPluginExtensionDirs( + gatewayName: string, sandboxName: string, dir: string, -): OpenClawManagedExtensionDiscoveryResult { - const result = readFreshOpenClawPluginInstallIndex(deps, configFile, sandboxName, dir); - if ( - result.stdout && - Buffer.byteLength(result.stdout) > OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES - ) { +): Promise { + const result = await readFreshOpenClawPluginInstallIndex(gatewayName, sandboxName, dir); + if (Buffer.byteLength(result.stdout) > OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES) { return { ok: false, error: "fresh OpenClaw plugin install registry response too large" }; } if (result.status !== 0 || result.error || result.signal || !result.stdout) { @@ -182,7 +165,7 @@ export function discoverFreshOpenClawPluginExtensionDirs( let config: unknown; try { - config = JSON.parse(result.stdout.toString("utf-8")) as unknown; + config = JSON.parse(result.stdout) as unknown; } catch { return { ok: false, @@ -195,21 +178,12 @@ export function discoverFreshOpenClawPluginExtensionDirs( : { ok: false, error: "fresh OpenClaw plugin install registry failed validation" }; } -export function discoverFreshOpenClawImagePluginInstalls( +export async function discoverFreshOpenClawImagePluginInstalls( sandboxName: string, - deps: OpenClawPluginDiscoveryDeps, + gatewayName: string, dir = "/sandbox/.openclaw", -): OpenClawManagedExtensionDiscoveryResult { - const sshConfig = deps.getSshConfig(sandboxName); - if (!sshConfig) { - return { ok: false, error: "could not get SSH config for OpenClaw plugin discovery" }; - } - const tempSshConfig = createTempSshConfig(sshConfig, "nemoclaw-plugin-discovery-"); - try { - return discoverFreshOpenClawPluginExtensionDirs(deps, tempSshConfig.file, sandboxName, dir); - } finally { - tempSshConfig.cleanup(); - } +): Promise { + return discoverFreshOpenClawPluginExtensionDirs(gatewayName, sandboxName, dir); } function isSafeOpenClawPluginInstallId(id: string): boolean { diff --git a/src/lib/state/sandbox-openclaw-plugin-restore.test.ts b/src/lib/state/sandbox-openclaw-plugin-restore.test.ts index e5f81479378..7804b6ff2a8 100644 --- a/src/lib/state/sandbox-openclaw-plugin-restore.test.ts +++ b/src/lib/state/sandbox-openclaw-plugin-restore.test.ts @@ -1,49 +1,40 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "child_process"; - import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; -vi.mock("child_process", async (importOriginal) => { - const actual = await importOriginal(); - return { ...actual, spawnSync: vi.fn() }; -}); +import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing"; + +vi.mock("../adapters/openshell/sandbox-control-routing", () => ({ + execSandboxReadOnlyWithGrpcFallback: vi.fn(), +})); import { discoverFreshOpenClawPluginExtensionDirs } from "./openclaw-plugin-restore"; const OPENCLAW_DIR = "/sandbox/.openclaw"; const MAX_PLUGIN_REGISTRY_BYTES = 1024 * 1024; -function spawnResult( +function sandboxExecResult( status: number | null, - stdout: Buffer, + stdout: string, options: { error?: Error; signal?: NodeJS.Signals | null } = {}, -): ReturnType { +): Awaited> { return { - error: options.error, status, - signal: options.signal ?? null, - output: [null, stdout, Buffer.alloc(0)], - pid: 1234, stdout, - stderr: Buffer.alloc(0), - } as ReturnType; + stderr: "", + ...(options.error ? { error: options.error } : {}), + ...(options.signal ? { signal: options.signal } : {}), + }; } function discover() { - return discoverFreshOpenClawPluginExtensionDirs( - { - getSshConfig: () => "unused", - sshArgs: (configFile, sandboxName) => ["-F", configFile, `openshell-${sandboxName}`], - }, - "/tmp/ssh-config", - "sandbox-one", - OPENCLAW_DIR, - ); + return discoverFreshOpenClawPluginExtensionDirs("gateway-one", "sandbox-one", OPENCLAW_DIR); } describe("fresh OpenClaw plugin registry reads", () => { + const execMock = vi.mocked(execSandboxReadOnlyWithGrpcFallback); + beforeEach(() => { vi.clearAllMocks(); }); @@ -52,65 +43,71 @@ describe("fresh OpenClaw plugin registry reads", () => { vi.restoreAllMocks(); }); - it("rejects an oversized SQLite registry response before JSON.parse", () => { + it("rejects an oversized SQLite registry response before JSON.parse", async () => { const parseSpy = vi.spyOn(JSON, "parse"); - vi.mocked(spawnSync).mockReturnValue(spawnResult(0, Buffer.alloc(5 * 1024 * 1024, " "))); + execMock.mockResolvedValue(sandboxExecResult(0, " ".repeat(5 * 1024 * 1024))); - expect(discover()).toEqual({ + await expect(discover()).resolves.toEqual({ ok: false, error: "fresh OpenClaw plugin install registry response too large", }); expect(parseSpy).not.toHaveBeenCalled(); - expect(spawnSync).toHaveBeenCalledOnce(); - expect(vi.mocked(spawnSync).mock.calls[0]?.[2]).toEqual( - expect.objectContaining({ maxBuffer: MAX_PLUGIN_REGISTRY_BYTES, timeout: 30000 }), + expect(execMock).toHaveBeenCalledOnce(); + expect(execMock.mock.calls[0]?.[1]).toEqual( + expect.objectContaining({ + maxOutputBytes: MAX_PLUGIN_REGISTRY_BYTES, + timeoutMs: 30_000, + }), ); }); - it("classifies a real maxBuffer ENOBUFS result before parsing truncated output", () => { + it("classifies a bounded-output transport failure before parsing truncated output", async () => { const parseSpy = vi.spyOn(JSON, "parse"); - const error = Object.assign(new Error("spawnSync ssh ENOBUFS"), { code: "ENOBUFS" }); - vi.mocked(spawnSync).mockReturnValue( - spawnResult(null, Buffer.alloc(MAX_PLUGIN_REGISTRY_BYTES + 8192, " "), { + const error = new Error("sandbox exec output limit exceeded"); + execMock.mockResolvedValue( + sandboxExecResult(null, " ".repeat(MAX_PLUGIN_REGISTRY_BYTES + 8192), { error, signal: "SIGTERM", }), ); - expect(discover()).toEqual({ + await expect(discover()).resolves.toEqual({ ok: false, error: "fresh OpenClaw plugin install registry response too large", }); expect(parseSpy).not.toHaveBeenCalled(); - expect(spawnSync).toHaveBeenCalledOnce(); + expect(execMock).toHaveBeenCalledOnce(); }); - it("rejects an oversized legacy registry response after the status-2 fallback", () => { + it("rejects an oversized legacy registry response after the status-2 fallback", async () => { const parseSpy = vi.spyOn(JSON, "parse"); - vi.mocked(spawnSync) - .mockReturnValueOnce(spawnResult(2, Buffer.alloc(0))) - .mockReturnValueOnce(spawnResult(0, Buffer.alloc(5 * 1024 * 1024, " "))); + execMock + .mockResolvedValueOnce(sandboxExecResult(2, "")) + .mockResolvedValueOnce(sandboxExecResult(0, " ".repeat(5 * 1024 * 1024))); - expect(discover()).toEqual({ + await expect(discover()).resolves.toEqual({ ok: false, error: "fresh OpenClaw plugin install registry response too large", }); expect(parseSpy).not.toHaveBeenCalled(); - expect(spawnSync).toHaveBeenCalledTimes(2); - for (const call of vi.mocked(spawnSync).mock.calls) { - expect(call[2]).toEqual( - expect.objectContaining({ maxBuffer: MAX_PLUGIN_REGISTRY_BYTES, timeout: 30000 }), + expect(execMock).toHaveBeenCalledTimes(2); + for (const call of execMock.mock.calls) { + expect(call[1]).toEqual( + expect.objectContaining({ + maxOutputBytes: MAX_PLUGIN_REGISTRY_BYTES, + timeoutMs: 30_000, + }), ); } }); - it.each([10, 11])("does not use the legacy fallback for SQLite status %i", (status) => { - vi.mocked(spawnSync).mockReturnValue(spawnResult(status, Buffer.alloc(0))); + it.each([10, 11])("does not use the legacy fallback for SQLite status %i", async (status) => { + execMock.mockResolvedValue(sandboxExecResult(status, "")); - expect(discover()).toEqual({ + await expect(discover()).resolves.toEqual({ ok: false, error: "could not read fresh OpenClaw plugin install registry", }); - expect(spawnSync).toHaveBeenCalledOnce(); + expect(execMock).toHaveBeenCalledOnce(); }); }); diff --git a/src/lib/state/sandbox-recreated-openclaw-restore.test.ts b/src/lib/state/sandbox-recreated-openclaw-restore.test.ts index 6fd08d0f1f5..acac0cbd91d 100644 --- a/src/lib/state/sandbox-recreated-openclaw-restore.test.ts +++ b/src/lib/state/sandbox-recreated-openclaw-restore.test.ts @@ -5,7 +5,45 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { describe, expect, it } from "vitest"; +import { describe, expect, it, vi } from "vitest"; + +vi.mock("../adapters/openshell/sandbox-control-routing", async () => { + const { spawnSync } = await import("node:child_process"); + const exec = async (request: { + command: readonly string[]; + stdin?: string | Buffer; + maxOutputBytes?: number; + timeoutMs?: number; + stdoutEncoding?: "utf8" | "buffer"; + }) => { + const binary = request.stdoutEncoding === "buffer"; + const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: binary ? undefined : "utf8", + }); + 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 } : {}), + }; + }; + return { + execSandboxReadOnlyWithGrpcFallback: async ( + _gateway: string, + request: Parameters[0], + ) => exec(request), + selectOpenShellSandboxControlForMutation: () => ({ + control: { exec }, + transport: "grpc", + close: () => {}, + }), + }; +}); import { restoreEnvBulk } from "../../../test/helpers/env-test-helpers.js"; import type { OpenClawImagePluginInstall } from "./openclaw-plugin-restore.js"; @@ -27,20 +65,20 @@ function extensionDir(install: OpenClawImagePluginInstall): string | null { return install.installPath.startsWith(prefix) ? install.installPath.slice(prefix.length) : null; } -function runRestoreScenario(options: { +async function runRestoreScenario(options: { backupConfig: Record; backupExtensionDirs: string[]; freshConfig: Record; freshPluginInstalls: OpenClawImagePluginInstall[]; previousPluginInstalls?: OpenClawImagePluginInstall[]; -}): { +}): Promise<{ cleanupCommand: string | undefined; freshMarkers: Record; - restore: ReturnType; + restore: Awaited>; restoredConfig: Record; staleUserExtensionExists: boolean; userExtensionMarker: string; -} { +}> { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recreated-restore-")); const previousOpenshellBin = process.env.NEMOCLAW_OPENSHELL_BIN; const previousPath = process.env.PATH; @@ -157,7 +195,7 @@ process.exit(1); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${previousPath ?? ""}`; - const restore = restoreRecreatedSandboxState("alpha", backupPath, { + const restore = await restoreRecreatedSandboxState("alpha", backupPath, { targetAgentType: "openclaw", freshOpenClawImagePluginInstalls: options.freshPluginInstalls, }); @@ -189,7 +227,7 @@ process.exit(1); } } -function expectSuccessfulRestore(result: ReturnType): void { +function expectSuccessfulRestore(result: Awaited>): void { expect(result.restore).toEqual({ success: true, restoredDirs: ["extensions"], @@ -205,11 +243,11 @@ describe("recreated OpenClaw state restore", () => { it.each([ { provenance: "missing legacy", previousPluginInstalls: undefined }, { provenance: "known-empty", previousPluginInstalls: [] }, - ])("restores config and extensions with $provenance previous provenance", ({ + ])("restores config and extensions with $provenance previous provenance", async ({ previousPluginInstalls, }) => { const weather = imageInstall("weather", "weather"); - const result = runRestoreScenario({ + const result = await runRestoreScenario({ previousPluginInstalls, freshPluginInstalls: [weather], backupExtensionDirs: ["weather"], @@ -242,11 +280,11 @@ describe("recreated OpenClaw state restore", () => { expect(result.cleanupCommand).toContain("! -name 'weather'"); }); - it("reconciles populated previous and fresh image-plugin provenance during config restore", () => { + it("reconciles populated previous and fresh image-plugin provenance during config restore", async () => { const previousWeather = imageInstall("weather", "weather-v1"); const freshWeather = imageInstall("weather", "weather-v2"); const userPluginPath = `${OPENCLAW_DIR}/extensions/user-plugin`; - const result = runRestoreScenario({ + const result = await runRestoreScenario({ previousPluginInstalls: [previousWeather], freshPluginInstalls: [freshWeather], backupExtensionDirs: ["weather-v1"], diff --git a/src/lib/state/sandbox-state-file-restore-contract.test.ts b/src/lib/state/sandbox-state-file-restore-contract.test.ts index 04a77425abf..22e4fd1dd56 100644 --- a/src/lib/state/sandbox-state-file-restore-contract.test.ts +++ b/src/lib/state/sandbox-state-file-restore-contract.test.ts @@ -65,10 +65,10 @@ describe("state-file restore target contract", () => { { path: "./config.toml", strategy: "copy" as const }, ], }, - ])("rejects repeated backup state-file $description", ({ stateFiles }) => { + ])("rejects repeated backup state-file $description", async ({ stateFiles }) => { const backupPath = writeBackup({ stateFiles }); - const result = restoreRecreatedSandboxState("alpha", backupPath, { + const result = await restoreRecreatedSandboxState("alpha", backupPath, { targetAgentType: "langchain-deepagents-code", }); @@ -77,12 +77,12 @@ describe("state-file restore target contract", () => { expect(result.failedFiles).toContain("config.toml"); }); - it("rejects a backup agent that does not match the recreated target", () => { + it("rejects a backup agent that does not match the recreated target", async () => { const backupPath = writeBackup({ stateFiles: [{ path: "config.toml", strategy: "copy" }], }); - const result = restoreRecreatedSandboxState("alpha", backupPath, { + const result = await restoreRecreatedSandboxState("alpha", backupPath, { targetAgentType: "openclaw", }); @@ -91,12 +91,12 @@ describe("state-file restore target contract", () => { expect(result.failedFiles).toEqual(["config.toml"]); }); - it("rejects a stale backup file that the target manifest does not declare", () => { + it("rejects a stale backup file that the target manifest does not declare", async () => { const backupPath = writeBackup({ stateFiles: [{ path: "stale.toml", strategy: "copy" }], }); - const result = restoreRecreatedSandboxState("alpha", backupPath, { + const result = await restoreRecreatedSandboxState("alpha", backupPath, { targetAgentType: "langchain-deepagents-code", }); @@ -105,12 +105,12 @@ describe("state-file restore target contract", () => { expect(result.failedFiles).toEqual(["stale.toml"]); }); - it("rejects a backup state-file strategy that differs from the target manifest", () => { + it("rejects a backup state-file strategy that differs from the target manifest", async () => { const backupPath = writeBackup({ stateFiles: [{ path: "config.toml", strategy: "sqlite_backup" }], }); - const result = restoreRecreatedSandboxState("alpha", backupPath, { + const result = await restoreRecreatedSandboxState("alpha", backupPath, { targetAgentType: "langchain-deepagents-code", }); @@ -119,13 +119,13 @@ describe("state-file restore target contract", () => { expect(result.failedFiles).toEqual(["config.toml"]); }); - it("rejects a backup state directory that differs from the current target manifest", () => { + it("rejects a backup state directory that differs from the current target manifest", async () => { const backupPath = writeBackup({ dir: "/sandbox/.unexpected", stateFiles: [{ path: "config.toml", strategy: "copy" }], }); - const result = restoreRecreatedSandboxState("alpha", backupPath, { + const result = await restoreRecreatedSandboxState("alpha", backupPath, { targetAgentType: "langchain-deepagents-code", }); diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index 9c93db305d7..05be76b9301 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -25,10 +25,10 @@ import os from "node:os"; import path from "node:path"; import { spawnSync } from "child_process"; -import { captureSandboxSshConfigCommand } from "../adapters/openshell/client.js"; -import { resolveOpenshell } from "../adapters/openshell/resolve.js"; -import { execSandboxReadOnlyWithGrpcFallback } from "../adapters/openshell/sandbox-control-routing.js"; -import { OPENSHELL_PROBE_TIMEOUT_MS } from "../adapters/openshell/timeouts.js"; +import { + execSandboxReadOnlyWithGrpcFallback, + selectOpenShellSandboxControlForMutation, +} from "../adapters/openshell/sandbox-control-routing.js"; import type { AgentStateFile } from "../agent/defs.js"; import { loadAgent } from "../agent/defs.js"; import { isObjectRecord, type UnknownRecord } from "../core/json-types.js"; @@ -38,7 +38,6 @@ import { } from "../domain/backup-failure.js"; import { shellQuote } from "../runner.js"; import { resolveSandboxGatewayName } from "../onboard/gateway-binding.js"; -import { createTempSshConfig } from "../sandbox/temp-ssh-config.js"; import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; import { buildRestoreCleanupCommand, @@ -170,6 +169,8 @@ export interface RecreatedSandboxRestoreOptions { allowCustomImageWholeStateFileRestore?: true; /** Pre-captured baseline avoids a second remote read during onboarding finalization. */ freshOpenClawImagePluginInstalls?: readonly OpenClawImagePluginInstall[]; + /** Explicit binding for a newly created sandbox not yet in the local registry. */ + gatewayName?: string; } interface InternalRestoreOptions { @@ -177,6 +178,7 @@ interface InternalRestoreOptions { allowCustomImageWholeStateFileRestore?: true; discoverFreshOpenClawImagePluginInstalls?: true; freshOpenClawImagePluginInstalls?: readonly OpenClawImagePluginInstall[]; + gatewayName?: string; } export interface TarValidationResult { @@ -544,36 +546,6 @@ export function safeTarExtract(tarBuffer: Buffer, targetDir: string): SafeExtrac return { success: true }; } -// ── Helpers ──────────────────────────────────────────────────────── - -export function getSshConfig(sandboxName: string): string | null { - const openshellBinary = resolveOpenshell(); - if (!openshellBinary) return null; - - const result = captureSandboxSshConfigCommand(openshellBinary, sandboxName, { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (result.status !== 0) return null; - return result.output; -} - -export function sshArgs(configFile: string, sandboxName: string): string[] { - return [ - "-F", - configFile, - "-o", - "StrictHostKeyChecking=no", - "-o", - "UserKnownHostsFile=/dev/null", - "-o", - "ConnectTimeout=10", - "-o", - "LogLevel=ERROR", - `openshell-${sandboxName}`, - ]; -} - function computeBlueprintDigest(): string | null { // Look for blueprint.yaml relative to the agent-defs ROOT const candidates = [ @@ -1262,7 +1234,10 @@ export async function backupSandboxState( /** * Restore state directories into a sandbox from a prior backup. */ -export function restoreSandboxState(sandboxName: string, backupPath: string): RestoreResult { +export async function restoreSandboxState( + sandboxName: string, + backupPath: string, +): Promise { const target = registry.getSandbox(sandboxName); if (!target) { return { @@ -1284,7 +1259,7 @@ export function restoreRecreatedSandboxState( sandboxName: string, backupPath: string, options: RecreatedSandboxRestoreOptions, -): RestoreResult { +): Promise { return restoreSandboxStateInternal(sandboxName, backupPath, { targetAgentType: options.targetAgentType, ...(options.allowCustomImageWholeStateFileRestore @@ -1295,14 +1270,15 @@ export function restoreRecreatedSandboxState( ? { discoverFreshOpenClawImagePluginInstalls: true } : {}), freshOpenClawImagePluginInstalls: options.freshOpenClawImagePluginInstalls, + gatewayName: options.gatewayName, }); } -function restoreSandboxStateInternal( +async function restoreSandboxStateInternal( sandboxName: string, backupPath: string, options: InternalRestoreOptions, -): RestoreResult { +): Promise { _log(`restoreSandboxState: sandbox=${sandboxName}, backupPath=${backupPath}`); const manifest = readManifest(backupPath); if (!manifest) { @@ -1410,6 +1386,15 @@ function restoreSandboxStateInternal( } } + let gatewayName: string; + try { + gatewayName = + options.gatewayName ?? resolveSandboxGatewayName(registry.getSandbox(sandboxName)); + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return failRestoreContract(`Could not resolve sandbox gateway: ${detail}`); + } + let freshOpenClawImagePluginInstalls: readonly OpenClawImagePluginInstall[] | undefined; if (options.freshOpenClawImagePluginInstalls !== undefined) { const parsed = parseOpenClawImagePluginInstalls( @@ -1425,9 +1410,9 @@ function restoreSandboxStateInternal( } freshOpenClawImagePluginInstalls = parsed.pluginInstalls; } else if (options.discoverFreshOpenClawImagePluginInstalls === true) { - const discovery = discoverFreshOpenClawImagePluginInstalls( + const discovery = await discoverFreshOpenClawImagePluginInstalls( sandboxName, - { getSshConfig, sshArgs }, + gatewayName, targetAgent.configPaths.dir, ); if (!discovery.ok) { @@ -1445,21 +1430,6 @@ function restoreSandboxStateInternal( return { success: true, restoredDirs, failedDirs, restoredFiles, failedFiles }; } - _log("Getting SSH config for restore"); - const sshConfig = getSshConfig(sandboxName); - if (!sshConfig) { - _log("FAILED: Could not get SSH config for restore"); - return { - success: false, - restoredDirs, - failedDirs: [...localDirs], - restoredFiles, - failedFiles: localFiles.map((f) => f.path), - }; - } - - const tempSshConfig = createTempSshConfig(sshConfig, "nemoclaw-state-"); - const configFile = tempSshConfig.file; const previousOpenClawImagePluginInstalls = freshOpenClawImagePluginInstalls !== undefined ? manifest.openclawImagePluginInstalls @@ -1473,39 +1443,46 @@ function restoreSandboxStateInternal( previousOpenClawImagePluginInstalls !== undefined ? freshOpenClawImagePluginInstalls : undefined; - try { - const pluginRestorePlan = planOpenClawPluginRestore({ - agentType: manifest.agentType, - dir, - localDirs, - freshImagePluginInstalls: freshOpenClawImagePluginInstalls, - previousImagePluginInstalls: previousOpenClawImagePluginInstalls, - }); - if (!pluginRestorePlan.ok) { - return { - success: false, - restoredDirs, - failedDirs: [...localDirs], - restoredFiles, - failedFiles: localFiles.map((f) => f.path), - error: - manifest.reconcileOpenClawImagePluginProvenance === true - ? OPENCLAW_IMAGE_PLUGIN_PROVENANCE_RESTORE_ERROR - : pluginRestorePlan.error, - }; - } - if ( - freshOpenClawImagePluginInstalls !== undefined && - pluginRestorePlan.preservedExtensionDirs.length > 0 - ) { - _log( - `Fresh image-managed OpenClaw extensions: [${pluginRestorePlan.freshExtensionDirs.join(",")}]`, - ); - _log( - `Previous image-managed OpenClaw extensions: [${pluginRestorePlan.previousExtensionDirs.join(",")}]`, - ); - } + const pluginRestorePlan = planOpenClawPluginRestore({ + agentType: manifest.agentType, + dir, + localDirs, + freshImagePluginInstalls: freshOpenClawImagePluginInstalls, + previousImagePluginInstalls: previousOpenClawImagePluginInstalls, + }); + if (!pluginRestorePlan.ok) { + return { + success: false, + restoredDirs, + failedDirs: [...localDirs], + restoredFiles, + failedFiles: localFiles.map((f) => f.path), + error: + manifest.reconcileOpenClawImagePluginProvenance === true + ? OPENCLAW_IMAGE_PLUGIN_PROVENANCE_RESTORE_ERROR + : pluginRestorePlan.error, + }; + } + if ( + freshOpenClawImagePluginInstalls !== undefined && + pluginRestorePlan.preservedExtensionDirs.length > 0 + ) { + _log( + `Fresh image-managed OpenClaw extensions: [${pluginRestorePlan.freshExtensionDirs.join(",")}]`, + ); + _log( + `Previous image-managed OpenClaw extensions: [${pluginRestorePlan.previousExtensionDirs.join(",")}]`, + ); + } + let mutation; + try { + mutation = selectOpenShellSandboxControlForMutation(gatewayName); + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return failRestoreContract(`Could not select sandbox restore transport: ${detail}`); + } + try { if (localDirs.length > 0) { // Upload via tar pipe // NC-2227-04: Removed -h flag from restore as well — no symlink following. @@ -1541,12 +1518,13 @@ function restoreSandboxStateInternal( new Set(pluginRestorePlan.requiredFreshExtensionDirs), ); _log(`Cleaning target dirs before restore: ${rmCmd}`); - const rmResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), rmCmd], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, + const rmResult = await mutation.control.exec({ + sandboxName, + command: ["sh", "-c", rmCmd], + timeoutMs: 30_000, }); if (rmResult.status !== 0 || rmResult.error || rmResult.signal) { - const stderr = (rmResult.stderr?.toString() || "").trim(); + const stderr = rmResult.stderr.trim(); const detail = stderr || rmResult.error?.message || @@ -1562,24 +1540,26 @@ function restoreSandboxStateInternal( } const extractCmd = `tar --no-same-owner -xf - -C ${shellQuote(dir)}`; - const sshResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), extractCmd], { - input: tarResult.stdout, - stdio: ["pipe", "pipe", "pipe"], - timeout: 120000, + const extractResult = await mutation.control.exec({ + sandboxName, + command: ["sh", "-c", extractCmd], + stdin: tarResult.stdout, + timeoutMs: 120_000, }); - if (sshResult.status === 0) { + if (extractResult.status === 0 && !extractResult.error && !extractResult.signal) { const restoredPaths = localDirs.map((d) => `${dir}/${d}`); - // Best-effort only: OpenShell exec/SSH normally runs as the sandbox user, + // Best-effort only: OpenShell exec normally runs as the sandbox user, // which cannot chown even files it owns. The tar restore above runs as the // same user, so the real restore gate is whether the restored state dirs // are usable by that user. const chownCmd = `chown -R sandbox:sandbox -- ${restoredPaths.map(shellQuote).join(" ")} 2>/dev/null || true`; _log(`Best-effort ownership repair: ${chownCmd}`); - const chownResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), chownCmd], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, + const chownResult = await mutation.control.exec({ + sandboxName, + command: ["sh", "-c", chownCmd], + timeoutMs: 30_000, }); if (chownResult.error || chownResult.signal) { const detail = @@ -1597,18 +1577,15 @@ function restoreSandboxStateInternal( ) .join(" && "); _log(`Verifying restored state usability: ${usabilityCmd}`); - const usabilityResult = spawnSync( - "ssh", - [...sshArgs(configFile, sandboxName), usabilityCmd], - { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - }, - ); + const usabilityResult = await mutation.control.exec({ + sandboxName, + command: ["sh", "-c", usabilityCmd], + timeoutMs: 30_000, + }); if (usabilityResult.status === 0 && !usabilityResult.error && !usabilityResult.signal) { restoredDirs.push(...localDirs); } else { - const stderr = (usabilityResult.stderr?.toString() || "").trim(); + const stderr = usabilityResult.stderr.trim(); const detail = stderr || usabilityResult.error?.message || @@ -1627,8 +1604,9 @@ function restoreSandboxStateInternal( const targetStateFile = targetStateFiles.get(spec.path); if (!targetStateFile) throw new Error(`Validated target state file missing: ${spec.path}`); if ( - restoreStateFile( - sshArgs(configFile, sandboxName), + await restoreStateFile( + mutation.control, + sandboxName, dir, spec, backupPath, @@ -1645,11 +1623,7 @@ function restoreSandboxStateInternal( } } } finally { - try { - tempSshConfig.cleanup(); - } catch { - /* ignore */ - } + mutation.close(); } return { diff --git a/src/lib/state/state-file-restore-custom-image.test.ts b/src/lib/state/state-file-restore-custom-image.test.ts index 6ede727bb85..52bab58317b 100644 --- a/src/lib/state/state-file-restore-custom-image.test.ts +++ b/src/lib/state/state-file-restore-custom-image.test.ts @@ -7,22 +7,16 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; +import type { OpenShellSandboxControl } from "../adapters/openshell/sandbox-control"; import type { StateFileKeyAllowlistRestoreOwnership } from "../agent/defs"; import { restoreStateFile } from "./state-file-restore"; -type SpawnSyncCall = ( - command: string, - args: readonly string[], - options: { input?: Buffer }, -) => { status: number; error?: Error; signal: NodeJS.Signals | null; stderr: Buffer }; - -const spawnSyncMock = vi.hoisted(() => - vi.fn(() => ({ status: 0, signal: null, stderr: Buffer.alloc(0) })), -); - -vi.mock("node:child_process", () => ({ - spawnSync: spawnSyncMock, +const execMock = vi.fn(async () => ({ + status: 0, + stdout: "", + stderr: "", })); +const sandboxControl = { exec: execMock }; const fixtures: string[] = []; const ownership: StateFileKeyAllowlistRestoreOwnership = { @@ -49,11 +43,12 @@ afterEach(() => { }); describe("custom-image state-file restore capability (#6334)", () => { - it("restores the complete backup without invoking the managed key allowlist", () => { + it("restores the complete backup without invoking the managed key allowlist", async () => { const { backupPath, backupContents } = createBackupFixture(); - const restored = restoreStateFile( - ["-F", "/tmp/ssh-config", "openshell-alpha"], + const restored = await restoreStateFile( + sandboxControl, + "alpha", "/sandbox/.deepagents", { path: "config.toml", strategy: "copy" }, backupPath, @@ -63,20 +58,20 @@ describe("custom-image state-file restore capability (#6334)", () => { ); expect(restored).toBe(true); - const [binary, args, options] = spawnSyncMock.mock.calls[0] ?? []; - expect(binary).toBe("ssh"); - const command = String(args?.at(-1)); + const request = execMock.mock.calls[0]?.[0]; + const command = String(request?.command.at(-1)); expect(command).toContain(".nemoclaw-restore.XXXXXX"); expect(command).not.toContain("/opt/venv/bin/python3"); expect(command).not.toContain("show_scrollbar"); - expect(options?.input).toEqual(backupContents); + expect(request?.stdin).toEqual(backupContents); }); - it("requires the capability before bypassing the managed key allowlist", () => { + it("requires the capability before bypassing the managed key allowlist", async () => { const { backupPath, backupContents } = createBackupFixture(); - const restored = restoreStateFile( - ["-F", "/tmp/ssh-config", "openshell-alpha"], + const restored = await restoreStateFile( + sandboxControl, + "alpha", "/sandbox/.deepagents", { path: "config.toml", strategy: "copy" }, backupPath, @@ -86,13 +81,12 @@ describe("custom-image state-file restore capability (#6334)", () => { ); expect(restored).toBe(true); - const [binary, args, options] = spawnSyncMock.mock.calls[0] ?? []; - expect(binary).toBe("ssh"); - const command = String(args?.at(-1)); + const request = execMock.mock.calls[0]?.[0]; + const command = String(request?.command.at(-1)); expect(command).toContain("/opt/venv/bin/python3 -I -c"); expect(command).toContain("show_scrollbar"); expect(command).toContain("require_fresh_tables"); expect(command).not.toContain(".nemoclaw-restore.XXXXXX"); - expect(options?.input).toEqual(backupContents); + expect(request?.stdin).toEqual(backupContents); }); }); diff --git a/src/lib/state/state-file-restore.ts b/src/lib/state/state-file-restore.ts index a893a599c44..84da15e56de 100644 --- a/src/lib/state/state-file-restore.ts +++ b/src/lib/state/state-file-restore.ts @@ -1,10 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { spawnSync } from "node:child_process"; import { existsSync, readFileSync } from "node:fs"; import path from "node:path"; +import type { OpenShellSandboxControl } from "../adapters/openshell/sandbox-control.js"; import type { StateFileRestoreOwnership } from "../agent/defs.js"; import { shellQuote } from "../runner.js"; import { buildOpenClawConfigRestoreInputFromSandbox } from "./openclaw-config-restore-input.js"; @@ -100,8 +100,9 @@ export function buildStateFileRestoreCommand( return steps.join("; "); } -export function restoreStateFile( - sshArgs: readonly string[], +export async function restoreStateFile( + sandboxControl: OpenShellSandboxControl, + sandboxName: string, dir: string, spec: StateFileRestoreSpec, backupPath: string, @@ -110,7 +111,7 @@ export function restoreStateFile( log: (message: string) => void, freshImagePluginInstalls?: readonly OpenClawImagePluginInstall[], previousImagePluginInstalls?: readonly OpenClawImagePluginInstall[], -): boolean { +): Promise { const localPath = path.join(backupPath, spec.path); if (!existsSync(localPath)) return true; @@ -121,14 +122,15 @@ export function restoreStateFile( let input: Buffer | null; if (ownership?.merge === "openclaw-config") { command = buildStateFileRestoreCommand(dir, spec, true); - const result = buildOpenClawConfigRestoreInputFromSandbox({ + const result = await buildOpenClawConfigRestoreInputFromSandbox({ backupContents, dir, freshImagePluginInstalls, log, previousImagePluginInstalls, + sandboxControl, + sandboxName, specPath: spec.path, - sshArgs, }); if (result.ok) { input = result.input; @@ -147,16 +149,17 @@ export function restoreStateFile( } if (input === null) return false; - const result = spawnSync("ssh", [...sshArgs, command], { - input, - stdio: ["pipe", "pipe", "pipe"], - timeout: 120000, + const result = await sandboxControl.exec({ + sandboxName, + command: ["sh", "-c", command], + stdin: input, + timeoutMs: 120_000, }); if (result.status === 0 && !result.error && !result.signal) return true; const detail = - (result.stderr?.toString() || "").trim() || + result.stderr.trim() || result.error?.message || (result.signal ? `signal ${result.signal}` : `exit ${String(result.status)}`); log(`FAILED: state file restore ${spec.path}: ${detail.substring(0, 200)}`); diff --git a/test/openclaw-config-restore.test.ts b/test/openclaw-config-restore.test.ts index 8e01fcc25cb..44008ccbf38 100644 --- a/test/openclaw-config-restore.test.ts +++ b/test/openclaw-config-restore.test.ts @@ -133,14 +133,14 @@ function staleBackupConfig(): string { ); } -function restoreOpenClawStateFileWithFakeSsh(options: { +async function restoreOpenClawStateFileWithFakeSsh(options: { backupContents: string; currentContents: string; currentReadMode?: CurrentOpenClawReadMode; -}): { - restore: ReturnType; +}): Promise<{ + restore: Awaited>; currentContents: string; -} { +}> { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-restore-fixture-")); const oldPath = process.env.PATH; const oldOpenshell = process.env.NEMOCLAW_OPENSHELL_BIN; @@ -195,7 +195,7 @@ process.exit(0); const { backupPath } = writeBackup("alpha", "2026-06-10T20-00-00-000Z"); fs.writeFileSync(path.join(backupPath, "openclaw.json"), options.backupContents); - const restore = sandboxState.restoreSandboxState("alpha", backupPath); + const restore = await sandboxState.restoreSandboxState("alpha", backupPath); return { restore, currentContents: fs.readFileSync(path.join(openclawDir, "openclaw.json"), "utf-8"), @@ -212,8 +212,8 @@ process.exit(0); } describe("OpenClaw config restore failure modes", () => { - it("fails closed when the current rebuilt openclaw.json cannot be read", () => { - const { restore, currentContents } = restoreOpenClawStateFileWithFakeSsh({ + it("fails closed when the current rebuilt openclaw.json cannot be read", async () => { + const { restore, currentContents } = await restoreOpenClawStateFileWithFakeSsh({ backupContents: staleBackupConfig(), currentContents: freshRuntimeConfig(), currentReadMode: "missing", @@ -226,8 +226,8 @@ describe("OpenClaw config restore failure modes", () => { expect(JSON.parse(currentContents).channels.slack).toBeUndefined(); }); - it("fails closed when the current rebuilt openclaw.json is invalid JSON", () => { - const { restore, currentContents } = restoreOpenClawStateFileWithFakeSsh({ + it("fails closed when the current rebuilt openclaw.json is invalid JSON", async () => { + const { restore, currentContents } = await restoreOpenClawStateFileWithFakeSsh({ backupContents: staleBackupConfig(), currentContents: freshRuntimeConfig(), currentReadMode: "invalid-json", @@ -242,8 +242,8 @@ describe("OpenClaw config restore failure modes", () => { ); }); - it("fails closed when the backed-up openclaw.json is invalid JSON", () => { - const { restore, currentContents } = restoreOpenClawStateFileWithFakeSsh({ + it("fails closed when the backed-up openclaw.json is invalid JSON", async () => { + const { restore, currentContents } = await restoreOpenClawStateFileWithFakeSsh({ backupContents: "{ invalid backup json", currentContents: freshRuntimeConfig(), }); diff --git a/test/openclaw-config-snapshot.test.ts b/test/openclaw-config-snapshot.test.ts index ca46258751d..23e531cabcf 100644 --- a/test/openclaw-config-snapshot.test.ts +++ b/test/openclaw-config-snapshot.test.ts @@ -8,17 +8,14 @@ import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; 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"; - }, - ) => { +vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { + const exec = async (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, @@ -34,8 +31,19 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => ({ ...(result.error ? { error: result.error } : {}), ...(result.signal ? { signal: result.signal } : {}), }; - }, -})); + }; + return { + execSandboxReadOnlyWithGrpcFallback: async ( + _gatewayName: string, + request: Parameters[0], + ) => exec(request), + selectOpenShellSandboxControlForMutation: () => ({ + control: { exec }, + transport: "grpc", + close: () => {}, + }), + }; +}); // sandbox-state computes its backup root from HOME at module load time. const ORIGINAL_HOME = process.env.HOME; @@ -240,7 +248,7 @@ describe("OpenClaw durable config file (#5027)", () => { 2, ), ); - const restore = sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); + const restore = await sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); expect(restore.success).toBe(true); expect(restore.restoredFiles).toEqual(["openclaw.json"]); @@ -375,7 +383,7 @@ describe("OpenClaw durable config file (#5027)", () => { ), ); - const restore = sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); + const restore = await sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); expect(restore.success).toBe(true); const after = JSON.parse(fs.readFileSync(path.join(openclawDir, "openclaw.json"), "utf-8")); diff --git a/test/snapshot-openclaw-managed-extensions.test.ts b/test/snapshot-openclaw-managed-extensions.test.ts index dfe5e8c20d1..a028495779b 100644 --- a/test/snapshot-openclaw-managed-extensions.test.ts +++ b/test/snapshot-openclaw-managed-extensions.test.ts @@ -6,7 +6,45 @@ 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", async () => { + const { spawnSync } = await import("node:child_process"); + const exec = async (request: { + command: readonly string[]; + stdin?: string | Buffer; + maxOutputBytes?: number; + timeoutMs?: number; + stdoutEncoding?: "utf8" | "buffer"; + }) => { + const binary = request.stdoutEncoding === "buffer"; + const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: binary ? undefined : "utf8", + }); + 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 } : {}), + }; + }; + return { + execSandboxReadOnlyWithGrpcFallback: async ( + _gatewayName: string, + request: Parameters[0], + ) => exec(request), + selectOpenShellSandboxControlForMutation: () => ({ + control: { exec }, + transport: "grpc", + close: () => {}, + }), + }; +}); import { restoreEnv, restoreEnvBulk } from "./helpers/env-test-helpers"; @@ -120,7 +158,7 @@ describe("OpenClaw managed extension snapshot restore", () => { it.each( installIndexCases, - )("preserves fresh extensions and handles image-plugin $name from the $installIndexSource install index", ({ + )("preserves fresh extensions and handles image-plugin $name from the $installIndexSource install index", async ({ installIndexSource, previousPlugin, freshPlugin, @@ -241,9 +279,13 @@ process.exit(0); process.env.NEMOCLAW_OPENSHELL_BIN = openshell; process.env.PATH = `${binDir}:${oldPath || ""}`; - const restore = sandboxState.restoreRecreatedSandboxState("alpha", manifest.backupPath, { - targetAgentType: "openclaw", - }); + const restore = await sandboxState.restoreRecreatedSandboxState( + "alpha", + manifest.backupPath, + { + targetAgentType: "openclaw", + }, + ); expect(restore.success).toBe(true); expect(restore.restoredDirs).toEqual(["extensions"]); for (const extensionName of managedExtensions) { @@ -292,9 +334,13 @@ process.exit(0); }, }), ); - const rejected = sandboxState.restoreRecreatedSandboxState("alpha", manifest.backupPath, { - targetAgentType: "openclaw", - }); + const rejected = await sandboxState.restoreRecreatedSandboxState( + "alpha", + manifest.backupPath, + { + targetAgentType: "openclaw", + }, + ); expect(rejected.success).toBe(false); expect(rejected.error).toBe("fresh OpenClaw plugin install registry failed validation"); expect(fs.existsSync(path.join(extensionsDir, previousPlugin))).toBe( diff --git a/test/snapshot-recovery-validation.test.ts b/test/snapshot-recovery-validation.test.ts index dbbb054b5b8..e1e36b238ed 100644 --- a/test/snapshot-recovery-validation.test.ts +++ b/test/snapshot-recovery-validation.test.ts @@ -111,18 +111,18 @@ describe("prepared rebuild backup recovery validation (#6114)", () => { }); }); - it("rejects a marked manifest without explicit image-plugin provenance", () => { + it("rejects a marked manifest without explicit image-plugin provenance", async () => { const manifest = writeBackup("alpha", "2026-07-01T06-50-42-045Z", { reconcileOpenClawImagePluginProvenance: true, }); expect(sandboxState.getLatestBackup("alpha")).toBeNull(); - expect( + await expect( sandboxState.restoreRecreatedSandboxState("alpha", String(manifest.backupPath), { targetAgentType: "openclaw", freshOpenClawImagePluginInstalls: [], }), - ).toMatchObject({ + ).resolves.toMatchObject({ success: false, error: sandboxState.OPENCLAW_IMAGE_PLUGIN_PROVENANCE_RESTORE_ERROR, }); diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts index 5df2b3cbc4e..10cc3ae558d 100644 --- a/test/snapshot.test.ts +++ b/test/snapshot.test.ts @@ -12,17 +12,14 @@ import { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; 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"; - }, - ) => { +vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { + const exec = async (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, @@ -38,8 +35,19 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => ({ ...(result.error ? { error: result.error } : {}), ...(result.signal ? { signal: result.signal } : {}), }; - }, -})); + }; + return { + execSandboxReadOnlyWithGrpcFallback: async ( + _gatewayName: string, + request: Parameters[0], + ) => exec(request), + selectOpenShellSandboxControlForMutation: () => ({ + control: { exec }, + transport: "grpc", + close: () => {}, + }), + }; +}); // Override HOME BEFORE importing sandbox-state — it reads process.env.HOME // at module-load time to compute REBUILD_BACKUPS_DIR. Captured original is @@ -298,7 +306,7 @@ describe("listBackups computes virtual versions", () => { }); expect(sandboxState.listBackups("test-sandbox")).toEqual([]); }); - it("does not restore backed-up directory entries that are plain files", () => { + it("does not restore backed-up directory entries that are plain files", async () => { const manifest = writeBackup("test-sandbox", "2026-04-21T14-00-00-000Z", { stateDirs: ["workspace"], backedUpDirs: ["workspace"], @@ -306,7 +314,10 @@ describe("listBackups computes virtual versions", () => { writeAgentRegistry("test-sandbox", "openclaw"); fs.writeFileSync(path.join(String(manifest.backupPath), "workspace"), "not a directory"); - const restore = sandboxState.restoreSandboxState("test-sandbox", String(manifest.backupPath)); + const restore = await sandboxState.restoreSandboxState( + "test-sandbox", + String(manifest.backupPath), + ); expect(restore).toEqual({ success: true, @@ -631,7 +642,7 @@ process.exit(0); expect(backup.manifest?.backedUpDirs).toEqual(["extensions"]); expect(fs.existsSync(path.join(backup.manifest!.backupPath, "agents"))).toBe(true); - const restore = sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); + const restore = await sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); expect(restore.success).toBe(true); expect(restore.restoredDirs).toEqual(["extensions"]); @@ -1286,7 +1297,10 @@ process.exit(0); // #5753 is "lost after rebuild" (backup + recreate + restore): restore // must list agent/skills among the dirs it brings back into the sandbox. - const restore = sandboxState.restoreSandboxState("deepagents", backup.manifest!.backupPath); + const restore = await sandboxState.restoreSandboxState( + "deepagents", + backup.manifest!.backupPath, + ); expect(restore.success).toBe(true); expect(restore.restoredDirs).toEqual( expect.arrayContaining([".state", "skills", "agent/skills"]), @@ -1432,7 +1446,7 @@ process.exit(0); fs.writeFileSync(path.join(hermesDir, "SOUL.md"), "changed soul\n"); fs.writeFileSync(path.join(hermesDir, ".hermes_history"), "changed history\n"); fs.writeFileSync(path.join(runtimeDir, "state.db"), "changed db\n"); - const restore = sandboxState.restoreSandboxState("hermes", backup.manifest!.backupPath); + const restore = await sandboxState.restoreSandboxState("hermes", backup.manifest!.backupPath); expect(restore.success).toBe(true); expect(restore.restoredFiles).toEqual(["SOUL.md", ".hermes_history", "runtime/state.db"]); expect(fs.readFileSync(path.join(hermesDir, "SOUL.md"), "utf-8")).toBe("original soul\n"); From 8fecb4990c171628982193356900d2f110f0117f Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:00:59 -0700 Subject: [PATCH 02/14] refactor(onboard): keep restore wiring compact Signed-off-by: Aaron Erickson --- src/lib/onboard.ts | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index dffcdc89753..bc6ba7e13bf 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2897,14 +2897,9 @@ async function createSandboxWithBaseImageResolution( model, preferredInferenceApi, }, + // biome-ignore format: keep src/lib/onboard.ts within the growth guardrail. { - // biome-ignore format: keep src/lib/onboard.ts net-neutral for growth guardrail. - discoverFreshOpenClawImagePluginInstalls: (name) => openClawPluginRestore.discoverFreshOpenClawImagePluginInstalls(name, GATEWAY_NAME, agent?.configPaths.dir), - restoreRecreatedSandboxState: (name, backupPath, options) => - sandboxState.restoreRecreatedSandboxState(name, backupPath, { - ...options, - gatewayName: GATEWAY_NAME, - }), + discoverFreshOpenClawImagePluginInstalls: (name) => openClawPluginRestore.discoverFreshOpenClawImagePluginInstalls(name, GATEWAY_NAME, agent?.configPaths.dir), restoreRecreatedSandboxState: (name, backupPath, options) => sandboxState.restoreRecreatedSandboxState(name, backupPath, { ...options, gatewayName: GATEWAY_NAME }), getDcodeSelectionDrift: (name, selectedProvider, selectedModel, selectedApi) => getDcodeSelectionDrift(name, selectedProvider, selectedModel, selectedApi, { runCaptureOpenshell, From f33497a09a3e39fca42cf31b1cffacebcbf3a5e0 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:17:20 -0700 Subject: [PATCH 03/14] test(snapshot): migrate restore transport fixtures Signed-off-by: Aaron Erickson --- .../sandbox/snapshot-auto-create-failure.test.ts | 1 + .../actions/sandbox/snapshot-restore-test-fixture.ts | 1 + test/onboard-custom-dockerfile.test.ts | 12 +++++++++++- 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts index b9d6692b7b1..92cf72d4772 100644 --- a/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts +++ b/src/lib/actions/sandbox/snapshot-auto-create-failure.test.ts @@ -80,6 +80,7 @@ vi.mock("../../shields", () => ({ })); vi.mock("../../shields/timer-bound-lock", () => ({ withTimerBoundShieldsMutationLock: vi.fn((_sandbox, _command, fn) => fn()), + withTimerBoundShieldsMutationLockAsync: vi.fn((_sandbox, _command, fn) => fn()), })); vi.mock("../../shields/timer-control", () => ({ readTimerMarker: vi.fn(() => null) })); vi.mock("../../state/gateway", () => ({ diff --git a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts index cfa7be5d49a..ba51a3136ee 100644 --- a/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts +++ b/src/lib/actions/sandbox/snapshot-restore-test-fixture.ts @@ -200,6 +200,7 @@ vi.mock("../../shields", () => ({ vi.mock("../../shields/timer-bound-lock", () => ({ withTimerBoundShieldsMutationLock: lifecycleMock.withTimerBoundMock, + withTimerBoundShieldsMutationLockAsync: lifecycleMock.withTimerBoundMock, })); vi.mock("../../shields/timer-control", () => ({ diff --git a/test/onboard-custom-dockerfile.test.ts b/test/onboard-custom-dockerfile.test.ts index bcd6b641d59..d6998bb45ef 100644 --- a/test/onboard-custom-dockerfile.test.ts +++ b/test/onboard-custom-dockerfile.test.ts @@ -186,6 +186,16 @@ describe("onboard custom Dockerfile", () => { fs.mkdirSync(fakeBin, { recursive: true }); writeOkOpenshell(fakeBin); + const gatewayDir = path.join(tmpDir, ".config", "openshell", "gateways", "nemoclaw"); + fs.mkdirSync(gatewayDir, { recursive: true }); + fs.writeFileSync( + path.join(gatewayDir, "metadata.json"), + JSON.stringify({ + name: "nemoclaw", + gateway_endpoint: "https://gateway.example.test", + auth_mode: "cloudflare_jwt", + }), + ); const customDockerfilePath = JSON.stringify(path.join(customBuildDir, "Dockerfile")); @@ -203,7 +213,7 @@ const path = require("node:path"); const originalSpawnSync = childProcess.spawnSync; childProcess.spawnSync = (command, args, options) => { const normalized = _n([command, ...(Array.isArray(args) ? args : [])]); - if (command === "ssh" && normalized.includes("installed_plugin_index")) { + if (String(command).endsWith("openshell") && normalized.includes("sandbox exec") && normalized.includes("installed_plugin_index")) { return { status: 0, signal: null, From 4ad33ab166bcf70cf9b662d1a2463e18b94bf365 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 16:24:07 -0700 Subject: [PATCH 04/14] test(snapshot): remove restore SSH fixture Signed-off-by: Aaron Erickson --- test/snapshot-gateway-guard.test.ts | 25 +++++++++++-------------- 1 file changed, 11 insertions(+), 14 deletions(-) diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index 1ccfedbc665..6624c0e858f 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -157,6 +157,16 @@ function makeVmRestoreToEnv( openshellDriver: "vm", ...entry, }); + const gatewayDir = path.join(home, ".config", "openshell", "gateways", "nemoclaw"); + fs.mkdirSync(gatewayDir, { recursive: true }); + fs.writeFileSync( + path.join(gatewayDir, "metadata.json"), + JSON.stringify({ + name: "nemoclaw", + gateway_endpoint: "https://gateway.example.test", + auth_mode: "cloudflare_jwt", + }), + ); const cloneReadyMarker = path.join(home, "clone-1-ready"); writeExecutable(path.join(localBin, "openshell"), [ @@ -164,26 +174,13 @@ function makeVmRestoreToEnv( ' "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") 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 exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *installed_plugin_index*) printf "{\\"version\\":1,\\"installRecords\\":{},\\"loadPaths\\":[]}" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; exit 0 ;;', ` "sandbox create") touch ${JSON.stringify(cloneReadyMarker)}; printf "created clone-1\\n"; exit 0 ;;`, "esac", 'if [ "$1" = "status" ]; then exit 0; fi', "exit 0", ]); - const remoteOpenClawJson = path.join(home, "remote-openclaw.json"); - fs.writeFileSync(remoteOpenClawJson, JSON.stringify({ gateway: { auth: { token: "fresh" } } })); - writeExecutable(path.join(localBin, "ssh"), [ - `REMOTE_OPENCLAW_JSON=${JSON.stringify(remoteOpenClawJson)}`, - 'cmd=""; for arg do cmd="$arg"; done', - 'if printf "%s" "$cmd" | grep -q "openclaw.json"; then', - ' if printf "%s" "$cmd" | grep -q "cat --"; then cat "$REMOTE_OPENCLAW_JSON"; exit 0; fi', - ' if printf "%s" "$cmd" | grep -q ".nemoclaw-restore"; then cat > "$REMOTE_OPENCLAW_JSON"; exit 0; fi', - "fi", - "exit 0", - ]); - // `docker exec` must never run: if the fast path regresses, // resolveSrcPodImage falls into the kubectl-via-docker probe and this // marker shows up in the captured output. From f00ec9ebc194ac633aead44ff21d0e417479aae9 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 18:05:53 -0700 Subject: [PATCH 05/14] test(snapshot): report CLI output on restore failure --- test/snapshot-gateway-guard.test.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index 6624c0e858f..b88e4ae6f8e 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -218,7 +218,7 @@ describe("snapshot VM-driver gateway guard", () => { it("snapshot create accepts healthy macOS VM-driver gateways without legacy cluster container", () => { const env = makeHealthyVmGatewayEnv("nemoclaw-snap-vm-gw-create-"); const r = runCli("alpha snapshot create --name baseline", env); - expect(r.code).toBe(0); + expect(r.code, r.out).toBe(0); expect(r.out).toContain("Snapshot v1 name=baseline created"); expect(r.out).not.toContain("Failed to query live sandbox state"); }); @@ -233,7 +233,7 @@ describe("snapshot VM-driver gateway guard", () => { expect(seed.out).toContain("Snapshot v1 name=baseline created"); const r = runCli("alpha snapshot restore baseline --to clone-1", env); - expect(r.code).toBe(0); + expect(r.code, r.out).toBe(0); expect(r.out).not.toContain("could not resolve"); expect(r.out).not.toContain("kubectl-must-not-run"); expect(r.out).toContain("openshell/sandbox-from:fast-path-test"); From e78042ee4e3c7eb4d1195e119a326733158e34bb Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 18:16:14 -0700 Subject: [PATCH 06/14] test(snapshot): consume restore fixture stdin --- test/snapshot-gateway-guard.test.ts | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index b88e4ae6f8e..ce0fd454214 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -174,7 +174,9 @@ function makeVmRestoreToEnv( ' "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") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *installed_plugin_index*) printf "{\\"version\\":1,\\"installRecords\\":{},\\"loadPaths\\":[]}" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; exit 0 ;;', + // Restore writes config bytes on stdin. Consume them before exiting so the + // fake CLI cannot race its caller into a Linux-only EPIPE. + ' "sandbox exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *installed_plugin_index*) printf "{\\"version\\":1,\\"installRecords\\":{},\\"loadPaths\\":[]}" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; cat >/dev/null; exit 0 ;;', ` "sandbox create") touch ${JSON.stringify(cloneReadyMarker)}; printf "created clone-1\\n"; exit 0 ;;`, "esac", 'if [ "$1" = "status" ]; then exit 0; fi', From 4b4ad5d4945fb77988bff2fe7cdd7221ee54edb3 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 18:31:27 -0700 Subject: [PATCH 07/14] test(snapshot): expose restore fixture diagnostics --- test/snapshot-gateway-guard.test.ts | 1 + 1 file changed, 1 insertion(+) diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index ce0fd454214..b63b0b92041 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -196,6 +196,7 @@ function makeVmRestoreToEnv( return { HOME: home, + NEMOCLAW_REBUILD_VERBOSE: "1", PATH: `${localBin}:${process.env.PATH ?? ""}`, }; } From 4848c20d7a4c05b8a905351d3e451d8be7c6bbe5 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Mon, 13 Jul 2026 18:38:01 -0700 Subject: [PATCH 08/14] test(snapshot): isolate OpenShell config root --- test/snapshot-gateway-guard.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index b63b0b92041..08a409056f8 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -196,8 +196,8 @@ function makeVmRestoreToEnv( return { HOME: home, - NEMOCLAW_REBUILD_VERBOSE: "1", PATH: `${localBin}:${process.env.PATH ?? ""}`, + XDG_CONFIG_HOME: path.join(home, ".config"), }; } From 49963f05af04ca05e211a1987f6543ccdaabe6fd Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 14:05:46 -0700 Subject: [PATCH 09/14] refactor(openshell): harden gRPC state restore Signed-off-by: Aaron Erickson --- scripts/checks/legacy-sandbox-transports.ts | 8 +- .../adapters/openshell/sandbox-upload.test.ts | 145 +++ src/lib/adapters/openshell/sandbox-upload.ts | 278 ++++++ src/lib/onboard.ts | 4 +- .../created-sandbox-finalization.test.ts | 110 ++- .../onboard/created-sandbox-finalization.ts | 2 + .../key-allowlist-merge/python-config.ts | 67 +- .../key-allowlist-merge/python-entrypoint.ts | 9 +- .../state/openclaw-managed-extensions.test.ts | 133 --- src/lib/state/openclaw-managed-extensions.ts | 70 -- src/lib/state/openclaw-plugin-restore.test.ts | 40 +- src/lib/state/openclaw-plugin-restore.ts | 10 +- .../sandbox-openclaw-plugin-restore.test.ts | 11 +- ...sandbox-recreated-openclaw-restore.test.ts | 207 ++-- src/lib/state/sandbox-restore-payload.test.ts | 471 +++++++++ src/lib/state/sandbox-restore-payload.ts | 918 ++++++++++++++++++ src/lib/state/sandbox-restore-upload.test.ts | 359 +++++++ src/lib/state/sandbox.ts | 421 ++++---- .../state-file-key-merge-file-safety.test.ts | 44 +- .../state-file-key-merge-test-fixture.ts | 56 +- src/lib/state/state-file-key-merge.ts | 27 - .../state-file-restore-custom-image.test.ts | 237 ++++- .../state/state-file-restore-python.test.ts | 197 ++++ src/lib/state/state-file-restore.ts | 578 +++++++++-- test/openclaw-config-snapshot.test.ts | 50 +- ...apshot-openclaw-managed-extensions.test.ts | 225 ++--- test/snapshot.test.ts | 111 ++- test/state-file-restore-command.test.ts | 46 - 28 files changed, 3786 insertions(+), 1048 deletions(-) create mode 100644 src/lib/adapters/openshell/sandbox-upload.test.ts create mode 100644 src/lib/adapters/openshell/sandbox-upload.ts create mode 100644 src/lib/state/sandbox-restore-payload.test.ts create mode 100644 src/lib/state/sandbox-restore-payload.ts create mode 100644 src/lib/state/sandbox-restore-upload.test.ts create mode 100644 src/lib/state/state-file-restore-python.test.ts delete mode 100644 test/state-file-restore-command.test.ts diff --git a/scripts/checks/legacy-sandbox-transports.ts b/scripts/checks/legacy-sandbox-transports.ts index eae81ab3217..6dab8f85032 100644 --- a/scripts/checks/legacy-sandbox-transports.ts +++ b/scripts/checks/legacy-sandbox-transports.ts @@ -55,14 +55,8 @@ const REVIEWED_SITE_TUPLES = [ ["src/lib/share-command.ts", "sshfs-command", 1], ["src/lib/shields/index.ts", "privileged-sandbox-exec", 4], ["src/lib/shields/mutable-config-repair.ts", "privileged-sandbox-exec", 2], - ["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/openclaw-plugin-restore.ts", "grpc-cli-read-only-fallback", 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", 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], ] as const satisfies readonly ReviewedSiteTuple[]; diff --git a/src/lib/adapters/openshell/sandbox-upload.test.ts b/src/lib/adapters/openshell/sandbox-upload.test.ts new file mode 100644 index 00000000000..143ad1e6c6c --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-upload.test.ts @@ -0,0 +1,145 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import assert from "node:assert/strict"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { describe, expect, it, vi } from "vitest"; + +import type { OpenShellSandboxControl } from "./sandbox-control.js"; +import { + cleanupSandboxPayloadAfterFailure, + createPrivateSandboxPayloadFile, + createPrivateSandboxPayloadFileFromPath, + createSandboxPayloadRemotePath, + SANDBOX_PAYLOAD_CLEANUP_MAX_OUTPUT_BYTES, + SANDBOX_PAYLOAD_CLEANUP_OK, + SANDBOX_PAYLOAD_CLEANUP_PYTHON, + SANDBOX_PAYLOAD_CLEANUP_TIMEOUT_MS, + SANDBOX_PAYLOAD_UPLOAD_MAX_OUTPUT_BYTES, + SANDBOX_PAYLOAD_UPLOAD_TIMEOUT_MS, + type SandboxPayloadUploadDependencies, + uploadSandboxPayloadFile, +} from "./sandbox-upload.js"; + +describe("OpenShell sandbox payload upload", () => { + it("uses the exact gateway, option terminator, timeout, and output cap", () => { + const capture = vi.fn>(() => ({ + status: 0, + output: "", + stdout: "", + stderr: "", + })); + + const result = uploadSandboxPayloadFile( + "nemoclaw-18080", + "-sandbox", + "/private/input", + "/tmp/nemoclaw-state-restore-fixed", + { capture }, + ); + + expect(result).toEqual({ + ok: true, + remotePath: "/tmp/nemoclaw-state-restore-fixed", + }); + expect(capture).toHaveBeenCalledWith( + [ + "sandbox", + "upload", + "-g", + "nemoclaw-18080", + "--", + "-sandbox", + "/private/input", + "/tmp/nemoclaw-state-restore-fixed", + ], + { + ignoreError: true, + includeStreams: true, + timeout: SANDBOX_PAYLOAD_UPLOAD_TIMEOUT_MS, + maxBuffer: SANDBOX_PAYLOAD_UPLOAD_MAX_OUTPUT_BYTES, + }, + ); + }); + + it("rejects an ambient endpoint override before invoking OpenShell", () => { + const capture = vi.fn>(); + const result = uploadSandboxPayloadFile( + "nemoclaw", + "alpha", + "/private/input", + "/tmp/nemoclaw-state-restore-fixed", + { capture, env: { OPENSHELL_GATEWAY_ENDPOINT: "https://wrong.example" } }, + ); + + expect(result).toMatchObject({ ok: false, error: expect.stringContaining("may bypass") }); + expect(capture).not.toHaveBeenCalled(); + }); + + it("stages private bytes and removes the host artifact idempotently", () => { + const staged = createPrivateSandboxPayloadFile(Buffer.from([0x00, 0xff, 0x41])); + expect(staged.ok).toBe(true); + assert(staged.ok); + + expect(fs.statSync(path.dirname(staged.payload.localPath)).mode & 0o777).toBe(0o700); + expect(fs.statSync(staged.payload.localPath).mode & 0o777).toBe(0o600); + expect(fs.readFileSync(staged.payload.localPath)).toEqual(Buffer.from([0x00, 0xff, 0x41])); + staged.payload.cleanup(); + staged.payload.cleanup(); + expect(fs.existsSync(staged.payload.localPath)).toBe(false); + }); + + it("removes private staging when the source file cannot be opened", () => { + const before = new Set( + fs.readdirSync(os.tmpdir()).filter((entry) => entry.startsWith("nemoclaw-state-upload-")), + ); + + const staged = createPrivateSandboxPayloadFileFromPath( + path.join(os.tmpdir(), `missing-${String(process.pid)}-${String(Date.now())}`), + 1024, + ); + + expect(staged.ok).toBe(false); + expect( + fs + .readdirSync(os.tmpdir()) + .filter((entry) => entry.startsWith("nemoclaw-state-upload-") && !before.has(entry)), + ).toEqual([]); + }); + + it("creates unguessable remote paths in the reviewed namespace", () => { + expect(createSandboxPayloadRemotePath(() => "fixed-id")).toBe( + "/tmp/nemoclaw-state-restore-fixed-id", + ); + }); + + it("builds one fixed bounded cleanup request and rejects arbitrary paths", async () => { + const exec = vi.fn(async () => ({ + status: 0, + stdout: `${SANDBOX_PAYLOAD_CLEANUP_OK}\n`, + stderr: "", + })); + const control = { exec }; + + expect(await cleanupSandboxPayloadAfterFailure(control, "alpha", "/tmp/unrelated")).toBe(false); + expect(exec).not.toHaveBeenCalled(); + expect( + await cleanupSandboxPayloadAfterFailure( + control, + "alpha", + "/tmp/nemoclaw-state-restore-fixed-id", + ), + ).toBe(true); + expect(exec).toHaveBeenCalledOnce(); + expect(exec).toHaveBeenCalledWith({ + sandboxName: "alpha", + command: ["python3", "-I", "-", "/tmp/nemoclaw-state-restore-fixed-id"], + stdin: SANDBOX_PAYLOAD_CLEANUP_PYTHON, + timeoutMs: SANDBOX_PAYLOAD_CLEANUP_TIMEOUT_MS, + maxOutputBytes: SANDBOX_PAYLOAD_CLEANUP_MAX_OUTPUT_BYTES, + }); + }); +}); diff --git a/src/lib/adapters/openshell/sandbox-upload.ts b/src/lib/adapters/openshell/sandbox-upload.ts new file mode 100644 index 00000000000..e343ee0d77a --- /dev/null +++ b/src/lib/adapters/openshell/sandbox-upload.ts @@ -0,0 +1,278 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { createHash, randomUUID } from "node:crypto"; +import { + chmodSync, + closeSync, + constants as fsConstants, + fstatSync, + fsyncSync, + mkdtempSync, + openSync, + readSync, + rmSync, + writeFileSync, + writeSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { + assertNoOpenShellGatewayEndpointOverride, + type OpenShellGatewayEndpointEnvironment, +} from "../../openshell-gateway-endpoint-guard.js"; +import { captureOpenshell } from "./runtime.js"; +import { + type OpenShellSandboxControl, + type SandboxExecRequest, + validateOpenShellExecRequest, +} from "./sandbox-control.js"; + +type CaptureOpenshell = typeof captureOpenshell; + +export const SANDBOX_PAYLOAD_UPLOAD_TIMEOUT_MS = 120_000; +export const SANDBOX_PAYLOAD_UPLOAD_MAX_OUTPUT_BYTES = 64 * 1024; +export const SANDBOX_PAYLOAD_CLEANUP_TIMEOUT_MS = 30_000; +export const SANDBOX_PAYLOAD_CLEANUP_MAX_OUTPUT_BYTES = 64 * 1024; +export const SANDBOX_PAYLOAD_CLEANUP_OK = "SANDBOX_PAYLOAD_CLEANUP_OK"; + +const SANDBOX_PAYLOAD_REMOTE_PATH_RE = + /^\/tmp\/nemoclaw-state-restore-[A-Za-z0-9][A-Za-z0-9-]{0,127}$/; + +export const SANDBOX_PAYLOAD_CLEANUP_PYTHON = String.raw`import os, posixpath, re, sys + +DIR_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + +def fail(message): + print(message, file=sys.stderr) + raise SystemExit(20) + +if len(sys.argv) != 2: + fail("cleanup requires one staged payload path") +remote_path = sys.argv[1] +if not isinstance(remote_path, str) or posixpath.normpath(remote_path) != remote_path or not re.fullmatch(r"/tmp/nemoclaw-state-restore-[A-Za-z0-9][A-Za-z0-9-]{0,127}", remote_path): + fail("invalid staged payload cleanup path") +parent_fd = os.open("/tmp", DIR_FLAGS) +try: + name = posixpath.basename(remote_path) + try: + os.unlink(name, dir_fd=parent_fd) + except FileNotFoundError: + pass +finally: + os.close(parent_fd) +print("SANDBOX_PAYLOAD_CLEANUP_OK") +`; + +export interface SandboxPayloadUploadDependencies { + capture?: CaptureOpenshell; + env?: OpenShellGatewayEndpointEnvironment; +} + +export type SandboxPayloadUploadResult = + | { ok: true; remotePath: string } + | { ok: false; error: string; remotePath: string }; + +export interface PrivateSandboxPayloadFile { + readonly localPath: string; + readonly sha256: string; + cleanup(): void; +} + +export type PrivateSandboxPayloadFileResult = + | { ok: true; payload: PrivateSandboxPayloadFile } + | { ok: false; error: string }; + +export function createSandboxPayloadRemotePath(randomId: () => string = randomUUID): string { + return `/tmp/nemoclaw-state-restore-${randomId()}`; +} + +export function createPrivateSandboxPayloadFile(payload: Buffer): PrivateSandboxPayloadFileResult { + let tempDir: string | undefined; + try { + tempDir = mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-upload-")); + chmodSync(tempDir, 0o700); + const localPath = path.join(tempDir, "payload"); + writeFileSync(localPath, payload, { flag: "wx", mode: 0o600 }); + const ownedTempDir = tempDir; + let cleaned = false; + return { + ok: true, + payload: { + localPath, + sha256: createHash("sha256").update(payload).digest("hex"), + cleanup: () => { + if (cleaned) return; + cleaned = true; + rmSync(ownedTempDir, { recursive: true, force: true }); + }, + }, + }; + } catch (cause) { + if (tempDir) rmSync(tempDir, { recursive: true, force: true }); + const detail = cause instanceof Error ? cause.message : String(cause); + return { ok: false, error: detail.substring(0, 200) }; + } +} + +function writeAllSync(fd: number, contents: Buffer): void { + let offset = 0; + while (offset < contents.length) { + const written = writeSync(fd, contents, offset, contents.length - offset); + if (written <= 0) throw new Error("could not write private sandbox payload"); + offset += written; + } +} + +/** Snapshot a host file into private bounded staging without allocating its full contents. */ +export function createPrivateSandboxPayloadFileFromPath( + sourcePath: string, + maxBytes: number, +): PrivateSandboxPayloadFileResult { + let tempDir: string | undefined; + let sourceFd: number | undefined; + let outputFd: number | undefined; + let complete = false; + try { + if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) { + return { ok: false, error: "invalid sandbox payload size limit" }; + } + tempDir = mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-upload-")); + chmodSync(tempDir, 0o700); + const localPath = path.join(tempDir, "payload"); + sourceFd = openSync(sourcePath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW); + const before = fstatSync(sourceFd); + if (!before.isFile() || before.nlink !== 1 || before.size > maxBytes) { + return { + ok: false, + error: `source is not a single regular file within ${String(maxBytes)} bytes`, + }; + } + outputFd = openSync( + localPath, + fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL, + 0o600, + ); + const chunk = Buffer.alloc(64 * 1024); + const digest = createHash("sha256"); + let total = 0; + for (;;) { + const count = readSync(sourceFd, chunk, 0, chunk.length, null); + if (count === 0) break; + total += count; + if (total > maxBytes) { + return { ok: false, error: `source exceeds ${String(maxBytes)} bytes while staging` }; + } + digest.update(chunk.subarray(0, count)); + writeAllSync(outputFd, chunk.subarray(0, count)); + } + const after = fstatSync(sourceFd); + if ( + total !== before.size || + after.size !== before.size || + after.mtimeMs !== before.mtimeMs || + after.ino !== before.ino || + after.dev !== before.dev + ) { + return { ok: false, error: "source changed while staging sandbox payload" }; + } + fsyncSync(outputFd); + closeSync(outputFd); + outputFd = undefined; + closeSync(sourceFd); + sourceFd = undefined; + const ownedTempDir = tempDir; + let cleaned = false; + complete = true; + return { + ok: true, + payload: { + localPath, + sha256: digest.digest("hex"), + cleanup: () => { + if (cleaned) return; + cleaned = true; + rmSync(ownedTempDir, { recursive: true, force: true }); + }, + }, + }; + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return { ok: false, error: detail.substring(0, 200) }; + } finally { + if (outputFd !== undefined) closeSync(outputFd); + if (sourceFd !== undefined) closeSync(sourceFd); + if (tempDir && !complete) { + rmSync(tempDir, { recursive: true, force: true }); + } + } +} + +/** + * Upload one already-private host file through OpenShell's supported command. + * + * Restore payloads may exceed ExecSandbox's unary request ceiling. The caller + * owns local staging and cleanup; this boundary owns exact gateway routing, + * endpoint-override rejection, option termination, and bounded diagnostics. + */ +export function uploadSandboxPayloadFile( + gatewayName: string, + sandboxName: string, + localPath: string, + remotePath: string, + dependencies: SandboxPayloadUploadDependencies = {}, +): SandboxPayloadUploadResult { + try { + assertNoOpenShellGatewayEndpointOverride(dependencies.env ?? process.env); + const result = (dependencies.capture ?? captureOpenshell)( + ["sandbox", "upload", "-g", gatewayName, "--", sandboxName, localPath, remotePath], + { + ignoreError: true, + includeStreams: true, + timeout: SANDBOX_PAYLOAD_UPLOAD_TIMEOUT_MS, + maxBuffer: SANDBOX_PAYLOAD_UPLOAD_MAX_OUTPUT_BYTES, + }, + ); + if (result.status === 0 && !result.error && !result.signal) { + return { ok: true, remotePath }; + } + const detail = + result.stderr?.trim() || + result.output.trim() || + result.error?.message || + (result.signal ? `signal ${result.signal}` : `exit ${String(result.status)}`); + return { ok: false, error: detail.substring(0, 200), remotePath }; + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return { ok: false, error: detail.substring(0, 200), remotePath }; + } +} + +/** Best-effort, non-replaying cleanup for a possibly uploaded private payload. */ +export async function cleanupSandboxPayloadAfterFailure( + sandboxControl: OpenShellSandboxControl, + sandboxName: string, + remotePath: string, +): Promise { + if (!SANDBOX_PAYLOAD_REMOTE_PATH_RE.test(remotePath)) return false; + const request: SandboxExecRequest = { + sandboxName, + command: ["python3", "-I", "-", remotePath], + stdin: SANDBOX_PAYLOAD_CLEANUP_PYTHON, + timeoutMs: SANDBOX_PAYLOAD_CLEANUP_TIMEOUT_MS, + maxOutputBytes: SANDBOX_PAYLOAD_CLEANUP_MAX_OUTPUT_BYTES, + }; + if (validateOpenShellExecRequest(request)) return false; + try { + const result = await sandboxControl.exec(request); + return ( + result.status === 0 && + !result.error && + !result.signal && + result.stdout.trim() === SANDBOX_PAYLOAD_CLEANUP_OK + ); + } catch { + return false; + } +} diff --git a/src/lib/onboard.ts b/src/lib/onboard.ts index bc6ba7e13bf..b9d02d6831a 100644 --- a/src/lib/onboard.ts +++ b/src/lib/onboard.ts @@ -2876,7 +2876,6 @@ async function createSandboxWithBaseImageResolution( finalHermesDashboardState = hermesDashboardForwarding.resolveStateForPort(actualDashboardPort); hermesDashboardForwarding.ensureForState(finalHermesDashboardState, sandboxName, true); } - // openshell tags images with seconds; buildId is ms. Parse actual tag from output. Fixes #2672. const resolvedImageTag = registryImageRef ?? @@ -2890,6 +2889,7 @@ async function createSandboxWithBaseImageResolution( restoreBackupPath, preUpgradeBackup: pendingStateRestoreBackupPath !== null, targetAgentType: agent?.name ?? "openclaw", + gatewayName: GATEWAY_NAME, customImage: Boolean(fromDockerfile), discoverOpenClawImagePluginInstalls: customOpenClawImage, validateManagedDcode: isManagedDcodeAgent, @@ -2899,7 +2899,7 @@ async function createSandboxWithBaseImageResolution( }, // biome-ignore format: keep src/lib/onboard.ts within the growth guardrail. { - discoverFreshOpenClawImagePluginInstalls: (name) => openClawPluginRestore.discoverFreshOpenClawImagePluginInstalls(name, GATEWAY_NAME, agent?.configPaths.dir), restoreRecreatedSandboxState: (name, backupPath, options) => sandboxState.restoreRecreatedSandboxState(name, backupPath, { ...options, gatewayName: GATEWAY_NAME }), + discoverFreshOpenClawImagePluginInstalls: (name) => openClawPluginRestore.discoverFreshOpenClawImagePluginInstalls(name, GATEWAY_NAME, agent?.configPaths.dir), restoreRecreatedSandboxState: (name, backupPath, options) => sandboxState.restoreRecreatedSandboxState(name, backupPath, options), getDcodeSelectionDrift: (name, selectedProvider, selectedModel, selectedApi) => getDcodeSelectionDrift(name, selectedProvider, selectedModel, selectedApi, { runCaptureOpenshell, diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index 9792e1c3229..65da553286b 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -8,7 +8,17 @@ import path from "node:path"; import { afterEach, describe, expect, it, vi } from "vitest"; -vi.mock("../adapters/openshell/sandbox-control-routing", async () => { +const restoreTransport = vi.hoisted(() => ({ + execCalls: 0, + hostPython: "python3", + liveDir: "", + pythonShim: "", + stageDir: "", + stagedRemotePaths: new Map(), + uploadCalls: 0, +})); + +vi.mock("../adapters/openshell/sandbox-control-routing.js", async () => { const { spawnSync } = await import("node:child_process"); const exec = async (request: { command: readonly string[]; @@ -17,17 +27,30 @@ vi.mock("../adapters/openshell/sandbox-control-routing", async () => { timeoutMs?: number; stdoutEncoding?: "utf8" | "buffer"; }) => { - const binary = request.stdoutEncoding === "buffer"; - const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { - input: request.stdin, - maxBuffer: request.maxOutputBytes, - timeout: request.timeoutMs, - encoding: binary ? undefined : "utf8", - }); + restoreTransport.execCalls += 1; + const command = [...request.command]; + const keyMerge = command[0] === "/opt/venv/bin/python3"; + const args = keyMerge ? command.slice(3) : command.slice(1); + if (keyMerge) { + args[0] = restoreTransport.liveDir; + args[3] = restoreTransport.stagedRemotePaths.get(args[3]) ?? args[3]; + } else { + args[2] = restoreTransport.stagedRemotePaths.get(args[2]) ?? args[2]; + args[3] = restoreTransport.liveDir; + } + const result = spawnSync( + keyMerge ? restoreTransport.pythonShim : restoreTransport.hostPython, + keyMerge ? [String(request.stdin ?? ""), ...args] : args, + { + input: keyMerge ? undefined : request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: "utf8", + }, + ); return { status: result.status, - stdout: binary ? "" : String(result.stdout ?? ""), - ...(binary ? { stdoutBytes: Buffer.from(result.stdout ?? "") } : {}), + stdout: String(result.stdout ?? ""), stderr: String(result.stderr ?? ""), ...(result.error ? { error: result.error } : {}), ...(result.signal ? { signal: result.signal } : {}), @@ -46,6 +69,27 @@ vi.mock("../adapters/openshell/sandbox-control-routing", async () => { }; }); +vi.mock("../adapters/openshell/sandbox-upload.js", async (importOriginal) => { + const fs = await import("node:fs"); + const path = await import("node:path"); + return { + ...(await importOriginal()), + uploadSandboxPayloadFile: ( + _gateway: string, + _sandbox: string, + localPath: string, + remotePath: string, + ) => { + restoreTransport.uploadCalls += 1; + const stagedPath = path.join(restoreTransport.stageDir, path.basename(remotePath)); + fs.copyFileSync(localPath, stagedPath); + fs.chmodSync(stagedPath, 0o600); + restoreTransport.stagedRemotePaths.set(remotePath, stagedPath); + return { ok: true, remotePath }; + }, + }; +}); + import * as sandboxState from "../state/sandbox"; import { finalizeCreatedSandbox } from "./created-sandbox-finalization"; import { getDcodeSelectionDrift } from "./dcode-selection-drift"; @@ -54,6 +98,9 @@ const fixtures: string[] = []; afterEach(() => { delete process.env.NEMOCLAW_OPENSHELL_BIN; + restoreTransport.execCalls = 0; + restoreTransport.stagedRemotePaths.clear(); + restoreTransport.uploadCalls = 0; for (const fixture of fixtures.splice(0)) fs.rmSync(fixture, { recursive: true, force: true }); vi.restoreAllMocks(); }); @@ -67,7 +114,7 @@ function makeRestoreFixture(): { currentPath: string; oldPath: string; } { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-finalize-")); + const root = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-dcode-finalize-"))); fixtures.push(root); const bin = path.join(root, "bin"); const backupPath = path.join(root, "backup"); @@ -181,27 +228,10 @@ sys.argv = [sys.argv[0], *sys.argv[script_index + 1:]] exec(script, {"__name__": "__main__"}) `, ); - const openshell = path.join(bin, "openshell"); - executable( - openshell, - '#!/usr/bin/env bash\nprintf "Host openshell-dcode\\n HostName 127.0.0.1\\n User sandbox\\n"\n', - ); - executable( - path.join(bin, "ssh"), - `#!/usr/bin/env node -const fs = require("node:fs"); -const { spawnSync } = require("node:child_process"); -const command = process.argv.at(-1) - .replaceAll("/sandbox/.deepagents", ${JSON.stringify(liveDir)}) - .replace("/opt/venv/bin/python3", ${JSON.stringify(python)}); -const result = spawnSync("bash", ["-c", command], { input: fs.readFileSync(0), stdio: ["pipe", "pipe", "pipe"] }); -if (result.stdout) fs.writeSync(1, result.stdout); -if (result.stderr) fs.writeSync(2, result.stderr); -process.exit(result.status ?? 1); -`, - ); - process.env.NEMOCLAW_OPENSHELL_BIN = openshell; - process.env.PATH = `${bin}${path.delimiter}${oldPath}`; + restoreTransport.hostPython = hostPython; + restoreTransport.liveDir = liveDir; + restoreTransport.pythonShim = python; + restoreTransport.stageDir = root; return { backupPath, currentPath, oldPath }; } @@ -231,6 +261,7 @@ describe("created DCode sandbox finalization", () => { restoreBackupPath: fixture.backupPath, preUpgradeBackup: false, targetAgentType: "langchain-deepagents-code", + gatewayName: "nemoclaw", validateManagedDcode: true, provider: "nvidia-prod", model: "new-model", @@ -267,6 +298,8 @@ describe("created DCode sandbox finalization", () => { ); expect(order).toEqual(["restore", "validate", "register"]); + expect(restoreTransport.uploadCalls).toBe(1); + expect(restoreTransport.execCalls).toBe(1); expect(registeredConfigs[0]).toContain('default = "openai:new-model"'); expect(registeredConfigs[0]).not.toContain("old-model"); expect(registeredConfigs[0]).not.toContain("[agents]"); @@ -287,6 +320,7 @@ describe("created DCode sandbox finalization", () => { restoreBackupPath: null, preUpgradeBackup: false, targetAgentType: "langchain-deepagents-code", + gatewayName: "nemoclaw", validateManagedDcode: true, provider: "nvidia-prod", model: "new-model", @@ -330,6 +364,7 @@ describe("created DCode sandbox finalization", () => { restoreBackupPath: fixture.backupPath, preUpgradeBackup: false, targetAgentType: "langchain-deepagents-code", + gatewayName: "nemoclaw", validateManagedDcode: true, provider: "nvidia-prod", model: "new-model", @@ -361,6 +396,8 @@ describe("created DCode sandbox finalization", () => { ` Warning: partial restore. Manual recovery: ${fixture.backupPath}`, ); expect(registeredConfigs).toHaveLength(1); + expect(restoreTransport.uploadCalls).toBe(1); + expect(restoreTransport.execCalls).toBe(1); expect(registeredConfigs[0]).toContain('default = "openai:new-model"'); expect(registeredConfigs[0]).not.toContain("old-model"); expect(registeredConfigs[0]).toContain("[ui]\nshow_scrollbar = true"); @@ -380,6 +417,7 @@ describe("created DCode sandbox finalization", () => { restoreBackupPath: fixture.backupPath, preUpgradeBackup: false, targetAgentType: "langchain-deepagents-code", + gatewayName: "nemoclaw", customImage: true, validateManagedDcode: false, provider: "custom-provider", @@ -403,6 +441,8 @@ describe("created DCode sandbox finalization", () => { ); expect(registeredConfigs).toHaveLength(1); + expect(restoreTransport.uploadCalls).toBe(1); + expect(restoreTransport.execCalls).toBe(1); expect(registeredConfigs[0]).toContain('default = "openai:old-model"'); expect(registeredConfigs[0]).toContain("[agents]"); expect(registeredConfigs[0]).toContain('theme = "dark"'); @@ -432,6 +472,7 @@ describe("created OpenClaw sandbox finalization", () => { restoreBackupPath: null, preUpgradeBackup: false, targetAgentType: "openclaw", + gatewayName: "nemoclaw", validateManagedDcode: false, provider: "compatible-endpoint", model: "demo", @@ -465,6 +506,7 @@ describe("created OpenClaw sandbox finalization", () => { restoreBackupPath: null, preUpgradeBackup: false, targetAgentType: "openclaw", + gatewayName: "nemoclaw", discoverOpenClawImagePluginInstalls: true, validateManagedDcode: false, provider: "compatible-endpoint", @@ -512,6 +554,7 @@ describe("created OpenClaw sandbox finalization", () => { restoreBackupPath: "/tmp/openclaw-backup", preUpgradeBackup: false, targetAgentType: "openclaw", + gatewayName: "nemoclaw", discoverOpenClawImagePluginInstalls: true, validateManagedDcode: false, provider: "compatible-endpoint", @@ -537,6 +580,7 @@ describe("created OpenClaw sandbox finalization", () => { expect(order).toEqual(["discover", "restore", "register"]); expect(restoreRecreatedSandboxState).toHaveBeenCalledWith("openclaw", "/tmp/openclaw-backup", { targetAgentType: "openclaw", + gatewayName: "nemoclaw", freshOpenClawImagePluginInstalls: pluginInstalls, }); expect(register).toHaveBeenCalledWith(pluginInstalls); @@ -554,6 +598,7 @@ describe("created OpenClaw sandbox finalization", () => { restoreBackupPath: "/tmp/openclaw-backup", preUpgradeBackup: false, targetAgentType: "openclaw", + gatewayName: "nemoclaw", discoverOpenClawImagePluginInstalls: true, validateManagedDcode: false, provider: "compatible-endpoint", @@ -601,6 +646,7 @@ describe("created OpenClaw sandbox finalization", () => { restoreBackupPath: "/tmp/openclaw-backup", preUpgradeBackup: false, targetAgentType: "openclaw", + gatewayName: "nemoclaw", discoverOpenClawImagePluginInstalls: true, validateManagedDcode: false, provider: "compatible-endpoint", diff --git a/src/lib/onboard/created-sandbox-finalization.ts b/src/lib/onboard/created-sandbox-finalization.ts index 04a46f12e58..9b4b4b4bbca 100644 --- a/src/lib/onboard/created-sandbox-finalization.ts +++ b/src/lib/onboard/created-sandbox-finalization.ts @@ -17,6 +17,7 @@ export type CreatedSandboxFinalizationOptions = { restoreBackupPath: string | null; preUpgradeBackup: boolean; targetAgentType: string; + gatewayName: string; customImage?: boolean; discoverOpenClawImagePluginInstalls?: boolean; validateManagedDcode: boolean; @@ -79,6 +80,7 @@ export async function finalizeCreatedSandbox( options.restoreBackupPath, { targetAgentType: options.targetAgentType, + gatewayName: options.gatewayName, ...(options.customImage ? { allowCustomImageWholeStateFileRestore: true } : {}), ...(freshOpenClawImagePluginInstalls !== undefined ? { freshOpenClawImagePluginInstalls } diff --git a/src/lib/state/key-allowlist-merge/python-config.ts b/src/lib/state/key-allowlist-merge/python-config.ts index edf38a54a7a..15c66d0b07a 100644 --- a/src/lib/state/key-allowlist-merge/python-config.ts +++ b/src/lib/state/key-allowlist-merge/python-config.ts @@ -4,6 +4,7 @@ /** Python helpers that parse TOML and open the fresh config without following links. */ export const KEY_ALLOWLIST_CONFIG_PYTHON = String.raw` import copy +import hashlib import json import math import os @@ -36,9 +37,69 @@ def parse_config_payload(payload, label): return text, parsed -def read_stdin_config(label): - payload = sys.stdin.buffer.read(MAX_CONFIG_BYTES + 1) - return parse_config_payload(payload, label) +def read_staged_config(pathname, expected_digest, label): + if ( + not isinstance(pathname, str) + or not os.path.isabs(pathname) + or not os.path.basename(pathname).startswith("nemoclaw-state-restore-") + or os.path.normpath(pathname) != pathname + ): + fail("staged config path is invalid") + if len(expected_digest) != 64 or any(char not in "0123456789abcdef" for char in expected_digest): + fail("staged config digest is invalid") + flags = os.O_RDONLY | os.O_DIRECTORY | getattr(os, "O_NOFOLLOW", 0) + parent_fd = os.open("/", flags) + parts = pathname.split("/")[1:] + try: + for component in parts[:-1]: + next_fd = os.open(component, flags, dir_fd=parent_fd) + os.close(parent_fd) + parent_fd = next_fd + before = os.stat(parts[-1], dir_fd=parent_fd, follow_symlinks=False) + payload_fd = os.open( + parts[-1], os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0), dir_fd=parent_fd + ) + try: + metadata = os.fstat(payload_fd) + if ( + not stat.S_ISREG(metadata.st_mode) + or metadata.st_nlink != 1 + or metadata.st_size > MAX_CONFIG_BYTES + or metadata.st_uid != os.geteuid() + or metadata.st_gid != os.getegid() + or metadata.st_mode & 0o022 + or (metadata.st_dev, metadata.st_ino) != (before.st_dev, before.st_ino) + ): + fail("staged config is not a single bounded regular file") + os.unlink(parts[-1], dir_fd=parent_fd) + baseline = os.fstat(payload_fd) + chunks = [] + total = 0 + digest = hashlib.sha256() + while True: + chunk = os.read(payload_fd, 65536) + if not chunk: + break + total += len(chunk) + if total > MAX_CONFIG_BYTES: + fail("staged config exceeds the restore size limit") + digest.update(chunk) + chunks.append(chunk) + after = os.fstat(payload_fd) + if ( + total != baseline.st_size + or after.st_size != baseline.st_size + or after.st_mtime_ns != baseline.st_mtime_ns + or after.st_ctime_ns != baseline.st_ctime_ns + ): + fail("staged config changed while snapshotting") + if digest.hexdigest() != expected_digest: + fail("staged config digest mismatch") + finally: + os.close(payload_fd) + finally: + os.close(parent_fd) + return parse_config_payload(b"".join(chunks), label) def open_config_parent(base_dir, relative_path): diff --git a/src/lib/state/key-allowlist-merge/python-entrypoint.ts b/src/lib/state/key-allowlist-merge/python-entrypoint.ts index bdd343d6e28..0193a0c0a6f 100644 --- a/src/lib/state/key-allowlist-merge/python-entrypoint.ts +++ b/src/lib/state/key-allowlist-merge/python-entrypoint.ts @@ -4,11 +4,11 @@ /** Python entrypoint kept separate from parsing, ownership, and replacement helpers. */ export const KEY_ALLOWLIST_ENTRYPOINT_PYTHON = String.raw` def main(): - if len(sys.argv) != 4: - fail("expected a config base, relative path, and ownership spec") - base_dir, relative_path, spec_raw = sys.argv[1:] + if len(sys.argv) != 6: + fail("expected a config base, relative path, ownership spec, staged path, and digest") + base_dir, relative_path, spec_raw = sys.argv[1:4] spec = load_spec(spec_raw) - _backup_text, backup = read_stdin_config("backed-up") + _backup_text, backup = read_staged_config(sys.argv[4], sys.argv[5], "backed-up") parent_fd, current_name = open_config_parent(base_dir, relative_path) try: current_text, current, current_metadata = read_regular_file_at( @@ -24,4 +24,5 @@ def main(): main() +print("KEY_ALLOWLIST_OK") `.trim(); diff --git a/src/lib/state/openclaw-managed-extensions.test.ts b/src/lib/state/openclaw-managed-extensions.test.ts index c6ce0a7a5fb..6c347611426 100644 --- a/src/lib/state/openclaw-managed-extensions.test.ts +++ b/src/lib/state/openclaw-managed-extensions.test.ts @@ -1,16 +1,9 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { execFileSync } from "node:child_process"; -import fs from "node:fs"; -import os from "node:os"; -import path from "node:path"; - import { describe, expect, it } from "vitest"; import { - buildRestoreCleanupCommand, - buildRestoreTarArgs, isAllowedStateSymlink, OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS, shouldPreserveOpenClawManagedExtensions, @@ -61,43 +54,6 @@ describe("OpenClaw managed extension policy", () => { ]), ).toBe(false); }); - - it("excludes only image-managed extensions from the restore archive", () => { - const args = buildRestoreTarArgs( - "/tmp/rebuild backup", - ["workspace", "extensions"], - OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS, - ); - - expect(args.slice(0, 4)).toEqual(["-cf", "-", "-C", "/tmp/rebuild backup"]); - expect(args.flatMap((arg, index) => (arg === "--exclude" ? [args[index + 1]] : []))).toEqual( - EXPECTED_MANAGED_EXTENSIONS.map((name) => `extensions/${name}`), - ); - expect(args.slice(-3)).toEqual(["--", "workspace", "extensions"]); - expect(args).not.toContain("extensions/telegram"); - }); - - it("also excludes dynamically discovered fresh plugin directories", () => { - const args = buildRestoreTarArgs( - "/tmp/backup", - ["extensions"], - [...OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS, "weather"], - ); - - expect(args).toContain("extensions/weather"); - }); - - it("leaves ordinary restore archives unfiltered", () => { - expect(buildRestoreTarArgs("/tmp/backup", ["workspace", "extensions"], [])).toEqual([ - "-cf", - "-", - "-C", - "/tmp/backup", - "--", - "workspace", - "extensions", - ]); - }); }); describe("OpenClaw managed extension symlink policy", () => { @@ -169,92 +125,3 @@ describe("OpenClaw managed extension symlink policy", () => { expect(isAllowedStateSymlink(source, target)).toBe(false); }); }); - -describe("OpenClaw managed extension cleanup", () => { - it("removes ordinary state while preserving and validating managed extension directories", () => { - const command = buildRestoreCleanupCommand( - "/sandbox/.openclaw", - ["workspace", "extensions"], - OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS, - new Set(), - ); - - expect(command).toContain("rm -rf -- '/sandbox/.openclaw/workspace'"); - expect(command).not.toContain("rm -rf -- '/sandbox/.openclaw/extensions'"); - expect(command).toContain("mkdir -p -- '/sandbox/.openclaw/extensions'"); - for (const extensionName of EXPECTED_MANAGED_EXTENSIONS) { - expect(command).toContain(`p='/sandbox/.openclaw/extensions/${extensionName}'`); - expect(command).toContain(`! -name '${extensionName}'`); - } - expect(command).toContain('[ -e "$p" ] || [ -L "$p" ]'); - expect(command).toContain('[ ! -d "$p" ] || [ -L "$p" ]'); - expect(command).toContain("-exec rm -rf -- {} +"); - }); - - it("executes cleanup without deleting managed directories and rejects dangling symlinks", () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-managed-extensions-")); - const extensions = path.join(root, "extensions"); - const managed = path.join(extensions, "nemoclaw"); - const dangling = path.join(extensions, "brave"); - const userExtension = path.join(extensions, "user-extension"); - fs.mkdirSync(managed, { recursive: true }); - fs.mkdirSync(userExtension); - fs.symlinkSync(path.join(root, "missing-target"), dangling); - const command = buildRestoreCleanupCommand( - root, - ["extensions"], - OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS, - new Set(), - ); - - expect(() => execFileSync("bash", ["-c", command], { stdio: "pipe" })).toThrow(); - expect(fs.lstatSync(dangling).isSymbolicLink()).toBe(true); - fs.unlinkSync(dangling); - execFileSync("bash", ["-c", command], { stdio: "pipe" }); - - expect(fs.statSync(managed).isDirectory()).toBe(true); - expect(fs.existsSync(userExtension)).toBe(false); - fs.rmSync(root, { recursive: true, force: true }); - }); - - it("requires dynamically discovered fresh plugin directories to remain real directories", () => { - const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-required-extension-")); - try { - const extensions = path.join(root, "extensions"); - const weather = path.join(extensions, "weather"); - const userExtension = path.join(extensions, "user-extension"); - fs.mkdirSync(weather, { recursive: true }); - fs.mkdirSync(userExtension); - const command = buildRestoreCleanupCommand( - root, - ["extensions"], - [...OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS, "weather"], - new Set(["weather"]), - ); - - execFileSync("bash", ["-c", command], { stdio: "pipe" }); - expect(fs.statSync(weather).isDirectory()).toBe(true); - expect(fs.existsSync(userExtension)).toBe(false); - - fs.rmSync(weather, { recursive: true, force: true }); - expect(() => execFileSync("bash", ["-c", command], { stdio: "pipe" })).toThrow(); - - const target = path.join(root, "weather-target"); - fs.mkdirSync(target); - fs.symlinkSync(target, weather); - expect(() => execFileSync("bash", ["-c", command], { stdio: "pipe" })).toThrow(); - } finally { - fs.rmSync(root, { recursive: true, force: true }); - } - }); - - it("removes complete state directories when managed preservation is disabled", () => { - expect( - buildRestoreCleanupCommand("/sandbox/.openclaw", ["workspace", "extensions"], [], new Set()), - ).toBe("rm -rf -- '/sandbox/.openclaw/workspace' && rm -rf -- '/sandbox/.openclaw/extensions'"); - }); - - it("returns a no-op when no restore directories require cleanup", () => { - expect(buildRestoreCleanupCommand("/sandbox/.openclaw", [], [], new Set())).toBe(":"); - }); -}); diff --git a/src/lib/state/openclaw-managed-extensions.ts b/src/lib/state/openclaw-managed-extensions.ts index 2a07e2c75d5..9ad1775760f 100644 --- a/src/lib/state/openclaw-managed-extensions.ts +++ b/src/lib/state/openclaw-managed-extensions.ts @@ -3,7 +3,6 @@ import path from "node:path"; -import { shellQuote } from "../core/shell-quote.js"; import { listOpenClawPluginExtensionIds } from "../messaging/channels/metadata.js"; // Exact symlinks baked into OpenClaw messaging images at build time. Source @@ -86,72 +85,3 @@ export function shouldPreserveOpenClawManagedExtensions( (manifest.agentType === "openclaw" || dir.replace(/\/+$/, "") === "/sandbox/.openclaw") ); } - -export function buildRestoreTarArgs( - backupPath: string, - localDirs: readonly string[], - managedExtensionDirs: readonly string[], -): string[] { - const args = ["-cf", "-", "-C", backupPath]; - for (const extensionName of managedExtensionDirs) { - args.push("--exclude", `extensions/${extensionName}`); - } - args.push("--", ...localDirs); - return args; -} - -function buildOpenClawExtensionsCleanupCommand( - dir: string, - managedExtensionDirs: readonly string[], - requiredExtensionDirs: ReadonlySet, -): string { - const extensionsDir = `${dir}/extensions`; - const quotedExtensionsDir = shellQuote(extensionsDir); - const validationCommands = managedExtensionDirs - .map((extensionName) => { - const managedPath = `${extensionsDir}/${extensionName}`; - if (requiredExtensionDirs.has(extensionName)) { - return ( - `p=${shellQuote(managedPath)}; ` + - 'if [ ! -d "$p" ] || [ -L "$p" ]; then ' + - 'echo "refusing missing or unsafe image-managed extension: $p" >&2; exit 20; fi' - ); - } - return ( - `p=${shellQuote(managedPath)}; ` + - 'if { [ -e "$p" ] || [ -L "$p" ]; } && { [ ! -d "$p" ] || [ -L "$p" ]; }; then ' + - 'echo "refusing to preserve unsafe managed extension: $p" >&2; exit 20; fi' - ); - }) - .join("; "); - const validateManagedPaths = `{ ${validationCommands}; }`; - const preservedNames = managedExtensionDirs - .map((extensionName) => `! -name ${shellQuote(extensionName)}`) - .join(" "); - - return [ - `mkdir -p -- ${quotedExtensionsDir}`, - validateManagedPaths, - `find ${quotedExtensionsDir} -mindepth 1 -maxdepth 1 ${preservedNames} -exec rm -rf -- {} +`, - ].join(" && "); -} - -export function buildRestoreCleanupCommand( - dir: string, - localDirs: readonly string[], - managedExtensionDirs: readonly string[], - requiredExtensionDirs: ReadonlySet, -): string { - const preserveManagedExtensions = managedExtensionDirs.length > 0; - const commands: string[] = []; - for (const dirName of localDirs) { - if (preserveManagedExtensions && dirName === "extensions") continue; - commands.push(`rm -rf -- ${shellQuote(`${dir}/${dirName}`)}`); - } - if (preserveManagedExtensions) { - commands.push( - buildOpenClawExtensionsCleanupCommand(dir, managedExtensionDirs, requiredExtensionDirs), - ); - } - return commands.length > 0 ? commands.join(" && ") : ":"; -} diff --git a/src/lib/state/openclaw-plugin-restore.test.ts b/src/lib/state/openclaw-plugin-restore.test.ts index 6f0c6ef4581..d283033440c 100644 --- a/src/lib/state/openclaw-plugin-restore.test.ts +++ b/src/lib/state/openclaw-plugin-restore.test.ts @@ -12,6 +12,7 @@ import { OPENCLAW_IMAGE_MANAGED_EXTENSION_DIRS } from "./openclaw-managed-extens import { buildFreshOpenClawPluginIndexSqliteReadCommand, hasCompleteOpenClawImagePluginProvenance, + OPENCLAW_PLUGIN_INDEX_SQLITE_PY, parseFreshOpenClawPluginExtensionDirs, parseOpenClawImagePluginInstalls, planOpenClawPluginRestore, @@ -49,6 +50,13 @@ function createPluginIndexDatabase(dbPath: string, records: unknown): void { execFileSync("python3", ["-c", CREATE_PLUGIN_INDEX_SQLITE_PY, dbPath, JSON.stringify(records)]); } +function runPluginIndexRead(root: string) { + return spawnSync("bash", ["-c", buildFreshOpenClawPluginIndexSqliteReadCommand(root)], { + input: OPENCLAW_PLUGIN_INDEX_SQLITE_PY, + encoding: "utf8", + }); +} + describe("buildFreshOpenClawPluginIndexSqliteReadCommand", () => { it("reads canonical install records from the OpenClaw SQLite index", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-plugin-index-")); @@ -58,12 +66,13 @@ describe("buildFreshOpenClawPluginIndexSqliteReadCommand", () => { createPluginIndexDatabase(dbPath, records); writeOpenClawConfig(root); - const stdout = execFileSync( - "bash", - ["-c", buildFreshOpenClawPluginIndexSqliteReadCommand(root)], - { encoding: "utf8" }, - ); - expect(JSON.parse(stdout)).toEqual({ version: 1, installRecords: records, loadPaths: [] }); + const result = runPluginIndexRead(root); + expect(result.status, result.stderr).toBe(0); + expect(JSON.parse(result.stdout)).toEqual({ + version: 1, + installRecords: records, + loadPaths: [], + }); } finally { fs.rmSync(root, { recursive: true, force: true }); } @@ -74,9 +83,7 @@ describe("buildFreshOpenClawPluginIndexSqliteReadCommand", () => { try { createPluginIndexDatabase(path.join(root, "state", "openclaw.sqlite"), null); writeOpenClawConfig(root); - expect(() => - execFileSync("bash", ["-c", buildFreshOpenClawPluginIndexSqliteReadCommand(root)]), - ).toThrow(); + expect(runPluginIndexRead(root).status).not.toBe(0); } finally { fs.rmSync(root, { recursive: true, force: true }); } @@ -85,10 +92,7 @@ describe("buildFreshOpenClawPluginIndexSqliteReadCommand", () => { it("uses exit status 2 only when the canonical SQLite database is absent", () => { const root = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-plugin-index-")); try { - const result = spawnSync("bash", [ - "-c", - buildFreshOpenClawPluginIndexSqliteReadCommand(root), - ]); + const result = runPluginIndexRead(root); expect(result.status).toBe(2); } finally { fs.rmSync(root, { recursive: true, force: true }); @@ -101,10 +105,7 @@ describe("buildFreshOpenClawPluginIndexSqliteReadCommand", () => { const dbPath = path.join(root, "state", "openclaw.sqlite"); fs.mkdirSync(path.dirname(dbPath), { recursive: true }); fs.symlinkSync(path.join(root, "missing.sqlite"), dbPath); - const result = spawnSync("bash", [ - "-c", - buildFreshOpenClawPluginIndexSqliteReadCommand(root), - ]); + const result = runPluginIndexRead(root); expect(result.status).toBe(10); } finally { fs.rmSync(root, { recursive: true, force: true }); @@ -116,10 +117,7 @@ describe("buildFreshOpenClawPluginIndexSqliteReadCommand", () => { try { createPluginIndexDatabase(path.join(root, "state", "openclaw.sqlite"), {}); fs.symlinkSync(path.join(root, "missing-openclaw.json"), path.join(root, "openclaw.json")); - const result = spawnSync("bash", [ - "-c", - buildFreshOpenClawPluginIndexSqliteReadCommand(root), - ]); + const result = runPluginIndexRead(root); expect(result.status).toBe(10); } finally { fs.rmSync(root, { recursive: true, force: true }); diff --git a/src/lib/state/openclaw-plugin-restore.ts b/src/lib/state/openclaw-plugin-restore.ts index 51b7c84e16a..f9fd0cfccbd 100644 --- a/src/lib/state/openclaw-plugin-restore.ts +++ b/src/lib/state/openclaw-plugin-restore.ts @@ -58,7 +58,7 @@ export type OpenClawPluginRestorePlanResult = } | { ok: false; error: string }; -const OPENCLAW_PLUGIN_INDEX_SQLITE_PY = [ +export const OPENCLAW_PLUGIN_INDEX_SQLITE_PY = [ "import json, sqlite3, sys, urllib.parse", 'uri = "file:" + urllib.parse.quote(sys.argv[1], safe="/") + "?mode=ro"', "conn = sqlite3.connect(uri, uri=True, timeout=30)", @@ -77,7 +77,7 @@ const OPENCLAW_PLUGIN_INDEX_SQLITE_PY = [ " conn.close()", ].join("\n"); -const OPENCLAW_PLUGIN_INDEX_LEGACY_PY = [ +export const OPENCLAW_PLUGIN_INDEX_LEGACY_PY = [ "import json, sys", "with open(sys.argv[1], 'r', encoding='utf-8') as index_file: index = json.load(index_file)", "with open(sys.argv[2], 'r', encoding='utf-8') as config_file: config = json.load(config_file)", @@ -108,7 +108,7 @@ export function buildFreshOpenClawPluginIndexSqliteReadCommand(dir: string): str `cfg=${quotedConfigPath}`, ...buildSafeRegularFileReadGuard("db", 2), ...buildSafeRegularFileReadGuard("cfg", 12), - `python3 -c ${shellQuote(OPENCLAW_PLUGIN_INDEX_SQLITE_PY)} "$db" "$cfg"`, + 'python3 -I - "$db" "$cfg"', ].join("; "); } @@ -122,7 +122,7 @@ function buildLegacyOpenClawPluginIndexReadCommand(dir: string): string { `cfg=${quotedConfigPath}`, ...buildSafeRegularFileReadGuard("src", 2), ...buildSafeRegularFileReadGuard("cfg", 12), - `python3 -c ${shellQuote(OPENCLAW_PLUGIN_INDEX_LEGACY_PY)} "$src" "$cfg"`, + 'python3 -I - "$src" "$cfg"', ].join("; "); } @@ -137,6 +137,7 @@ async function readFreshOpenClawPluginInstallIndex( const sqliteResult = await execSandboxReadOnlyWithGrpcFallback(gatewayName, { sandboxName, command: ["sh", "-c", buildFreshOpenClawPluginIndexSqliteReadCommand(dir)], + stdin: OPENCLAW_PLUGIN_INDEX_SQLITE_PY, timeoutMs: 30_000, maxOutputBytes: OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES, }); @@ -145,6 +146,7 @@ async function readFreshOpenClawPluginInstallIndex( return execSandboxReadOnlyWithGrpcFallback(gatewayName, { sandboxName, command: ["sh", "-c", buildLegacyOpenClawPluginIndexReadCommand(dir)], + stdin: OPENCLAW_PLUGIN_INDEX_LEGACY_PY, timeoutMs: 30_000, maxOutputBytes: OPENCLAW_PLUGIN_INSTALL_REGISTRY_MAX_BYTES, }); diff --git a/src/lib/state/sandbox-openclaw-plugin-restore.test.ts b/src/lib/state/sandbox-openclaw-plugin-restore.test.ts index 7804b6ff2a8..9bd53d7bc18 100644 --- a/src/lib/state/sandbox-openclaw-plugin-restore.test.ts +++ b/src/lib/state/sandbox-openclaw-plugin-restore.test.ts @@ -9,7 +9,11 @@ vi.mock("../adapters/openshell/sandbox-control-routing", () => ({ execSandboxReadOnlyWithGrpcFallback: vi.fn(), })); -import { discoverFreshOpenClawPluginExtensionDirs } from "./openclaw-plugin-restore"; +import { + discoverFreshOpenClawPluginExtensionDirs, + OPENCLAW_PLUGIN_INDEX_LEGACY_PY, + OPENCLAW_PLUGIN_INDEX_SQLITE_PY, +} from "./openclaw-plugin-restore"; const OPENCLAW_DIR = "/sandbox/.openclaw"; const MAX_PLUGIN_REGISTRY_BYTES = 1024 * 1024; @@ -55,6 +59,8 @@ describe("fresh OpenClaw plugin registry reads", () => { expect(execMock).toHaveBeenCalledOnce(); expect(execMock.mock.calls[0]?.[1]).toEqual( expect.objectContaining({ + command: ["sh", "-c", expect.stringContaining('python3 -I - "$db" "$cfg"')], + stdin: OPENCLAW_PLUGIN_INDEX_SQLITE_PY, maxOutputBytes: MAX_PLUGIN_REGISTRY_BYTES, timeoutMs: 30_000, }), @@ -91,6 +97,9 @@ describe("fresh OpenClaw plugin registry reads", () => { }); expect(parseSpy).not.toHaveBeenCalled(); expect(execMock).toHaveBeenCalledTimes(2); + expect(execMock.mock.calls[1]?.[1]).toEqual( + expect.objectContaining({ stdin: OPENCLAW_PLUGIN_INDEX_LEGACY_PY }), + ); for (const call of execMock.mock.calls) { expect(call[1]).toEqual( expect.objectContaining({ diff --git a/src/lib/state/sandbox-recreated-openclaw-restore.test.ts b/src/lib/state/sandbox-recreated-openclaw-restore.test.ts index acac0cbd91d..4081cc18f02 100644 --- a/src/lib/state/sandbox-recreated-openclaw-restore.test.ts +++ b/src/lib/state/sandbox-recreated-openclaw-restore.test.ts @@ -1,51 +1,44 @@ // 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 { describe, expect, it, vi } from "vitest"; -vi.mock("../adapters/openshell/sandbox-control-routing", async () => { - const { spawnSync } = await import("node:child_process"); - const exec = async (request: { - command: readonly string[]; - stdin?: string | Buffer; - maxOutputBytes?: number; - timeoutMs?: number; - stdoutEncoding?: "utf8" | "buffer"; - }) => { - const binary = request.stdoutEncoding === "buffer"; - const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { - input: request.stdin, - maxBuffer: request.maxOutputBytes, - timeout: request.timeoutMs, - encoding: binary ? undefined : "utf8", - }); - 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 } : {}), - }; - }; - return { - execSandboxReadOnlyWithGrpcFallback: async ( - _gateway: string, - request: Parameters[0], - ) => exec(request), - selectOpenShellSandboxControlForMutation: () => ({ - control: { exec }, - transport: "grpc", - close: () => {}, - }), - }; -}); +import type { SandboxExecRequest } from "../adapters/openshell/sandbox-control.js"; + +const mocks = vi.hoisted(() => ({ + exec: vi.fn(), + getSandbox: vi.fn(), + upload: vi.fn(), +})); + +vi.mock("../adapters/openshell/sandbox-control-routing.js", async (importOriginal) => ({ + ...(await importOriginal()), + execSandboxReadOnlyWithGrpcFallback: async ( + _gateway: string, + request: Parameters[0], + ) => mocks.exec(request), + selectOpenShellSandboxControlForMutation: () => ({ + control: { exec: mocks.exec }, + transport: "grpc", + close: () => {}, + }), +})); + +vi.mock("../adapters/openshell/sandbox-upload.js", async (importOriginal) => ({ + ...(await importOriginal()), + uploadSandboxPayloadFile: mocks.upload, +})); + +vi.mock("./registry.js", async (importOriginal) => ({ + ...(await importOriginal()), + getSandbox: mocks.getSandbox, +})); -import { restoreEnvBulk } from "../../../test/helpers/env-test-helpers.js"; import type { OpenClawImagePluginInstall } from "./openclaw-plugin-restore.js"; import { restoreRecreatedSandboxState } from "./sandbox.js"; @@ -56,10 +49,6 @@ function imageInstall(id: string, extensionDir: string): OpenClawImagePluginInst return { id, installPath, loadPaths: [installPath] }; } -function writeExecutable(filePath: string, source: string): void { - fs.writeFileSync(filePath, source, { mode: 0o755 }); -} - function extensionDir(install: OpenClawImagePluginInstall): string | null { const prefix = `${OPENCLAW_DIR}/extensions/`; return install.installPath.startsWith(prefix) ? install.installPath.slice(prefix.length) : null; @@ -72,7 +61,6 @@ async function runRestoreScenario(options: { freshPluginInstalls: OpenClawImagePluginInstall[]; previousPluginInstalls?: OpenClawImagePluginInstall[]; }): Promise<{ - cleanupCommand: string | undefined; freshMarkers: Record; restore: Awaited>; restoredConfig: Record; @@ -80,22 +68,21 @@ async function runRestoreScenario(options: { userExtensionMarker: string; }> { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-recreated-restore-")); - const previousOpenshellBin = process.env.NEMOCLAW_OPENSHELL_BIN; - const previousPath = process.env.PATH; try { - const binDir = path.join(fixture, "bin"); - const openclawDir = path.join(fixture, "sandbox-root", ".openclaw"); + const sandboxRoot = path.join(fs.realpathSync(fixture), "sandbox-root"); + fs.mkdirSync(sandboxRoot); + const openclawDir = path.join(fs.realpathSync(sandboxRoot), ".openclaw"); const extensionsDir = path.join(openclawDir, "extensions"); const backupPath = path.join(fixture, "backup"); const backupExtensionsDir = path.join(backupPath, "extensions"); - const sshLog = path.join(fixture, "ssh-log.jsonl"); + const stagedRemotePaths = new Map(); const freshExtensionDirs = [ "nemoclaw", ...options.freshPluginInstalls .map(extensionDir) .filter((entry): entry is string => entry !== null), ]; - fs.mkdirSync(binDir, { recursive: true }); + fs.mkdirSync(extensionsDir, { recursive: true }); for (const extensionName of freshExtensionDirs) { const target = path.join(extensionsDir, extensionName); @@ -134,79 +121,58 @@ async function runRestoreScenario(options: { : {}), }; fs.writeFileSync(path.join(backupPath, "rebuild-manifest.json"), JSON.stringify(manifest)); - - const openshell = path.join(binDir, "openshell"); - writeExecutable( - openshell, - `#!/usr/bin/env node -const args = process.argv.slice(2); -if (args[0] === "sandbox" && args[1] === "ssh-config") { - process.stdout.write("Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n"); -} -process.exit(0); -`, - ); - writeExecutable( - path.join(binDir, "ssh"), - `#!/usr/bin/env node -const fs = require("node:fs"); -const path = require("node:path"); -const { spawnSync } = require("node:child_process"); -const cmd = process.argv[process.argv.length - 1] || ""; -const openclawDir = ${JSON.stringify(openclawDir)}; -const extensionsDir = ${JSON.stringify(extensionsDir)}; -fs.appendFileSync(${JSON.stringify(sshLog)}, JSON.stringify({ cmd }) + "\\n"); -function readStdin() { - const chunks = []; - for (;;) { - const buffer = Buffer.alloc(65536); - const count = fs.readSync(0, buffer, 0, buffer.length, null); - if (count === 0) break; - chunks.push(buffer.subarray(0, count)); - } - return Buffer.concat(chunks); -} -if (cmd.includes("${OPENCLAW_DIR}/extensions") && cmd.includes("-exec rm -rf")) { - const preserved = new Set(${JSON.stringify(freshExtensionDirs)}); - for (const entry of fs.readdirSync(extensionsDir)) { - if (!preserved.has(entry)) fs.rmSync(path.join(extensionsDir, entry), { recursive: true, force: true }); - } - process.exit(0); -} -if (cmd.includes("tar --no-same-owner -xf -")) { - const result = spawnSync("tar", ["--no-same-owner", "-xf", "-", "-C", openclawDir], { - input: readStdin(), - stdio: ["pipe", "pipe", "pipe"], - }); - process.exit(result.status || 0); -} -if (cmd.includes("chown") || cmd.includes("[ -d ")) process.exit(0); -if (cmd.includes("openclaw.json") && cmd.includes("cat --")) { - process.stdout.write(fs.readFileSync(path.join(openclawDir, "openclaw.json"))); - process.exit(0); -} -if (cmd.includes("openclaw.json") && cmd.includes(".nemoclaw-restore")) { - fs.writeFileSync(path.join(openclawDir, "openclaw.json"), readStdin()); - process.exit(0); -} -process.exit(1); -`, + mocks.getSandbox.mockReturnValue({ + name: "alpha", + agent: "openclaw", + gatewayName: "nemoclaw", + }); + mocks.upload.mockImplementation( + (_gateway: string, _sandbox: string, localPath: string, remotePath: string) => { + const stagedPath = path.join( + fs.realpathSync(path.dirname(remotePath)), + path.basename(remotePath), + ); + fs.copyFileSync(localPath, stagedPath); + stagedRemotePaths.set(remotePath, stagedPath); + return { ok: true, remotePath }; + }, ); + mocks.exec.mockImplementation(async (request: SandboxExecRequest) => { + if (request.command[0] === "sh") { + return { + status: 0, + stdout: "", + stdoutBytes: fs.readFileSync(path.join(openclawDir, "openclaw.json")), + stderr: "", + }; + } + const command = [...request.command]; + command[3] = stagedRemotePaths.get(command[3]) ?? command[3]; + command[4] = openclawDir; + const result = spawnSync(command[0], command.slice(1), { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: request.stdoutEncoding === "buffer" ? undefined : "utf8", + }); + return { + status: result.status, + stdout: request.stdoutEncoding === "buffer" ? "" : String(result.stdout ?? ""), + ...(request.stdoutEncoding === "buffer" + ? { stdoutBytes: Buffer.from(result.stdout ?? "") } + : {}), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + }); - process.env.NEMOCLAW_OPENSHELL_BIN = openshell; - process.env.PATH = `${binDir}:${previousPath ?? ""}`; const restore = await restoreRecreatedSandboxState("alpha", backupPath, { targetAgentType: "openclaw", freshOpenClawImagePluginInstalls: options.freshPluginInstalls, }); - const loggedCommands = fs - .readFileSync(sshLog, "utf8") - .trim() - .split("\n") - .map((line) => JSON.parse(line).cmd as string); return { - cleanupCommand: loggedCommands.find((command) => command.includes("-exec rm -rf")), freshMarkers: Object.fromEntries( freshExtensionDirs.map((name) => [ name, @@ -216,13 +182,14 @@ process.exit(1); restore, restoredConfig: JSON.parse(fs.readFileSync(path.join(openclawDir, "openclaw.json"), "utf8")), staleUserExtensionExists: fs.existsSync(path.join(extensionsDir, "stale-user-extension")), - userExtensionMarker: fs.readFileSync( - path.join(extensionsDir, "user-extension", "marker.txt"), - "utf8", - ), + userExtensionMarker: fs.existsSync(path.join(extensionsDir, "user-extension", "marker.txt")) + ? fs.readFileSync(path.join(extensionsDir, "user-extension", "marker.txt"), "utf8") + : "missing", }; } finally { - restoreEnvBulk({ NEMOCLAW_OPENSHELL_BIN: previousOpenshellBin, PATH: previousPath }); + mocks.exec.mockReset(); + mocks.getSandbox.mockReset(); + mocks.upload.mockReset(); fs.rmSync(fixture, { recursive: true, force: true }); } } @@ -276,8 +243,6 @@ describe("recreated OpenClaw state restore", () => { "user-plugin": { enabled: true }, weather: { enabled: true, config: { revision: "fresh" } }, }); - expect(result.cleanupCommand).toContain("! -name 'nemoclaw'"); - expect(result.cleanupCommand).toContain("! -name 'weather'"); }); it("reconciles populated previous and fresh image-plugin provenance during config restore", async () => { diff --git a/src/lib/state/sandbox-restore-payload.test.ts b/src/lib/state/sandbox-restore-payload.test.ts new file mode 100644 index 00000000000..964c81a66b8 --- /dev/null +++ b/src/lib/state/sandbox-restore-payload.test.ts @@ -0,0 +1,471 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { + encodeStateDirectoryRestoreMetadata, + MAX_STATE_DIRECTORY_RESTORE_DIRS, + MAX_STATE_DIRECTORY_RESTORE_MANAGED_EXTENSIONS, + MAX_STATE_DIRECTORY_RESTORE_METADATA_BYTES, + STATE_DIRECTORY_RESTORE_MAGIC, + STATE_DIRECTORY_RESTORE_PYTHON, + STATE_DIRECTORY_RESTORE_VERSION, +} from "./sandbox-restore-payload.js"; + +interface TarEntry { + name: string; + type?: "directory" | "file" | "hardlink" | "symlink" | "fifo" | "sparse"; + linkname?: string; + data?: Buffer; + declaredSize?: number; + mode?: number; +} + +const fixtures: string[] = []; + +function writeAscii(target: Buffer, offset: number, length: number, value: string): void { + target.write(value, offset, Math.min(length, Buffer.byteLength(value)), "ascii"); +} + +function writeOctal(target: Buffer, offset: number, length: number, value: number): void { + writeAscii(target, offset, length, `${value.toString(8).padStart(length - 1, "0")}\0`); +} + +function tarArchive(entries: readonly TarEntry[]): Buffer { + const chunks: Buffer[] = []; + for (const entry of entries) { + const header = Buffer.alloc(512); + const data = entry.data ?? Buffer.alloc(0); + writeAscii(header, 0, 100, entry.name); + writeOctal(header, 100, 8, entry.mode ?? 0o755); + writeOctal(header, 108, 8, 0); + writeOctal(header, 116, 8, 0); + writeOctal(header, 124, 12, entry.declaredSize ?? data.length); + writeOctal(header, 136, 12, 0); + header.fill(0x20, 148, 156); + const type = entry.type ?? "file"; + header[156] = { + directory: 0x35, + file: 0x30, + hardlink: 0x31, + symlink: 0x32, + fifo: 0x36, + sparse: 0x53, + }[type]; + writeAscii(header, 157, 100, entry.linkname ?? ""); + writeAscii(header, 257, 6, "ustar\0"); + writeAscii(header, 263, 2, "00"); + const checksum = header.reduce((sum, byte) => sum + byte, 0); + writeAscii(header, 148, 8, `${checksum.toString(8).padStart(6, "0")}\0 `); + chunks.push(header); + chunks.push(data, Buffer.alloc((512 - (data.length % 512)) % 512)); + } + chunks.push(Buffer.alloc(1024)); + return Buffer.concat(chunks); +} + +function framedPayload( + directories: readonly string[], + managedExtensions: readonly (readonly [string, boolean])[], + archive: Buffer, +): Buffer { + const metadata = Buffer.from(JSON.stringify({ directories, managedExtensions }), "utf8"); + const header = Buffer.alloc(STATE_DIRECTORY_RESTORE_MAGIC.length + 5); + STATE_DIRECTORY_RESTORE_MAGIC.copy(header); + header.writeUInt8(STATE_DIRECTORY_RESTORE_VERSION, STATE_DIRECTORY_RESTORE_MAGIC.length); + header.writeUInt32BE(metadata.length, STATE_DIRECTORY_RESTORE_MAGIC.length + 1); + return Buffer.concat([header, metadata, archive]); +} + +function truncatedRegularArchive(): Buffer { + const archive = tarArchive([ + { name: "workspace", type: "directory" }, + { name: "workspace/data", data: Buffer.alloc(1024, 0x41) }, + ]); + return archive.subarray(0, 512 + 512 + 100); +} + +function fixture(): { base: string; remotePath: string; stateRoot: string } { + const base = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-restore-program-"))); + fixtures.push(base); + const stateRoot = path.join(base, "state-root"); + fs.mkdirSync(stateRoot); + return { + base, + stateRoot, + remotePath: path.join(base, "nemoclaw-state-restore-fixture"), + }; +} + +function runProgram( + remotePath: string, + stateRoot: string, + program = STATE_DIRECTORY_RESTORE_PYTHON, + expectedDigest?: string, + timeout = 30_000, +) { + const digest = createHash("sha256").update(fs.readFileSync(remotePath)).digest("hex"); + return spawnSync("python3", ["-I", "-", remotePath, stateRoot, expectedDigest ?? digest], { + input: program, + encoding: "utf8", + timeout, + maxBuffer: 64 * 1024, + }); +} + +afterEach(() => { + for (const item of fixtures.splice(0)) fs.rmSync(item, { recursive: true, force: true }); +}); + +describe("framed state directory restore", () => { + it("preserves managed extensions, strips special modes, and extracts in bounded Python", () => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "extensions", "managed"), { recursive: true }); + fs.writeFileSync(path.join(stateRoot, "extensions", "managed", "keep"), "fresh"); + fs.mkdirSync(path.join(stateRoot, "extensions", "stale"), { recursive: true }); + fs.writeFileSync(path.join(stateRoot, "extensions", "stale", "remove"), "old"); + const archive = tarArchive([ + { name: "extensions", type: "directory" }, + { name: "extensions/user", type: "directory" }, + { name: "extensions/user/tool", data: Buffer.from("restored"), mode: 0o4755 }, + { name: "extensions/user/node_modules", type: "directory" }, + { name: "extensions/user/node_modules/.bin", type: "directory" }, + { + name: "extensions/user/node_modules/.bin/tool", + type: "symlink", + linkname: "../tool/bin.js", + }, + ]); + fs.writeFileSync(remotePath, framedPayload(["extensions"], [["managed", true]], archive), { + mode: 0o600, + }); + + const result = runProgram(remotePath, stateRoot); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("RESTORE_OK"); + expect(fs.existsSync(remotePath)).toBe(false); + expect(fs.readFileSync(path.join(stateRoot, "extensions", "managed", "keep"), "utf8")).toBe( + "fresh", + ); + expect(fs.existsSync(path.join(stateRoot, "extensions", "stale"))).toBe(false); + const restored = path.join(stateRoot, "extensions", "user", "tool"); + expect(fs.readFileSync(restored, "utf8")).toBe("restored"); + expect(fs.statSync(restored).mode & 0o7000).toBe(0); + expect( + fs.readlinkSync(path.join(stateRoot, "extensions", "user", "node_modules", ".bin", "tool")), + ).toBe("../tool/bin.js"); + }); + + it("creates a missing parent for an explicitly declared nested state directory", () => { + const { remotePath, stateRoot } = fixture(); + fs.writeFileSync( + remotePath, + framedPayload( + ["agent/skills"], + [], + tarArchive([ + { name: "agent/skills", type: "directory" }, + { name: "agent/skills/SKILL.md", data: Buffer.from("restored\n") }, + ]), + ), + { mode: 0o600 }, + ); + + const result = runProgram(remotePath, stateRoot); + + expect(result.status, result.stderr).toBe(0); + expect(fs.readFileSync(path.join(stateRoot, "agent", "skills", "SKILL.md"), "utf8")).toBe( + "restored\n", + ); + }); + + it("rejects replacement of a preserved managed extension after cleanup", () => { + const { remotePath, stateRoot } = fixture(); + const managedPath = path.join(stateRoot, "extensions", "managed"); + fs.mkdirSync(managedPath, { recursive: true }); + fs.writeFileSync(path.join(managedPath, "keep"), "fresh"); + fs.writeFileSync( + remotePath, + framedPayload( + ["extensions"], + [["managed", true]], + tarArchive([{ name: "extensions", type: "directory" }]), + ), + { mode: 0o600 }, + ); + const extractionCall = " extract_archive(stream, tar_offset, root_fd, records)"; + const raceProgram = STATE_DIRECTORY_RESTORE_PYTHON.replace( + extractionCall, + String.raw` attack_fd = open_dir_at(root_fd, ["extensions"], False) + try: + os.replace("managed", "managed-before-race", src_dir_fd=attack_fd, dst_dir_fd=attack_fd) + os.mkdir("managed", 0o700, dir_fd=attack_fd) + finally: + os.close(attack_fd) + extract_archive(stream, tar_offset, root_fd, records)`, + ); + expect(raceProgram).not.toBe(STATE_DIRECTORY_RESTORE_PYTHON); + + const result = runProgram(remotePath, stateRoot, raceProgram); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("managed extension changed during restore"); + expect(result.stdout).not.toContain("RESTORE_OK"); + expect( + fs.readFileSync(path.join(stateRoot, "extensions", "managed-before-race", "keep"), "utf8"), + ).toBe("fresh"); + }); + + it("pins a newly created root for absent optional managed extensions", () => { + const { remotePath, stateRoot } = fixture(); + fs.writeFileSync( + remotePath, + framedPayload( + ["extensions"], + [["optional", false]], + tarArchive([{ name: "extensions", type: "directory" }]), + ), + { mode: 0o600 }, + ); + const extractionCall = " extract_archive(stream, tar_offset, root_fd, records)"; + const raceProgram = STATE_DIRECTORY_RESTORE_PYTHON.replace( + extractionCall, + String.raw` os.replace("extensions", "extensions-before-race", src_dir_fd=root_fd, dst_dir_fd=root_fd) + os.mkdir("extensions", 0o700, dir_fd=root_fd) + extract_archive(stream, tar_offset, root_fd, records)`, + ); + expect(raceProgram).not.toBe(STATE_DIRECTORY_RESTORE_PYTHON); + + const result = runProgram(remotePath, stateRoot, raceProgram); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("managed extension root changed during restore"); + expect(result.stdout).not.toContain("RESTORE_OK"); + }); + + it.each([ + ["traversal", { name: "../escape", data: Buffer.from("x") }], + ["hard link", { name: "workspace/hard", type: "hardlink", linkname: "workspace/file" }], + ["special file", { name: "workspace/pipe", type: "fifo" }], + ["sparse file", { name: "workspace/sparse", type: "sparse", declaredSize: 4096 }], + ["unsafe link", { name: "workspace/leak", type: "symlink", linkname: "/etc/passwd" }], + ] as const)("rejects a %s member table before target mutation", (_label, entry) => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + fs.writeFileSync(remotePath, framedPayload(["workspace"], [], tarArchive([entry])), { + mode: 0o600, + }); + + const result = runProgram(remotePath, stateRoot); + + expect(result.status).not.toBe(0); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it.each([ + ["empty archive", tarArchive([])], + ["implicit root", tarArchive([{ name: "workspace/child", data: Buffer.from("x") }])], + ["unusable root mode", tarArchive([{ name: "workspace", type: "directory", mode: 0o000 }])], + [ + "non-directory ancestor", + tarArchive([ + { name: "workspace", type: "directory" }, + { name: "workspace/file", data: Buffer.alloc(0) }, + { name: "workspace/file/child", data: Buffer.from("x") }, + ]), + ], + [ + "late non-directory ancestor", + tarArchive([ + { name: "workspace", type: "directory" }, + { name: "workspace/file/child", data: Buffer.from("x") }, + { name: "workspace/file", data: Buffer.alloc(0) }, + ]), + ], + ["truncated regular payload", truncatedRegularArchive()], + ] as const)("rejects an unsafe %s before cleaning the target", (_label, archive) => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + fs.writeFileSync(remotePath, framedPayload(["workspace"], [], archive), { mode: 0o600 }); + + const result = runProgram(remotePath, stateRoot); + + expect(result.status).not.toBe(0); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it("rejects an oversized metadata length before target mutation", () => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + const header = Buffer.alloc(STATE_DIRECTORY_RESTORE_MAGIC.length + 5); + STATE_DIRECTORY_RESTORE_MAGIC.copy(header); + header.writeUInt8(STATE_DIRECTORY_RESTORE_VERSION, STATE_DIRECTORY_RESTORE_MAGIC.length); + header.writeUInt32BE( + MAX_STATE_DIRECTORY_RESTORE_METADATA_BYTES + 1, + STATE_DIRECTORY_RESTORE_MAGIC.length + 1, + ); + fs.writeFileSync(remotePath, header, { mode: 0o600 }); + + const result = runProgram(remotePath, stateRoot); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("metadata exceeds limit"); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it("rejects an archive whose physical tar bytes exceed the fixed cap", () => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + const archive = tarArchive([ + { name: "workspace", type: "directory" }, + { name: "workspace/data", data: Buffer.alloc(1024) }, + ]); + fs.writeFileSync(remotePath, framedPayload(["workspace"], [], archive), { mode: 0o600 }); + const boundedProgram = STATE_DIRECTORY_RESTORE_PYTHON.replace( + "MAX_ARCHIVE = 256 * 1024 * 1024", + "MAX_ARCHIVE = 2 * 1024", + ); + + const result = runProgram(remotePath, stateRoot, boundedProgram); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("archive exceeds limit"); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it("rejects an uploaded directory payload with a mismatched digest", () => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + fs.writeFileSync( + remotePath, + framedPayload(["workspace"], [], tarArchive([{ name: "workspace", type: "directory" }])), + { mode: 0o600 }, + ); + + const result = runProgram( + remotePath, + stateRoot, + STATE_DIRECTORY_RESTORE_PYTHON, + "0".repeat(64), + ); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("digest mismatch"); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it("rejects a high-cardinality conflict within the fixed runtime budget", () => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + const entries: TarEntry[] = [{ name: "workspace", type: "directory" }]; + entries.push( + ...Array.from({ length: 4096 }, (_unused, index) => ({ + name: `workspace/dir-${String(index).padStart(4, "0")}/child`, + data: Buffer.alloc(0), + })), + { name: "workspace/dir-4095", data: Buffer.alloc(0) }, + ); + fs.writeFileSync(remotePath, framedPayload(["workspace"], [], tarArchive(entries)), { + mode: 0o600, + }); + + const result = runProgram( + remotePath, + stateRoot, + STATE_DIRECTORY_RESTORE_PYTHON, + undefined, + 5000, + ); + + expect(result.error).toBeUndefined(); + expect(result.status).not.toBe(0); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it("rejects symlink races in both staged-file and state-root components", () => { + const { base, remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + const payload = framedPayload( + ["workspace"], + [], + tarArchive([{ name: "workspace", type: "directory" }]), + ); + const realPayload = path.join(base, "real-payload"); + fs.writeFileSync(realPayload, payload, { mode: 0o600 }); + fs.symlinkSync(realPayload, remotePath); + expect(runProgram(remotePath, stateRoot).status).not.toBe(0); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + + fs.rmSync(remotePath); + fs.writeFileSync(remotePath, payload, { mode: 0o600 }); + const rootLink = path.join(base, "state-root-link"); + fs.symlinkSync(stateRoot, rootLink); + expect(runProgram(remotePath, rootLink).status).not.toBe(0); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it("rejects a group/world-writable staged payload before target mutation", () => { + const { remotePath, stateRoot } = fixture(); + fs.mkdirSync(path.join(stateRoot, "workspace")); + const marker = path.join(stateRoot, "workspace", "keep"); + fs.writeFileSync(marker, "untouched"); + fs.writeFileSync( + remotePath, + framedPayload(["workspace"], [], tarArchive([{ name: "workspace", type: "directory" }])), + { mode: 0o666 }, + ); + fs.chmodSync(remotePath, 0o666); + + const result = runProgram(remotePath, stateRoot); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("unsafe staged restore file"); + expect(fs.readFileSync(marker, "utf8")).toBe("untouched"); + }); + + it("bounds high-cardinality directory and managed-extension metadata", () => { + const directories = Array.from( + { length: MAX_STATE_DIRECTORY_RESTORE_DIRS }, + (_unused, index) => `dir-${String(index).padStart(5, "0")}`, + ); + const atLimit = encodeStateDirectoryRestoreMetadata(directories, []); + expect(atLimit.ok).toBe(true); + expect(encodeStateDirectoryRestoreMetadata([...directories, "one-too-many"], [])).toMatchObject( + { ok: false, error: expect.stringContaining("1-16384") }, + ); + + const managed = Array.from( + { length: MAX_STATE_DIRECTORY_RESTORE_MANAGED_EXTENSIONS }, + (_unused, index) => ({ name: `extension-${String(index)}`, required: index % 2 === 0 }), + ); + expect(encodeStateDirectoryRestoreMetadata(["extensions"], managed).ok).toBe(true); + expect( + encodeStateDirectoryRestoreMetadata( + ["extensions"], + [...managed, { name: "one-too-many", required: false }], + ), + ).toMatchObject({ ok: false, error: expect.stringContaining("exceeds 256") }); + }); +}); diff --git a/src/lib/state/sandbox-restore-payload.ts b/src/lib/state/sandbox-restore-payload.ts new file mode 100644 index 00000000000..ae1e40047ec --- /dev/null +++ b/src/lib/state/sandbox-restore-payload.ts @@ -0,0 +1,918 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawn } from "node:child_process"; +import { createHash, type Hash } from "node:crypto"; +import { + chmodSync, + closeSync, + fstatSync, + fsyncSync, + mkdtempSync, + openSync, + rmSync, + writeFileSync, + writeSync, +} from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { isSafeOpenClawExtensionDirName } from "./openclaw-plugin-restore.js"; + +export const STATE_DIRECTORY_RESTORE_MAGIC = Buffer.from("NEMOCLAW_STATE_RESTORE\0", "ascii"); +export const STATE_DIRECTORY_RESTORE_VERSION = 1; +export const MAX_STATE_DIRECTORY_RESTORE_METADATA_BYTES = 512 * 1024; +export const MAX_STATE_DIRECTORY_RESTORE_DIRS = 16 * 1024; +export const MAX_STATE_DIRECTORY_RESTORE_MANAGED_EXTENSIONS = 256; +export const MAX_STATE_DIRECTORY_RESTORE_ARCHIVE_BYTES = 256 * 1024 * 1024; +const STATE_DIRECTORY_RESTORE_HEADER_BYTES = STATE_DIRECTORY_RESTORE_MAGIC.length + 1 + 4; +const STATE_DIRECTORY_RESTORE_TAR_TIMEOUT_MS = 60_000; +const STATE_DIRECTORY_RESTORE_TAR_DIAGNOSTIC_BYTES = 64 * 1024; + +export interface ManagedExtensionRestoreRecord { + readonly name: string; + readonly required: boolean; +} + +interface StateDirectoryRestoreMetadata { + readonly directories: readonly string[]; + readonly managedExtensions: readonly (readonly [string, boolean])[]; +} + +export interface StateDirectoryRestorePayload { + readonly localPath: string; + readonly remotePath: string; + readonly sha256: string; + readonly sizeBytes: number; + cleanup(): void; +} + +export type StateDirectoryRestorePayloadResult = + | { ok: true; payload: StateDirectoryRestorePayload } + | { ok: false; error: string }; + +export type StateDirectoryRestoreMetadataResult = + | { ok: true; metadata: Buffer } + | { ok: false; error: string }; + +function isSafeRestoreDirectoryName(name: string): boolean { + if ( + name.length === 0 || + name.length > 4096 || + name.includes("\0") || + name.includes("\r") || + name.includes("\n") || + name.includes("\\") || + path.posix.isAbsolute(name) + ) { + return false; + } + const normalized = path.posix.normalize(name); + return ( + normalized === name && + normalized !== "." && + normalized !== ".." && + !normalized.startsWith("../") + ); +} + +function validateRestoreDirectories(directories: readonly string[]): string | null { + if (directories.length === 0 || directories.length > MAX_STATE_DIRECTORY_RESTORE_DIRS) { + return `state directory restore requires 1-${String(MAX_STATE_DIRECTORY_RESTORE_DIRS)} directories`; + } + const seen = new Set(); + for (const directory of directories) { + if (!isSafeRestoreDirectoryName(directory)) { + return `state directory restore contains an unsafe directory name: ${JSON.stringify(directory)}`; + } + if (seen.has(directory)) { + return `state directory restore repeats directory ${JSON.stringify(directory)}`; + } + seen.add(directory); + } + for (const directory of directories) { + const parts = directory.split("/"); + for (let index = 1; index < parts.length; index += 1) { + const ancestor = parts.slice(0, index).join("/"); + if (seen.has(ancestor)) { + return `state directory restore contains overlapping directories ${JSON.stringify(ancestor)} and ${JSON.stringify(directory)}`; + } + } + } + return null; +} + +function validateManagedExtensions( + directories: readonly string[], + managedExtensions: readonly ManagedExtensionRestoreRecord[], +): string | null { + if (managedExtensions.length > MAX_STATE_DIRECTORY_RESTORE_MANAGED_EXTENSIONS) { + return `state directory restore exceeds ${String(MAX_STATE_DIRECTORY_RESTORE_MANAGED_EXTENSIONS)} managed extensions`; + } + if (managedExtensions.length > 0 && !directories.includes("extensions")) { + return "managed extensions require the extensions state directory"; + } + const seen = new Set(); + for (const extension of managedExtensions) { + if (!isSafeOpenClawExtensionDirName(extension.name) || seen.has(extension.name)) { + return `state directory restore contains an unsafe or repeated managed extension: ${JSON.stringify(extension.name)}`; + } + seen.add(extension.name); + } + return null; +} + +function validateArchiveExcludedExtensions( + directories: readonly string[], + extensions: readonly string[], +): string | null { + if (extensions.length > MAX_STATE_DIRECTORY_RESTORE_MANAGED_EXTENSIONS) { + return `state directory restore exceeds ${String(MAX_STATE_DIRECTORY_RESTORE_MANAGED_EXTENSIONS)} archive-excluded extensions`; + } + if (extensions.length > 0 && !directories.includes("extensions")) { + return "archive-excluded extensions require the extensions state directory"; + } + const seen = new Set(); + for (const extension of extensions) { + if (!isSafeOpenClawExtensionDirName(extension) || seen.has(extension)) { + return `state directory restore contains an unsafe or repeated archive-excluded extension: ${JSON.stringify(extension)}`; + } + seen.add(extension); + } + return null; +} + +function payloadHeader(metadataBytes: number): Buffer { + const header = Buffer.alloc(STATE_DIRECTORY_RESTORE_HEADER_BYTES); + STATE_DIRECTORY_RESTORE_MAGIC.copy(header, 0); + header.writeUInt8(STATE_DIRECTORY_RESTORE_VERSION, STATE_DIRECTORY_RESTORE_MAGIC.length); + header.writeUInt32BE(metadataBytes, STATE_DIRECTORY_RESTORE_MAGIC.length + 1); + return header; +} + +function writeAllSync(fd: number, contents: Buffer): void { + let offset = 0; + while (offset < contents.length) { + const written = writeSync(fd, contents, offset, contents.length - offset); + if (written <= 0) throw new Error("could not write staged restore payload"); + offset += written; + } +} + +export function encodeStateDirectoryRestoreMetadata( + directories: readonly string[], + managedExtensions: readonly ManagedExtensionRestoreRecord[], +): StateDirectoryRestoreMetadataResult { + const directoryError = validateRestoreDirectories(directories); + if (directoryError) return { ok: false, error: directoryError }; + const extensionError = validateManagedExtensions(directories, managedExtensions); + if (extensionError) return { ok: false, error: extensionError }; + const metadata: StateDirectoryRestoreMetadata = { + directories, + managedExtensions: managedExtensions.map( + (extension) => [extension.name, extension.required] as const, + ), + }; + const encodedMetadata = Buffer.from(JSON.stringify(metadata), "utf8"); + if (encodedMetadata.length > MAX_STATE_DIRECTORY_RESTORE_METADATA_BYTES) { + return { + ok: false, + error: `state directory restore metadata exceeds ${String(MAX_STATE_DIRECTORY_RESTORE_METADATA_BYTES)} bytes`, + }; + } + return { ok: true, metadata: encodedMetadata }; +} + +interface StreamedTarResult { + error?: Error; + overflow: boolean; + signal: NodeJS.Signals | null; + status: number | null; + stderr: Buffer; +} + +function tarFailureDetail(result: StreamedTarResult): string { + const stderr = result.stderr.toString("utf8").trim(); + return ( + stderr || + result.error?.message || + (result.signal ? `signal ${result.signal}` : `exit ${String(result.status)}`) + ).substring(0, 200); +} + +function streamTarArchive( + args: readonly string[], + payloadFd: number, + digest: Hash, +): Promise { + return new Promise((resolve) => { + const child = spawn("tar", args, { + stdio: ["ignore", "pipe", "pipe"], + env: { ...process.env, COPYFILE_DISABLE: "1" }, + }); + const stderrChunks: Buffer[] = []; + let stderrBytes = 0; + let archiveBytes = 0; + let overflow = false; + let writeError: Error | undefined; + let spawnError: Error | undefined; + + child.stdout.on("data", (value: Buffer | string) => { + if (overflow || writeError) return; + const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value); + archiveBytes += chunk.length; + if (archiveBytes > MAX_STATE_DIRECTORY_RESTORE_ARCHIVE_BYTES) { + overflow = true; + child.kill("SIGKILL"); + return; + } + try { + digest.update(chunk); + writeAllSync(payloadFd, chunk); + } catch (cause) { + writeError = cause instanceof Error ? cause : new Error(String(cause)); + child.kill("SIGKILL"); + } + }); + child.stderr.on("data", (value: Buffer | string) => { + if (stderrBytes >= STATE_DIRECTORY_RESTORE_TAR_DIAGNOSTIC_BYTES) return; + const chunk = Buffer.isBuffer(value) ? value : Buffer.from(value); + const retained = chunk.subarray( + 0, + STATE_DIRECTORY_RESTORE_TAR_DIAGNOSTIC_BYTES - stderrBytes, + ); + stderrChunks.push(retained); + stderrBytes += retained.length; + }); + child.once("error", (cause) => { + spawnError = cause; + }); + const timeout = setTimeout(() => child.kill("SIGKILL"), STATE_DIRECTORY_RESTORE_TAR_TIMEOUT_MS); + child.once("close", (status, signal) => { + clearTimeout(timeout); + resolve({ + status, + signal, + overflow, + stderr: Buffer.concat(stderrChunks, stderrBytes), + ...(writeError || spawnError ? { error: writeError ?? spawnError } : {}), + }); + }); + }); +} + +/** + * Build a framed restore file without retaining or concatenating the tar bytes. + * Both GNU tar and bsdtar treat a NUL `-T` list as verbatim, which keeps the + * command size constant for high-cardinality manifests. + */ +export async function createStateDirectoryRestorePayload(options: { + backupPath: string; + directories: readonly string[]; + managedExtensions: readonly ManagedExtensionRestoreRecord[]; + archiveExcludedExtensions?: readonly string[]; + remotePath: string; +}): Promise { + const encoded = encodeStateDirectoryRestoreMetadata( + options.directories, + options.managedExtensions, + ); + if (!encoded.ok) return encoded; + const encodedMetadata = encoded.metadata; + const archiveExcludedExtensions = + options.archiveExcludedExtensions ?? options.managedExtensions.map(({ name }) => name); + const archiveExclusionError = validateArchiveExcludedExtensions( + options.directories, + archiveExcludedExtensions, + ); + if (archiveExclusionError) return { ok: false, error: archiveExclusionError }; + + let tempDir: string | undefined; + let payloadFd: number | undefined; + let complete = false; + try { + tempDir = mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-restore-")); + chmodSync(tempDir, 0o700); + const payloadPath = path.join(tempDir, "payload"); + const namesPath = path.join(tempDir, "directories"); + payloadFd = openSync(payloadPath, "wx", 0o600); + const digest = createHash("sha256"); + const header = payloadHeader(encodedMetadata.length); + digest.update(header); + writeAllSync(payloadFd, header); + digest.update(encodedMetadata); + writeAllSync(payloadFd, encodedMetadata); + writeFileSync(namesPath, Buffer.from(`${options.directories.join("\0")}\0`, "utf8"), { + flag: "wx", + mode: 0o600, + }); + + const tarArgs = ["-cf", "-", "-C", options.backupPath]; + for (const extension of archiveExcludedExtensions) { + tarArgs.push("--exclude", `extensions/${extension}`); + } + tarArgs.push("--null", "-T", namesPath); + const tarResult = await streamTarArchive(tarArgs, payloadFd, digest); + if (tarResult.overflow) { + return { + ok: false, + error: `state directory restore archive exceeds ${String(MAX_STATE_DIRECTORY_RESTORE_ARCHIVE_BYTES)} bytes`, + }; + } + if (tarResult.status !== 0 || tarResult.error || tarResult.signal) { + return { + ok: false, + error: `could not archive state directories: ${tarFailureDetail(tarResult)}`, + }; + } + fsyncSync(payloadFd); + const sizeBytes = fstatSync(payloadFd).size; + closeSync(payloadFd); + payloadFd = undefined; + rmSync(namesPath, { force: true }); + + const ownedTempDir = tempDir; + let cleaned = false; + complete = true; + return { + ok: true, + payload: { + localPath: payloadPath, + remotePath: options.remotePath, + sha256: digest.digest("hex"), + sizeBytes, + cleanup: () => { + if (cleaned) return; + cleaned = true; + rmSync(ownedTempDir, { recursive: true, force: true }); + }, + }, + }; + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return { + ok: false, + error: `could not stage state directory restore: ${detail.substring(0, 200)}`, + }; + } finally { + if (payloadFd !== undefined) { + try { + closeSync(payloadFd); + } catch { + // The primary staging failure is more useful than close diagnostics. + } + } + // Successful callers own the returned cleanup. Any early return still has + // a live payload fd here or lacks a complete private payload. + if (tempDir && !complete) { + rmSync(tempDir, { recursive: true, force: true }); + } + } +} + +// This fixed program is the complete directory mutation surface. The staged +// pathname and root are the only argv values; all high-cardinality input stays +// in the bounded frame. It never calls extractall(), tar(1), chown, or chmod +// with archive special bits. +export const STATE_DIRECTORY_RESTORE_PYTHON = String.raw`import hashlib, json, os, posixpath, re, stat, struct, sys, tarfile, tempfile + +MAGIC = b"NEMOCLAW_STATE_RESTORE\x00" +VERSION = 1 +MAX_METADATA = 512 * 1024 +MAX_DIRS = 16 * 1024 +MAX_MANAGED = 256 +MAX_ARCHIVE = 256 * 1024 * 1024 +MAX_PAYLOAD = len(MAGIC) + 1 + 4 + MAX_METADATA + MAX_ARCHIVE +MAX_MEMBERS = 65536 +MAX_PATH = 4096 +CHUNK = 64 * 1024 +OPEN_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) + +def fail(message, code=20): + print(message, file=sys.stderr) + raise SystemExit(code) + +def safe_text(value, max_length=MAX_PATH): + return isinstance(value, str) and 0 < len(value) <= max_length and not any(ord(c) < 32 or ord(c) == 127 for c in value) + +def safe_relative(value): + return safe_text(value) and "\\" not in value and not posixpath.isabs(value) and posixpath.normpath(value) == value and value not in (".", "..") and not value.startswith("../") + +def safe_extension(value): + return safe_text(value, 128) and value not in (".", "..") and not any(c in value for c in "/\\*?[]") + +def read_exact(stream, size): + chunks = [] + remaining = size + while remaining: + chunk = stream.read(min(CHUNK, remaining)) + if not chunk: + fail("truncated state restore payload", 21) + chunks.append(chunk) + remaining -= len(chunk) + return b"".join(chunks) + +def open_absolute_parent(pathname): + if not safe_text(pathname) or not posixpath.isabs(pathname) or posixpath.normpath(pathname) != pathname or pathname == "/": + fail("invalid staged restore path") + parts = pathname.split("/")[1:] + parent = os.open("/", OPEN_FLAGS) + try: + for component in parts[:-1]: + child = os.open(component, OPEN_FLAGS, dir_fd=parent) + os.close(parent) + parent = child + return parent, parts[-1] + except BaseException: + os.close(parent) + raise + +def open_absolute_dir(pathname): + if not safe_text(pathname) or not posixpath.isabs(pathname) or posixpath.normpath(pathname) != pathname or pathname == "/": + fail("invalid state root") + current = os.open("/", OPEN_FLAGS) + try: + for component in pathname.split("/")[1:]: + child = os.open(component, OPEN_FLAGS, dir_fd=current) + os.close(current) + current = child + return current + except BaseException: + os.close(current) + raise + +def parse_metadata(stream): + if read_exact(stream, len(MAGIC)) != MAGIC: + fail("invalid state restore payload magic", 21) + version = read_exact(stream, 1)[0] + if version != VERSION: + fail("unsupported state restore payload version", 21) + metadata_size = struct.unpack(">I", read_exact(stream, 4))[0] + if metadata_size > MAX_METADATA: + fail("state restore metadata exceeds limit", 21) + try: + metadata = json.loads(read_exact(stream, metadata_size).decode("utf-8")) + except (UnicodeError, ValueError): + fail("invalid state restore metadata", 21) + if not isinstance(metadata, dict) or set(metadata) != {"directories", "managedExtensions"}: + fail("invalid state restore metadata shape", 21) + directories = metadata["directories"] + managed = metadata["managedExtensions"] + if not isinstance(directories, list) or not 1 <= len(directories) <= MAX_DIRS: + fail("invalid state restore directory count", 21) + if not isinstance(managed, list) or len(managed) > MAX_MANAGED: + fail("invalid managed extension count", 21) + seen = set() + for directory in directories: + if not safe_relative(directory) or directory in seen: + fail("invalid state restore directory", 21) + seen.add(directory) + for directory in directories: + parts = directory.split("/") + if any("/".join(parts[:index]) in seen for index in range(1, len(parts))): + fail("overlapping state restore directories", 21) + managed_records = [] + managed_names = set() + for record in managed: + if not isinstance(record, list) or len(record) != 2: + fail("invalid managed extension record", 21) + name, required = record + if not safe_extension(name) or type(required) is not bool or name in managed_names: + fail("invalid managed extension record", 21) + managed_names.add(name) + managed_records.append((name, required)) + if managed_records and "extensions" not in seen: + fail("managed extensions require extensions directory", 21) + return directories, managed_records + +def member_within_directories(name, directory_set): + if name in directory_set: + return True + parts = name.split("/") + return any("/".join(parts[:index]) in directory_set for index in range(1, len(parts))) + +def allowed_symlink(name, target): + if not safe_text(target) or "%" in target: + return False + if re.fullmatch(r"extensions/[A-Za-z0-9][A-Za-z0-9._-]*/node_modules/openclaw", name): + return target == "/usr/local/lib/node_modules/openclaw" + if not re.fullmatch(r"extensions/[A-Za-z0-9][A-Za-z0-9._-]*/node_modules/\.bin/[^/]+", name): + return False + if posixpath.isabs(target): + return False + bin_dir = posixpath.dirname(name) + modules_dir = posixpath.dirname(bin_dir) + resolved = posixpath.normpath(posixpath.join(bin_dir, target)) + relative = posixpath.relpath(resolved, modules_dir) + return relative not in (".", "..") and not relative.startswith("../") and not relative.startswith(".bin/") + +def canonical_member_name(member): + name = member.name + return name[:-1] if member.isdir() and name.endswith("/") else name + +def archive_record(member): + kind = "directory" if member.isdir() else "file" if member.isreg() else "symlink" if member.issym() else "unsupported" + return (canonical_member_name(member), kind, member.size, member.linkname, member.mode) + +def consume_regular_member(archive, member): + source = archive.extractfile(member) + if source is None: + fail("could not read state archive member", 22) + remaining = member.size + while remaining: + chunk = source.read(min(CHUNK, remaining)) + if not chunk: + fail("truncated state archive member", 22) + remaining -= len(chunk) + if source.read(1): + fail("oversized state archive member", 22) + +def validate_member(member, directory_set, managed_names, seen, non_directories, required_directories): + name = canonical_member_name(member) + if not safe_relative(name) or name in seen or not member_within_directories(name, directory_set): + fail("unsafe or repeated state archive member", 22) + if any(name == "extensions/" + managed or name.startswith("extensions/" + managed + "/") for managed in managed_names): + fail("state archive replaces a managed extension", 22) + record = archive_record(member) + kind = record[1] + if kind == "unsupported" or (kind == "symlink" and not allowed_symlink(name, member.linkname)): + fail("unsupported state archive member type", 22) + parts = name.split("/") + ancestors = ["/".join(parts[:index]) for index in range(1, len(parts))] + if any(ancestor in non_directories for ancestor in ancestors): + fail("state archive member has a non-directory ancestor", 22) + if kind != "directory" and name in required_directories: + fail("state archive member conflicts with an existing child", 22) + required_directories.update(ancestors) + if kind != "directory": + non_directories.add(name) + seen.add(name) + return record + +def scan_archive(stream, tar_offset, directories, managed_names): + stream.seek(tar_offset) + seen = set() + non_directories = set() + required_directories = set() + explicit_roots = set() + records = [] + count = 0 + logical_bytes = 0 + directory_set = set(directories) + try: + archive = tarfile.open(fileobj=stream, mode="r:") + try: + for member in archive: + count += 1 + if count > MAX_MEMBERS: + fail("state archive member count exceeds limit", 22) + if member.size < 0 or member.issparse() or member.type == tarfile.GNUTYPE_SPARSE or any(key.startswith("GNU.sparse") for key in member.pax_headers): + fail("sparse state archive members are unsupported", 22) + record = validate_member(member, directory_set, managed_names, seen, non_directories, required_directories) + if record[0] in directory_set: + if record[1] != "directory" or member.mode & 0o700 != 0o700: + fail("state archive root is not a usable directory", 22) + explicit_roots.add(record[0]) + if member.isreg(): + logical_bytes += member.size + if logical_bytes > MAX_ARCHIVE: + fail("state archive logical file bytes exceed limit", 22) + consume_regular_member(archive, member) + records.append(record) + finally: + archive.close() + except (tarfile.TarError, OSError) as error: + fail("invalid state archive: " + str(error), 22) + if explicit_roots != directory_set: + fail("state archive is missing an explicit directory root", 22) + return records + +def open_dir_at(parent_fd, components, create): + current = os.dup(parent_fd) + try: + for component in components: + try: + child = os.open(component, OPEN_FLAGS, dir_fd=current) + except FileNotFoundError: + if not create: + raise + os.mkdir(component, 0o700, dir_fd=current) + child = os.open(component, OPEN_FLAGS, dir_fd=current) + os.close(current) + current = child + return current + except BaseException: + os.close(current) + raise + +def remove_entry(parent_fd, name): + try: + metadata = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + return + if not stat.S_ISDIR(metadata.st_mode): + os.unlink(name, dir_fd=parent_fd) + return + child_fd = os.open(name, OPEN_FLAGS, dir_fd=parent_fd) + try: + opened = os.fstat(child_fd) + if (opened.st_dev, opened.st_ino) != (metadata.st_dev, metadata.st_ino): + fail("state directory changed during cleanup", 23) + for entry in os.scandir(child_fd): + remove_entry(child_fd, entry.name) + finally: + os.close(child_fd) + os.rmdir(name, dir_fd=parent_fd) + +def open_parent_at(root_fd, relative, create): + parts = relative.split("/") + return open_dir_at(root_fd, parts[:-1], create), parts[-1] + +def open_verified_directory(parent_fd, name, label): + try: + metadata = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + raise + if not stat.S_ISDIR(metadata.st_mode): + fail(label + " is not a directory", 23) + try: + directory_fd = os.open(name, OPEN_FLAGS, dir_fd=parent_fd) + except OSError: + fail(label + " is not a safe directory", 23) + opened = os.fstat(directory_fd) + if (opened.st_dev, opened.st_ino) != (metadata.st_dev, metadata.st_ino): + os.close(directory_fd) + fail(label + " changed while opening", 23) + if not os.access(name, os.R_OK | os.X_OK, dir_fd=parent_fd, follow_symlinks=False): + os.close(directory_fd) + fail(label + " is not usable", 23) + return directory_fd, (opened.st_dev, opened.st_ino) + +def validate_cleanup_targets(root_fd, directories, managed): + managed_names = {name for name, _required in managed} + managed_state = {"root": None, "entries": {}} + for directory in directories: + try: + parent_fd, name = open_parent_at(root_fd, directory, False) if "/" in directory else (os.dup(root_fd), directory) + except FileNotFoundError: + continue + try: + if directory == "extensions" and managed_names: + try: + extensions_fd, extensions_identity = open_verified_directory( + parent_fd, name, "managed extension root" + ) + except FileNotFoundError: + if any(required for _managed, required in managed): + fail("required managed extension root is missing", 23) + for managed_name, _required in managed: + managed_state["entries"][managed_name] = None + continue + managed_state["root"] = extensions_identity + try: + for managed_name, required in managed: + try: + managed_fd, managed_identity = open_verified_directory( + extensions_fd, + managed_name, + "managed extension " + managed_name, + ) + except FileNotFoundError: + if required: + fail("required managed extension is missing: " + managed_name, 23) + managed_state["entries"][managed_name] = None + continue + os.close(managed_fd) + managed_state["entries"][managed_name] = managed_identity + finally: + os.close(extensions_fd) + else: + try: + metadata = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + continue + if stat.S_ISLNK(metadata.st_mode): + continue + finally: + os.close(parent_fd) + return managed_state + +def clean_targets(root_fd, directories, managed, managed_state): + managed_names = {name for name, _required in managed} + for directory in directories: + try: + parent_fd, name = open_parent_at(root_fd, directory, False) if "/" in directory else (os.dup(root_fd), directory) + except FileNotFoundError: + continue + try: + if directory == "extensions" and managed_names: + created_root = False + try: + extensions_fd, actual_root = open_verified_directory( + parent_fd, name, "managed extension root" + ) + except FileNotFoundError: + os.mkdir(name, 0o700, dir_fd=parent_fd) + extensions_fd, actual_root = open_verified_directory( + parent_fd, name, "managed extension root" + ) + created_root = True + try: + expected_root = managed_state["root"] + if expected_root is None and not created_root: + fail("managed extension root appeared during restore", 23) + if expected_root is not None and actual_root != expected_root: + fail("managed extension root changed during restore", 23) + managed_state["root"] = actual_root + for entry in os.scandir(extensions_fd): + if entry.name not in managed_names: + remove_entry(extensions_fd, entry.name) + finally: + os.close(extensions_fd) + else: + remove_entry(parent_fd, name) + finally: + os.close(parent_fd) + +def verify_managed_extensions(root_fd, managed, managed_state): + if not managed: + return + extensions_fd, root_identity = open_verified_directory( + root_fd, "extensions", "managed extension root" + ) + try: + expected_root = managed_state["root"] + if expected_root is not None and root_identity != expected_root: + fail("managed extension root changed during restore", 25) + for managed_name, required in managed: + expected = managed_state["entries"].get(managed_name) + try: + managed_fd, actual = open_verified_directory( + extensions_fd, + managed_name, + "managed extension " + managed_name, + ) + except FileNotFoundError: + if required or expected is not None: + fail("managed extension disappeared during restore: " + managed_name, 25) + continue + os.close(managed_fd) + if expected is None: + fail("managed extension appeared during restore: " + managed_name, 25) + if actual != expected: + fail("managed extension changed during restore: " + managed_name, 25) + finally: + os.close(extensions_fd) + +def extract_archive(stream, tar_offset, root_fd, expected_records): + directory_modes = [] + record_index = 0 + stream.seek(tar_offset) + archive = tarfile.open(fileobj=stream, mode="r:") + try: + for member in archive: + record = archive_record(member) + if record_index >= len(expected_records) or record != expected_records[record_index]: + fail("state archive changed after validation", 24) + record_index += 1 + member_name = record[0] + parent_fd, name = open_parent_at(root_fd, member_name, True) + try: + mode = member.mode & 0o777 + if member.isdir(): + try: + os.mkdir(name, 0o700, dir_fd=parent_fd) + except FileExistsError: + pass + directory_fd = os.open(name, OPEN_FLAGS, dir_fd=parent_fd) + os.close(directory_fd) + directory_modes.append((member_name, mode)) + elif member.isreg(): + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + output_fd = os.open(name, flags, mode or 0o600, dir_fd=parent_fd) + try: + source = archive.extractfile(member) + if source is None: + fail("could not read state archive member", 24) + remaining = member.size + while remaining: + chunk = source.read(min(CHUNK, remaining)) + if not chunk: + fail("truncated state archive member", 24) + view = memoryview(chunk) + while view: + written = os.write(output_fd, view) + if written <= 0: + fail("could not write state archive member", 24) + view = view[written:] + remaining -= len(chunk) + if source.read(1): + fail("oversized state archive member", 24) + os.fchmod(output_fd, mode) + finally: + os.close(output_fd) + else: + os.symlink(member.linkname, name, dir_fd=parent_fd) + finally: + os.close(parent_fd) + finally: + archive.close() + if record_index != len(expected_records): + fail("state archive changed after validation", 24) + for relative, mode in sorted(directory_modes, key=lambda item: item[0].count("/"), reverse=True): + directory_fd = open_dir_at(root_fd, relative.split("/"), False) + try: + os.fchmod(directory_fd, mode) + finally: + os.close(directory_fd) + +def verify_directories(root_fd, directories): + for directory in directories: + directory_fd = open_dir_at(root_fd, directory.split("/"), False) + os.close(directory_fd) + parent_fd, name = open_parent_at(root_fd, directory, False) if "/" in directory else (os.dup(root_fd), directory) + try: + if not os.access(name, os.R_OK | os.W_OK, dir_fd=parent_fd, follow_symlinks=False): + fail("restored state directory is not usable: " + directory, 25) + finally: + os.close(parent_fd) + +def copy_private_payload(source_fd, expected_size): + private_stream = tempfile.TemporaryFile() + total = 0 + digest = hashlib.sha256() + try: + while True: + chunk = os.read(source_fd, CHUNK) + if not chunk: + break + total += len(chunk) + if total > MAX_PAYLOAD: + fail("staged restore payload exceeds limit") + digest.update(chunk) + private_stream.write(chunk) + if total != expected_size: + fail("staged restore payload changed while copying") + private_stream.flush() + os.fsync(private_stream.fileno()) + os.fchmod(private_stream.fileno(), 0o400) + private_stream.seek(0) + return private_stream, digest.hexdigest() + except BaseException: + private_stream.close() + raise + +if len(sys.argv) != 4: + fail("state restore requires staged path, state root, and payload digest") +remote_path, state_root, expected_digest = sys.argv[1:] +if not posixpath.basename(remote_path).startswith("nemoclaw-state-restore-"): + fail("invalid staged restore path") +if not re.fullmatch(r"[0-9a-f]{64}", expected_digest): + fail("invalid staged restore digest") +parent_fd, basename = open_absolute_parent(remote_path) +payload_fd = None +root_fd = None +stream = None +try: + before = os.stat(basename, dir_fd=parent_fd, follow_symlinks=False) + payload_fd = os.open(basename, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0), dir_fd=parent_fd) + opened = os.fstat(payload_fd) + if not stat.S_ISREG(opened.st_mode) or opened.st_nlink != 1 or opened.st_size > MAX_PAYLOAD or opened.st_uid != os.geteuid() or opened.st_gid != os.getegid() or opened.st_mode & 0o022 or (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino): + fail("unsafe staged restore file") + os.unlink(basename, dir_fd=parent_fd) + source_baseline = os.fstat(payload_fd) + stream, actual_digest = copy_private_payload(payload_fd, source_baseline.st_size) + source_after = os.fstat(payload_fd) + if source_after.st_size != source_baseline.st_size or source_after.st_mtime_ns != source_baseline.st_mtime_ns or source_after.st_ctime_ns != source_baseline.st_ctime_ns: + fail("staged restore payload changed while copying") + if actual_digest != expected_digest: + fail("staged restore payload digest mismatch") + os.close(payload_fd) + payload_fd = None + try: + directories, managed = parse_metadata(stream) + tar_offset = stream.tell() + stream.seek(0, os.SEEK_END) + archive_size = stream.tell() - tar_offset + if archive_size < 0 or archive_size > MAX_ARCHIVE: + fail("state restore archive exceeds limit", 22) + records = scan_archive(stream, tar_offset, directories, {name for name, _required in managed}) + root_fd = open_absolute_dir(state_root) + managed_state = validate_cleanup_targets(root_fd, directories, managed) + clean_targets(root_fd, directories, managed, managed_state) + extract_archive(stream, tar_offset, root_fd, records) + verify_directories(root_fd, directories) + verify_managed_extensions(root_fd, managed, managed_state) + finally: + stream.close() + stream = None +finally: + if stream is not None: + stream.close() + if root_fd is not None: + os.close(root_fd) + if payload_fd is not None: + os.close(payload_fd) + os.close(parent_fd) +print("RESTORE_OK") +`; diff --git a/src/lib/state/sandbox-restore-upload.test.ts b/src/lib/state/sandbox-restore-upload.test.ts new file mode 100644 index 00000000000..7f8ba05ef8e --- /dev/null +++ b/src/lib/state/sandbox-restore-upload.test.ts @@ -0,0 +1,359 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ + close: vi.fn(), + exec: vi.fn(), + getSandbox: vi.fn(), + loadAgent: vi.fn(), + select: vi.fn(), + upload: vi.fn(), +})); + +vi.mock("../adapters/openshell/sandbox-control-routing.js", async (importOriginal) => ({ + ...(await importOriginal()), + selectOpenShellSandboxControlForMutation: mocks.select, +})); + +vi.mock("../adapters/openshell/sandbox-upload.js", async (importOriginal) => ({ + ...(await importOriginal()), + uploadSandboxPayloadFile: mocks.upload, +})); + +vi.mock("../agent/defs.js", async (importOriginal) => ({ + ...(await importOriginal()), + loadAgent: mocks.loadAgent, +})); + +vi.mock("./registry.js", async (importOriginal) => ({ + ...(await importOriginal()), + getSandbox: mocks.getSandbox, +})); + +import { + SANDBOX_PAYLOAD_CLEANUP_OK, + SANDBOX_PAYLOAD_CLEANUP_PYTHON, +} from "../adapters/openshell/sandbox-upload.js"; +import { restoreRecreatedSandboxState } from "./sandbox.js"; +import { STATE_DIRECTORY_RESTORE_PYTHON } from "./sandbox-restore-payload.js"; + +const fixtures: string[] = []; +const STATE_ROOT = "/sandbox/.fixture"; + +function completed() { + return { status: 0, stdout: "RESTORE_OK\n", stderr: "" }; +} + +function cleanupCompleted() { + return { status: 0, stdout: `${SANDBOX_PAYLOAD_CLEANUP_OK}\n`, stderr: "" }; +} + +function restoreExecCalls() { + return mocks.exec.mock.calls.filter( + ([request]) => request.stdin === STATE_DIRECTORY_RESTORE_PYTHON, + ); +} + +function cleanupExecCalls() { + return mocks.exec.mock.calls.filter( + ([request]) => request.stdin === SANDBOX_PAYLOAD_CLEANUP_PYTHON, + ); +} + +function writeDirectoryBackup( + withStateFile = false, + stateDirs: string[] = ["workspace"], + materializeDirectories = true, + manifestDir = STATE_ROOT, +): string { + const backupPath = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-restore-upload-")); + fixtures.push(backupPath); + for (const stateDir of materializeDirectories ? stateDirs : []) { + fs.mkdirSync(path.join(backupPath, stateDir)); + fs.writeFileSync(path.join(backupPath, stateDir, "large.bin"), Buffer.alloc(1024 * 1024 + 7)); + } + fs.writeFileSync(path.join(backupPath, "config.json"), "{}\n"); + fs.writeFileSync( + path.join(backupPath, "rebuild-manifest.json"), + JSON.stringify({ + version: 1, + sandboxName: "alpha", + timestamp: "2026-07-14T00:00:00.000Z", + agentType: "fixture", + agentVersion: null, + expectedVersion: null, + stateDirs, + backedUpDirs: stateDirs, + stateFiles: withStateFile ? [{ path: "config.json", strategy: "copy" }] : [], + dir: manifestDir, + backupPath, + blueprintDigest: null, + }), + ); + return backupPath; +} + +beforeEach(() => { + vi.clearAllMocks(); + mocks.getSandbox.mockReturnValue({ + name: "alpha", + agent: "fixture", + gatewayName: "nemoclaw-18080", + }); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_ROOT }, + stateDirs: ["workspace"], + stateFiles: [], + }); + mocks.select.mockReturnValue({ + control: { exec: mocks.exec }, + transport: "grpc", + close: mocks.close, + }); + mocks.exec.mockImplementation(async (request) => + request.stdin === SANDBOX_PAYLOAD_CLEANUP_PYTHON ? cleanupCompleted() : completed(), + ); + mocks.upload.mockImplementation( + (_gateway: string, _sandbox: string, _local: string, remotePath: string) => ({ + ok: true, + remotePath, + }), + ); +}); + +afterEach(() => { + delete process.env.OPENSHELL_GATEWAY_ENDPOINT; + for (const fixture of fixtures.splice(0)) fs.rmSync(fixture, { recursive: true, force: true }); +}); + +describe("state directory restore transport boundary", () => { + it("uploads once to the registry gateway and dispatches one canonical fixed-program mutation", async () => { + const backupPath = writeDirectoryBackup(); + let stagedPath = ""; + mocks.upload.mockImplementation( + (gateway: string, sandbox: string, localPath: string, remotePath: string) => { + stagedPath = localPath; + expect(gateway).toBe("nemoclaw-18080"); + expect(sandbox).toBe("alpha"); + expect(fs.statSync(localPath).size).toBeGreaterThan(1024 * 1024); + return { ok: true, remotePath }; + }, + ); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + }); + + expect(result).toEqual({ + success: true, + restoredDirs: ["workspace"], + failedDirs: [], + restoredFiles: [], + failedFiles: [], + }); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(mocks.exec).toHaveBeenCalledOnce(); + const request = mocks.exec.mock.calls[0][0]; + expect(request).toMatchObject({ + sandboxName: "alpha", + command: [ + "python3", + "-I", + "-", + expect.stringMatching(/^\/tmp\/nemoclaw-state-restore-/), + STATE_ROOT, + expect.stringMatching(/^[0-9a-f]{64}$/), + ], + stdin: STATE_DIRECTORY_RESTORE_PYTHON, + timeoutMs: 120_000, + maxOutputBytes: 64 * 1024, + }); + expect(fs.existsSync(stagedPath)).toBe(false); + expect(mocks.close).toHaveBeenCalledOnce(); + }); + + it("uses an explicit non-default gateway before an unregistered recreated sandbox is published", async () => { + const backupPath = writeDirectoryBackup(); + mocks.getSandbox.mockReturnValue(undefined); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + gatewayName: "nemoclaw-18080", + }); + + expect(result).toMatchObject({ success: true, restoredDirs: ["workspace"] }); + expect(mocks.upload).toHaveBeenCalledWith( + "nemoclaw-18080", + "alpha", + expect.any(String), + expect.stringMatching(/^\/tmp\/nemoclaw-state-restore-/), + ); + expect(mocks.exec).toHaveBeenCalledOnce(); + expect(mocks.select).toHaveBeenCalledWith("nemoclaw-18080"); + }); + + it("canonicalizes a legacy trailing-slash manifest root before mutation", async () => { + const backupPath = writeDirectoryBackup(false, ["workspace"], true, `${STATE_ROOT}/`); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + gatewayName: "nemoclaw-18080", + }); + + expect(result).toMatchObject({ success: true, restoredDirs: ["workspace"] }); + expect(restoreExecCalls()).toHaveLength(1); + expect(restoreExecCalls()[0]?.[0].command[4]).toBe(STATE_ROOT); + }); + + it("accepts a discovered top-level workspace directory outside target declarations", async () => { + const backupPath = writeDirectoryBackup(false, ["workspace-.legacy", "workspace-_legacy"]); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + gatewayName: "nemoclaw-18080", + }); + + expect(result).toMatchObject({ + success: true, + restoredDirs: ["workspace-.legacy", "workspace-_legacy"], + }); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(mocks.exec).toHaveBeenCalledOnce(); + }); + + it("rejects an undeclared directory before gateway selection or upload", async () => { + const backupPath = writeDirectoryBackup(false, ["secrets"]); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + gatewayName: "nemoclaw-18080", + }); + + expect(result).toMatchObject({ success: false, failedDirs: ["secrets"] }); + expect(result.error).toContain("is not declared by target agent"); + expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.upload).not.toHaveBeenCalled(); + expect(mocks.exec).not.toHaveBeenCalled(); + }); + + it.each([ + "workspace-", + "prefix-workspace-agent", + "nested/workspace-agent", + "workspace-agent/nested", + "../workspace-agent", + "workspace-agent\nextra", + "workspace-agent\\extra", + `workspace-${"x".repeat(246)}`, + ])("rejects non-canonical discovered workspace path %j", async (stateDir) => { + const backupPath = writeDirectoryBackup(false, [stateDir], false); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + gatewayName: "nemoclaw-18080", + }); + + expect(result.success).toBe(false); + expect(mocks.select).not.toHaveBeenCalled(); + expect(mocks.upload).not.toHaveBeenCalled(); + expect(mocks.exec).not.toHaveBeenCalled(); + }); + + it("does not dispatch after upload failure", async () => { + const backupPath = writeDirectoryBackup(); + mocks.upload.mockReturnValue({ + ok: false, + error: "gateway unavailable", + remotePath: "/tmp/nemoclaw-state-restore-failed", + }); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + }); + + expect(result).toMatchObject({ success: false, failedDirs: ["workspace"] }); + expect(result.error).toContain("upload failed"); + expect(restoreExecCalls()).toHaveLength(0); + expect(cleanupExecCalls()).toHaveLength(1); + expect(mocks.close).toHaveBeenCalledOnce(); + }); + + it.each([ + ["error result", { status: null, stdout: "", stderr: "", error: new Error("unknown") }], + ["signal result", { status: null, stdout: "", stderr: "", signal: "SIGTERM" }], + ])("never replays an indeterminate %s", async (_label, outcome) => { + const backupPath = writeDirectoryBackup(); + mocks.exec.mockResolvedValue(outcome); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + }); + + expect(result).toMatchObject({ success: false, failedDirs: ["workspace"] }); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(restoreExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(1); + expect(mocks.close).toHaveBeenCalledOnce(); + }); + + it("never replays when the selected transport throws after dispatch", async () => { + const backupPath = writeDirectoryBackup(); + mocks.exec.mockRejectedValue(new Error("dispatch outcome unknown")); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + }); + + expect(result).toMatchObject({ success: false, failedDirs: ["workspace"] }); + expect(result.error).toContain("dispatch failed"); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(restoreExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(1); + }); + + it.each([ + 1, 20, 21, 22, 23, + ])("does not begin state-file mutations after indeterminate directory status %s", async (status) => { + const backupPath = writeDirectoryBackup(true); + mocks.loadAgent.mockReturnValue({ + configPaths: { dir: STATE_ROOT }, + stateDirs: ["workspace"], + stateFiles: [{ path: "config.json", strategy: "copy" }], + }); + mocks.exec.mockResolvedValue({ status, stdout: "", stderr: "directory restore failed" }); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + }); + + expect(result).toMatchObject({ + success: false, + failedDirs: ["workspace"], + failedFiles: ["config.json"], + }); + expect(restoreExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(1); + expect(mocks.upload).toHaveBeenCalledOnce(); + }); + + it("fails before upload or selection when the registry binding is invalid", async () => { + const backupPath = writeDirectoryBackup(); + mocks.getSandbox.mockReturnValue({ name: "alpha", agent: "fixture", gatewayName: "foreign" }); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + }); + + expect(result).toMatchObject({ success: false, failedDirs: ["workspace"] }); + expect(result.error).toContain("Invalid persisted sandbox gateway binding"); + expect(mocks.upload).not.toHaveBeenCalled(); + expect(mocks.exec).not.toHaveBeenCalled(); + expect(mocks.close).not.toHaveBeenCalled(); + }); +}); diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index dfdca9e1848..7e32192dd00 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -25,15 +25,20 @@ import os from "node:os"; import path from "node:path"; 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 { + execSandboxReadOnlyWithGrpcFallback, + selectOpenShellSandboxControlForMutation, +} from "../adapters/openshell/sandbox-control-routing.js"; +import { + cleanupSandboxPayloadAfterFailure, + createSandboxPayloadRemotePath, + uploadSandboxPayloadFile, +} from "../adapters/openshell/sandbox-upload.js"; import type { AgentStateFile } from "../agent/defs.js"; import { loadAgent } from "../agent/defs.js"; import { isObjectRecord, type UnknownRecord } from "../core/json-types.js"; @@ -42,14 +47,10 @@ import { classifyFailedDirsFromTarStderr, } from "../domain/backup-failure.js"; import { resolveSandboxGatewayName } from "../onboard/gateway-binding.js"; +import { assertNoOpenShellGatewayEndpointOverride } from "../openshell-gateway-endpoint-guard.js"; import { shellQuote } from "../runner.js"; -import { createTempSshConfig } from "../sandbox/temp-ssh-config.js"; import { isSensitiveFile, sanitizeConfigFile } from "../security/credential-filter.js"; -import { - buildRestoreCleanupCommand, - buildRestoreTarArgs, - isAllowedStateSymlink, -} from "./openclaw-managed-extensions.js"; +import { isAllowedStateSymlink } from "./openclaw-managed-extensions.js"; import { discoverFreshOpenClawImagePluginInstalls, hasCompleteOpenClawImagePluginProvenance, @@ -59,6 +60,10 @@ import { } from "./openclaw-plugin-restore.js"; import type { CustomPolicyEntry } from "./registry.js"; import * as registry from "./registry.js"; +import { + createStateDirectoryRestorePayload, + STATE_DIRECTORY_RESTORE_PYTHON, +} from "./sandbox-restore-payload.js"; import { restoreStateFile } from "./state-file-restore.js"; import { runTarListing } from "./tar-listing.js"; @@ -180,6 +185,8 @@ export interface RecreatedSandboxRestoreOptions { allowCustomImageWholeStateFileRestore?: true; /** Pre-captured baseline avoids a second remote read during onboarding finalization. */ freshOpenClawImagePluginInstalls?: readonly OpenClawImagePluginInstall[]; + /** Explicit binding for a newly created sandbox not yet in the local registry. */ + gatewayName?: string; } interface InternalRestoreOptions { @@ -187,6 +194,7 @@ interface InternalRestoreOptions { allowCustomImageWholeStateFileRestore?: true; discoverFreshOpenClawImagePluginInstalls?: true; freshOpenClawImagePluginInstalls?: readonly OpenClawImagePluginInstall[]; + gatewayName?: string; } export interface TarValidationResult { @@ -556,34 +564,6 @@ export function safeTarExtract(tarBuffer: Buffer, targetDir: string): SafeExtrac // ── Helpers ──────────────────────────────────────────────────────── -export function getSshConfig(sandboxName: string): string | null { - const openshellBinary = resolveOpenshell(); - if (!openshellBinary) return null; - - const result = captureSandboxSshConfigCommand(openshellBinary, sandboxName, { - ignoreError: true, - timeout: OPENSHELL_PROBE_TIMEOUT_MS, - }); - if (result.status !== 0) return null; - return result.output; -} - -export function sshArgs(configFile: string, sandboxName: string): string[] { - return [ - "-F", - configFile, - "-o", - "StrictHostKeyChecking=no", - "-o", - "UserKnownHostsFile=/dev/null", - "-o", - "ConnectTimeout=10", - "-o", - "LogLevel=ERROR", - `openshell-${sandboxName}`, - ]; -} - function computeBlueprintDigest(): string | null { // Look for blueprint.yaml relative to the agent-defs ROOT const candidates = [ @@ -693,6 +673,12 @@ function isSafeStateDirPath(dirPath: string): boolean { ); } +const DISCOVERED_WORKSPACE_STATE_DIR_RE = /^workspace-[A-Za-z0-9._-]{1,245}$/; + +function isDiscoveredWorkspaceStateDir(dirPath: string): boolean { + return DISCOVERED_WORKSPACE_STATE_DIR_RE.test(dirPath); +} + export type SandboxDirectoryNameListResult = | { ok: true; names: string[]; input: Buffer } | { ok: false; error: string }; @@ -1160,7 +1146,6 @@ async function backupStateFile( */ export { isSshTransportFailure } from "./ssh-transport.js"; -export { buildStateFileRestoreCommand } from "./state-file-restore.js"; export async function backupSandboxState( sandboxName: string, @@ -1630,7 +1615,7 @@ export async function backupSandboxState( // and append newly-discovered workspace-* names that weren't already in // stateDirs. See issue #1260. const discoveredWorkspaces = backedUpDirs.filter( - (d) => d.startsWith("workspace-") && !stateDirs.includes(d), + (d) => isDiscoveredWorkspaceStateDir(d) && !stateDirs.includes(d), ); if (discoveredWorkspaces.length > 0) { manifest.stateDirs = [...stateDirs, ...discoveredWorkspaces]; @@ -1660,7 +1645,10 @@ export async function backupSandboxState( /** * Restore state directories into a sandbox from a prior backup. */ -export function restoreSandboxState(sandboxName: string, backupPath: string): RestoreResult { +export async function restoreSandboxState( + sandboxName: string, + backupPath: string, +): Promise { const target = registry.getSandbox(sandboxName); if (!target) { return { @@ -1678,11 +1666,11 @@ export function restoreSandboxState(sandboxName: string, backupPath: string): Re }); } -export function restoreRecreatedSandboxState( +export async function restoreRecreatedSandboxState( sandboxName: string, backupPath: string, options: RecreatedSandboxRestoreOptions, -): RestoreResult { +): Promise { return restoreSandboxStateInternal(sandboxName, backupPath, { targetAgentType: options.targetAgentType, ...(options.allowCustomImageWholeStateFileRestore @@ -1693,14 +1681,15 @@ export function restoreRecreatedSandboxState( ? { discoverFreshOpenClawImagePluginInstalls: true } : {}), freshOpenClawImagePluginInstalls: options.freshOpenClawImagePluginInstalls, + gatewayName: options.gatewayName, }); } -function restoreSandboxStateInternal( +async function restoreSandboxStateInternal( sandboxName: string, backupPath: string, options: InternalRestoreOptions, -): RestoreResult { +): Promise { _log(`restoreSandboxState: sandbox=${sandboxName}, backupPath=${backupPath}`); const manifest = readManifest(backupPath); if (!manifest) { @@ -1779,6 +1768,33 @@ function restoreSandboxStateInternal( `Backup state directory '${normalizedBackupDir}' does not match target directory '${normalizedTargetDir}'`, ); } + const canonicalTargetDir = normalizedTargetDir; + const targetStateDirs = new Set(); + for (const targetDir of targetAgent.stateDirs) { + if (!isSafeStateDirPath(targetDir) || targetStateDirs.has(targetDir)) { + return failRestoreContract( + `Target agent manifest '${options.targetAgentType}' has an invalid or duplicate state directory declaration`, + ); + } + targetStateDirs.add(targetDir); + } + for (const [label, backupDirs] of [ + ["state directory", manifest.stateDirs], + ["backed-up state directory", manifest.backedUpDirs ?? []], + ] as const) { + const seenBackupDirs = new Set(); + for (const backupDir of backupDirs) { + if (seenBackupDirs.has(backupDir)) { + return failRestoreContract(`Backup manifest repeats ${label} '${backupDir}'`); + } + seenBackupDirs.add(backupDir); + if (!targetStateDirs.has(backupDir) && !isDiscoveredWorkspaceStateDir(backupDir)) { + return failRestoreContract( + `Backup state directory '${backupDir}' is not declared by target agent '${options.targetAgentType}'`, + ); + } + } + } const targetStateFiles = new Map(); for (const targetFile of targetAgent.stateFiles) { const normalized = normalizeStateFilePath(targetFile.path); @@ -1808,11 +1824,28 @@ function restoreSandboxStateInternal( } } + let gatewayName: string; + try { + const target = + options.gatewayName !== undefined + ? { gatewayName: options.gatewayName } + : registry.getSandbox(sandboxName); + if (!target) { + return failRestoreContract( + `Could not resolve target sandbox '${sandboxName}' gateway for state restore`, + ); + } + gatewayName = resolveSandboxGatewayName(target); + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return failRestoreContract(`Could not resolve sandbox gateway: ${detail}`); + } + let freshOpenClawImagePluginInstalls: readonly OpenClawImagePluginInstall[] | undefined; if (options.freshOpenClawImagePluginInstalls !== undefined) { const parsed = parseOpenClawImagePluginInstalls( options.freshOpenClawImagePluginInstalls, - targetAgent.configPaths.dir, + canonicalTargetDir, ); if (!parsed.ok) { return { @@ -1823,10 +1856,10 @@ function restoreSandboxStateInternal( } freshOpenClawImagePluginInstalls = parsed.pluginInstalls; } else if (options.discoverFreshOpenClawImagePluginInstalls === true) { - const discovery = discoverFreshOpenClawImagePluginInstalls( + const discovery = await discoverFreshOpenClawImagePluginInstalls( sandboxName, - { getSshConfig, sshArgs }, - targetAgent.configPaths.dir, + gatewayName, + canonicalTargetDir, ); if (!discovery.ok) { return { @@ -1843,21 +1876,6 @@ function restoreSandboxStateInternal( return { success: true, restoredDirs, failedDirs, restoredFiles, failedFiles }; } - _log("Getting SSH config for restore"); - const sshConfig = getSshConfig(sandboxName); - if (!sshConfig) { - _log("FAILED: Could not get SSH config for restore"); - return { - success: false, - restoredDirs, - failedDirs: [...localDirs], - restoredFiles, - failedFiles: localFiles.map((f) => f.path), - }; - } - - const tempSshConfig = createTempSshConfig(sshConfig, "nemoclaw-state-"); - const configFile = tempSshConfig.file; const previousOpenClawImagePluginInstalls = freshOpenClawImagePluginInstalls !== undefined ? manifest.openclawImagePluginInstalls @@ -1871,153 +1889,138 @@ function restoreSandboxStateInternal( previousOpenClawImagePluginInstalls !== undefined ? freshOpenClawImagePluginInstalls : undefined; - try { - const pluginRestorePlan = planOpenClawPluginRestore({ - agentType: manifest.agentType, - dir, - localDirs, - freshImagePluginInstalls: freshOpenClawImagePluginInstalls, - previousImagePluginInstalls: previousOpenClawImagePluginInstalls, - }); - if (!pluginRestorePlan.ok) { - return { - success: false, - restoredDirs, - failedDirs: [...localDirs], - restoredFiles, - failedFiles: localFiles.map((f) => f.path), - error: - manifest.reconcileOpenClawImagePluginProvenance === true - ? OPENCLAW_IMAGE_PLUGIN_PROVENANCE_RESTORE_ERROR - : pluginRestorePlan.error, - }; - } - if ( - freshOpenClawImagePluginInstalls !== undefined && - pluginRestorePlan.preservedExtensionDirs.length > 0 - ) { - _log( - `Fresh image-managed OpenClaw extensions: [${pluginRestorePlan.freshExtensionDirs.join(",")}]`, - ); - _log( - `Previous image-managed OpenClaw extensions: [${pluginRestorePlan.previousExtensionDirs.join(",")}]`, - ); - } + const pluginRestorePlan = planOpenClawPluginRestore({ + agentType: manifest.agentType, + dir: canonicalTargetDir, + localDirs, + freshImagePluginInstalls: freshOpenClawImagePluginInstalls, + previousImagePluginInstalls: previousOpenClawImagePluginInstalls, + }); + if (!pluginRestorePlan.ok) { + return { + success: false, + restoredDirs, + failedDirs: [...localDirs], + restoredFiles, + failedFiles: localFiles.map((f) => f.path), + error: + manifest.reconcileOpenClawImagePluginProvenance === true + ? OPENCLAW_IMAGE_PLUGIN_PROVENANCE_RESTORE_ERROR + : pluginRestorePlan.error, + }; + } + if ( + freshOpenClawImagePluginInstalls !== undefined && + pluginRestorePlan.preservedExtensionDirs.length > 0 + ) { + _log( + `Fresh image-managed OpenClaw extensions: [${pluginRestorePlan.freshExtensionDirs.join(",")}]`, + ); + _log( + `Previous image-managed OpenClaw extensions: [${pluginRestorePlan.previousExtensionDirs.join(",")}]`, + ); + } + let mutation; + try { + assertNoOpenShellGatewayEndpointOverride(); + mutation = selectOpenShellSandboxControlForMutation(gatewayName); + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return failRestoreContract(`Could not select sandbox restore transport: ${detail}`); + } + try { if (localDirs.length > 0) { - // Upload via tar pipe - // NC-2227-04: Removed -h flag from restore as well — no symlink following. - const tarResult = spawnSync( - "tar", - buildRestoreTarArgs(backupPath, localDirs, pluginRestorePlan.archiveExcludedExtensionDirs), - { - stdio: ["ignore", "pipe", "pipe"], - timeout: 60000, - maxBuffer: 256 * 1024 * 1024, - }, - ); - - if (tarResult.status !== 0 || !tarResult.stdout) { - return { - success: false, - restoredDirs, - failedDirs: [...localDirs], - restoredFiles, - failedFiles: localFiles.map((f) => f.path), - }; - } - - // Remove existing state dirs before extracting so stale files from later - // snapshots don't persist after restoring an earlier one. OpenClaw's - // image-managed extensions are preserved from the freshly built image and - // excluded from the restore tar; only user/non-managed extension entries - // are cleared and restored from the backup. - const rmCmd = buildRestoreCleanupCommand( - dir, - localDirs, - pluginRestorePlan.preservedExtensionDirs, - new Set(pluginRestorePlan.requiredFreshExtensionDirs), - ); - _log(`Cleaning target dirs before restore: ${rmCmd}`); - const rmResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), rmCmd], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, + const remotePath = createSandboxPayloadRemotePath(); + const requiredExtensions = new Set(pluginRestorePlan.requiredFreshExtensionDirs); + const staged = await createStateDirectoryRestorePayload({ + backupPath, + directories: localDirs, + archiveExcludedExtensions: pluginRestorePlan.archiveExcludedExtensionDirs, + managedExtensions: pluginRestorePlan.preservedExtensionDirs.map((name) => ({ + name, + required: requiredExtensions.has(name), + })), + remotePath, }); - if (rmResult.status !== 0 || rmResult.error || rmResult.signal) { - const stderr = (rmResult.stderr?.toString() || "").trim(); - const detail = - stderr || - rmResult.error?.message || - (rmResult.signal ? `signal ${rmResult.signal}` : `exit ${String(rmResult.status)}`); - _log(`FAILED: pre-restore cleanup failed: ${detail.substring(0, 200)}`); - return { - success: false, - restoredDirs, - failedDirs: [...localDirs], - restoredFiles, - failedFiles: localFiles.map((f) => f.path), - }; + if (!staged.ok) return failRestoreContract(staged.error); + const request: SandboxExecRequest = { + sandboxName, + command: ["python3", "-I", "-", remotePath, canonicalTargetDir, staged.payload.sha256], + stdin: STATE_DIRECTORY_RESTORE_PYTHON, + timeoutMs: 120_000, + maxOutputBytes: 64 * 1024, + }; + const validationError = validateOpenShellExecRequest(request); + if (validationError) { + staged.payload.cleanup(); + return failRestoreContract( + `state directory restore request failed validation: ${validationError.message}`, + ); } - const extractCmd = `tar --no-same-owner -xf - -C ${shellQuote(dir)}`; - const sshResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), extractCmd], { - input: tarResult.stdout, - stdio: ["pipe", "pipe", "pipe"], - timeout: 120000, - }); - - if (sshResult.status === 0) { - const restoredPaths = localDirs.map((d) => `${dir}/${d}`); - - // Best-effort only: OpenShell exec/SSH normally runs as the sandbox user, - // which cannot chown even files it owns. The tar restore above runs as the - // same user, so the real restore gate is whether the restored state dirs - // are usable by that user. - const chownCmd = `chown -R sandbox:sandbox -- ${restoredPaths.map(shellQuote).join(" ")} 2>/dev/null || true`; - _log(`Best-effort ownership repair: ${chownCmd}`); - const chownResult = spawnSync("ssh", [...sshArgs(configFile, sandboxName), chownCmd], { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - }); - if (chownResult.error || chownResult.signal) { - const detail = - chownResult.error?.message || - (chownResult.signal ? `signal ${chownResult.signal}` : "unknown error"); - _log( - `WARNING: post-restore ownership repair did not complete: ${detail.substring(0, 200)}`, - ); - } - - const usabilityCmd = restoredPaths - .map( - (p) => - `[ -d ${shellQuote(p)} ] && [ ! -L ${shellQuote(p)} ] && [ -r ${shellQuote(p)} ] && [ -w ${shellQuote(p)} ]`, - ) - .join(" && "); - _log(`Verifying restored state usability: ${usabilityCmd}`); - const usabilityResult = spawnSync( - "ssh", - [...sshArgs(configFile, sandboxName), usabilityCmd], - { - stdio: ["ignore", "pipe", "pipe"], - timeout: 30000, - }, + let upload; + try { + upload = uploadSandboxPayloadFile( + gatewayName, + sandboxName, + staged.payload.localPath, + staged.payload.remotePath, ); - if (usabilityResult.status === 0 && !usabilityResult.error && !usabilityResult.signal) { - restoredDirs.push(...localDirs); - } else { - const stderr = (usabilityResult.stderr?.toString() || "").trim(); - const detail = - stderr || - usabilityResult.error?.message || - (usabilityResult.signal - ? `signal ${usabilityResult.signal}` - : `exit ${String(usabilityResult.status)}`); - _log(`FAILED: restored state usability check failed: ${detail.substring(0, 200)}`); - failedDirs.push(...localDirs); + } finally { + staged.payload.cleanup(); + } + const cleanupRemotePayload = async (): Promise => { + if (!(await cleanupSandboxPayloadAfterFailure(mutation.control, sandboxName, remotePath))) { + _log(`WARNING: could not confirm cleanup of staged restore payload ${remotePath}`); } + }; + if (!upload.ok) { + await cleanupRemotePayload(); + return failRestoreContract(`state directory restore upload failed: ${upload.error}`); + } + + let restoreResult: SandboxExecResult; + try { + restoreResult = await mutation.control.exec(request); + } catch (cause) { + await cleanupRemotePayload(); + const detail = cause instanceof Error ? cause.message : String(cause); + return failRestoreContract(`state directory restore dispatch failed: ${detail}`); + } + if ( + restoreResult.status === 0 && + !restoreResult.error && + !restoreResult.signal && + restoreResult.stdout.trim() === "RESTORE_OK" + ) { + restoredDirs.push(...localDirs); } else { + await cleanupRemotePayload(); failedDirs.push(...localDirs); + const detail = + restoreResult.stderr.trim() || + restoreResult.error?.message || + (restoreResult.signal + ? `signal ${restoreResult.signal}` + : `exit ${String(restoreResult.status)}`); + _log(`FAILED: state directory restore: ${detail.substring(0, 200)}`); + // Only explicit extraction/usability failures have a determinate + // directory mutation outcome that permits independent file writes. + if ( + (restoreResult.status !== 24 && restoreResult.status !== 25) || + restoreResult.status === null || + restoreResult.error || + restoreResult.signal + ) { + return { + success: false, + restoredDirs, + failedDirs, + restoredFiles, + failedFiles: localFiles.map((file) => file.path), + }; + } } } @@ -2025,9 +2028,10 @@ function restoreSandboxStateInternal( const targetStateFile = targetStateFiles.get(spec.path); if (!targetStateFile) throw new Error(`Validated target state file missing: ${spec.path}`); if ( - restoreStateFile( - sshArgs(configFile, sandboxName), - dir, + await restoreStateFile( + mutation.control, + sandboxName, + canonicalTargetDir, spec, backupPath, targetStateFile.restore, @@ -2035,6 +2039,7 @@ function restoreSandboxStateInternal( _log, configFreshOpenClawImagePluginInstalls, previousOpenClawImagePluginInstalls, + gatewayName, ) ) { restoredFiles.push(spec.path); @@ -2043,11 +2048,7 @@ function restoreSandboxStateInternal( } } } finally { - try { - tempSshConfig.cleanup(); - } catch { - /* ignore */ - } + mutation.close(); } return { diff --git a/src/lib/state/state-file-key-merge-file-safety.test.ts b/src/lib/state/state-file-key-merge-file-safety.test.ts index b5bd166821c..c2920f86845 100644 --- a/src/lib/state/state-file-key-merge-file-safety.test.ts +++ b/src/lib/state/state-file-key-merge-file-safety.test.ts @@ -4,10 +4,7 @@ import { stringify } from "smol-toml"; import { describe, expect, it } from "vitest"; -import { - buildKeyAllowlistMergeRestoreCommand, - KEY_ALLOWLIST_MERGE_PYTHON, -} from "./state-file-key-merge"; +import { KEY_ALLOWLIST_MERGE_PYTHON } from "./state-file-key-merge"; import { DCODE_OWNERSHIP, generatedCurrent, @@ -21,7 +18,7 @@ import { } from "./state-file-key-merge-test-fixture"; describe("key-allowlist state-file merge", () => { - it("executes the full production command with backup TOML only on stdin", () => { + it("executes the fixed merge program with a staged payload and digest", () => { const backup = stringify({ ui: { show_scrollbar: true } }); const current = generatedCurrent({ models: { default: "openai:nvidia/new-model" }, @@ -74,6 +71,22 @@ describe("key-allowlist state-file merge", () => { expect(result.current).toBe(current); }); + it.each([ + ["group-writable stage", { stagedMode: 0o620 }], + ["digest mismatch", { stagedDigest: "0".repeat(64) }], + ])("rejects a %s before changing the current config", (_label, options) => { + const backup = stringify({ ui: { show_scrollbar: true } }); + const current = generatedCurrent({ + models: { default: "openai:nvidia/new-model" }, + update: { check: false, auto_update: false }, + }); + + const result = runProductionCommand(backup, current, options); + + expect(result.status).not.toBe(0); + expect(result.current).toBe(current); + }); + it("rejects symlink, hardlink, and inode swaps of its private stage before replacement", () => { const backup = stringify({ ui: { show_scrollbar: true } }); const current = generatedCurrent({ @@ -134,28 +147,9 @@ describe("key-allowlist state-file merge", () => { expect(result.stageEntries).toEqual([]); }); - it("builds a same-directory staged atomic restore command for any config dir", () => { - const command = buildKeyAllowlistMergeRestoreCommand( - "/sandbox/.deepagents/", - { path: "config.toml" }, - DCODE_OWNERSHIP, - ); - - expect(command).toContain("/opt/venv/bin/python3 -I -c"); - expect(command).toContain('"$dst"'); - expect(command).not.toContain("mktemp"); - expect(command).not.toContain('chmod 600 "$'); - expect(command).toContain("/sandbox/.deepagents/config.toml"); - expect(command).toContain("show_scrollbar"); + it("keeps the atomic replacement primitive in the fixed merge program", () => { expect(KEY_ALLOWLIST_MERGE_PYTHON).toContain( "os.replace(staged_name, current_name, src_dir_fd=parent_fd, dst_dir_fd=parent_fd)", ); - - const custom = buildKeyAllowlistMergeRestoreCommand( - "/sandbox/.custom", - { path: "config.toml" }, - DCODE_OWNERSHIP, - ); - expect(custom).toContain("/sandbox/.custom/config.toml"); }); }); diff --git a/src/lib/state/state-file-key-merge-test-fixture.ts b/src/lib/state/state-file-key-merge-test-fixture.ts index cc87ff5604a..57ed77ff56e 100644 --- a/src/lib/state/state-file-key-merge-test-fixture.ts +++ b/src/lib/state/state-file-key-merge-test-fixture.ts @@ -2,17 +2,13 @@ // SPDX-License-Identifier: Apache-2.0 import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { parse, stringify } from "smol-toml"; import { loadAgent, type StateFileKeyAllowlistRestoreOwnership } from "../agent/defs"; -import { shellQuote } from "../runner"; -import { - buildKeyAllowlistMergeRestoreCommand, - KEY_ALLOWLIST_MERGE_PYTHON, - stateFileKeyMergeSpec, -} from "./state-file-key-merge"; +import { KEY_ALLOWLIST_MERGE_PYTHON, stateFileKeyMergeSpec } from "./state-file-key-merge"; export const GENERATED_HEADER = "# Generated by NemoClaw. This file contains no provider secrets."; export const FRESH_PROVIDER_HEADER = @@ -55,6 +51,10 @@ exec(script, {"__name__": "__main__"}) `.trim(); export const INODE_SWAP_MARKER = "# replacement created during race test\n"; + +function sha256(value: string): string { + return createHash("sha256").update(value).digest("hex"); +} function failInstrumentation(label: string): never { throw new Error(`Could not instrument the ${label}`); } @@ -186,10 +186,14 @@ export function runMergeScript( stageEntries: string[]; swappedOriginal: string | null; } { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-file-key-merge-")); + const dir = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-file-key-merge-")), + ); try { const currentPath = path.join(dir, "config.toml"); + const stagedPath = path.join(dir, "nemoclaw-state-restore-backup"); fs.writeFileSync(currentPath, current, { mode: 0o660 }); + fs.writeFileSync(stagedPath, backup, { mode: 0o600 }); const result = spawnSync( "python3", @@ -201,8 +205,10 @@ export function runMergeScript( dir, "config.toml", JSON.stringify(stateFileKeyMergeSpec(ownership)), + stagedPath, + sha256(backup), ], - { encoding: "utf-8", input: backup }, + { encoding: "utf-8" }, ); return { current: fs.readFileSync(currentPath, "utf-8"), @@ -224,6 +230,8 @@ interface ProductionRunOptions { currentLink?: "hardlink" | "symlink"; parentAncestorSymlink?: boolean; script?: string; + stagedDigest?: string; + stagedMode?: number; } function ancestorSymlinkConfigDir(dir: string): { configDir: string; stateFilePath: string } { @@ -268,30 +276,34 @@ export function runProductionCommand( status: number | null; stderr: string; } { - const dir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-file-command-")); + const dir = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-file-command-")), + ); const { configDir, stateFilePath } = options.parentAncestorSymlink ? ancestorSymlinkConfigDir(dir) : { configDir: dir, stateFilePath: "config.toml" }; const currentPath = path.join(configDir, "config.toml"); try { + const stagedPath = path.join(dir, "nemoclaw-state-restore-backup"); + fs.writeFileSync(stagedPath, backup, { mode: 0o600 }); + fs.chmodSync(stagedPath, options.stagedMode ?? 0o600); const currentTargetPath = options.currentLink ? writeLinkedCurrentConfig(dir, currentPath, current, options.currentLink) : writePlainCurrentConfig(currentPath, current); - const baseCommand = buildKeyAllowlistMergeRestoreCommand( + const args = [ + "-I", + "-c", + PYTHON_TEST_TOMLI_WRITER_SHIM, + options.script ?? KEY_ALLOWLIST_MERGE_PYTHON, dir, - { path: stateFilePath }, - DCODE_OWNERSHIP, - ); - const commandWithScript = options.script - ? baseCommand.replace(shellQuote(KEY_ALLOWLIST_MERGE_PYTHON), shellQuote(options.script)) - : baseCommand; - const command = commandWithScript.replace( - "/opt/venv/bin/python3", - `python3 -I -c ${shellQuote(PYTHON_TEST_TOMLI_WRITER_SHIM)}`, - ); - const result = spawnSync("bash", ["-c", command], { + stateFilePath, + JSON.stringify(stateFileKeyMergeSpec(DCODE_OWNERSHIP)), + stagedPath, + options.stagedDigest ?? sha256(backup), + ]; + const command = JSON.stringify(["python3", ...args]); + const result = spawnSync("python3", args, { encoding: "utf-8", - input: backup, }); return { command, diff --git a/src/lib/state/state-file-key-merge.ts b/src/lib/state/state-file-key-merge.ts index ffc6558dd8f..0c76b3230ce 100644 --- a/src/lib/state/state-file-key-merge.ts +++ b/src/lib/state/state-file-key-merge.ts @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import type { StateFileKeyAllowlistRestoreOwnership, StateFileUserKeyType } from "../agent/defs.js"; -import { shellQuote } from "../runner.js"; export { KEY_ALLOWLIST_MERGE_PYTHON } from "./key-allowlist-merge/python-script.js"; @@ -44,29 +43,3 @@ export function stateFileKeyMergeSpec( })), }; } - -function assertSafeStateFilePath(path: string): void { - if (path.startsWith("/") || path.split("/").some((segment) => segment === "..")) { - throw new Error(`State file path '${path}' must be a relative path without '..' segments`); - } -} - -export function buildKeyAllowlistMergeRestoreCommand( - dir: string, - spec: { path: string }, - ownership: StateFileKeyAllowlistRestoreOwnership, -): string { - assertSafeStateFilePath(spec.path); - const normalizedDir = dir.replace(/\/+$/, ""); - const destination = shellQuote(`${normalizedDir}/${spec.path}`); - const baseDir = shellQuote(normalizedDir); - const relativePath = shellQuote(spec.path); - const mergeSpec = shellQuote(JSON.stringify(stateFileKeyMergeSpec(ownership))); - return [ - `dst=${destination}`, - 'parent="$(dirname "$dst")"', - '[ -d "$parent" ] && [ ! -L "$parent" ] || { echo "unsafe config parent" >&2; exit 10; }', - '[ -f "$dst" ] && [ ! -L "$dst" ] || { echo "fresh config is missing or unsafe" >&2; exit 11; }', - `/opt/venv/bin/python3 -I -c ${shellQuote(KEY_ALLOWLIST_MERGE_PYTHON)} ${baseDir} ${relativePath} ${mergeSpec}`, - ].join("; "); -} diff --git a/src/lib/state/state-file-restore-custom-image.test.ts b/src/lib/state/state-file-restore-custom-image.test.ts index 52bab58317b..713f1ca130c 100644 --- a/src/lib/state/state-file-restore-custom-image.test.ts +++ b/src/lib/state/state-file-restore-custom-image.test.ts @@ -5,15 +5,38 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; -import { afterEach, describe, expect, it, vi } from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; + +const mocks = vi.hoisted(() => ({ upload: vi.fn() })); + +vi.mock("../adapters/openshell/sandbox-upload.js", async (importOriginal) => ({ + ...(await importOriginal()), + uploadSandboxPayloadFile: mocks.upload, +})); import type { OpenShellSandboxControl } from "../adapters/openshell/sandbox-control"; +import { + SANDBOX_PAYLOAD_CLEANUP_OK, + SANDBOX_PAYLOAD_CLEANUP_PYTHON, +} from "../adapters/openshell/sandbox-upload.js"; import type { StateFileKeyAllowlistRestoreOwnership } from "../agent/defs"; -import { restoreStateFile } from "./state-file-restore"; +import { KEY_ALLOWLIST_MERGE_PYTHON } from "./state-file-key-merge"; +import { + KEY_ALLOWLIST_RESTORE_OK, + MAX_STATE_FILE_RESTORE_BYTES, + restoreStateFile, + STATE_FILE_RESTORE_OK, + STATE_FILE_RESTORE_PYTHON, +} from "./state-file-restore"; -const execMock = vi.fn(async () => ({ +const execMock = vi.fn(async (request) => ({ status: 0, - stdout: "", + stdout: + request.stdin === SANDBOX_PAYLOAD_CLEANUP_PYTHON + ? `${SANDBOX_PAYLOAD_CLEANUP_OK}\n` + : request.command[0] === "/opt/venv/bin/python3" + ? `${KEY_ALLOWLIST_RESTORE_OK}\n` + : `${STATE_FILE_RESTORE_OK}\n`, stderr: "", })); const sandboxControl = { exec: execMock }; @@ -35,8 +58,35 @@ function createBackupFixture(): { backupPath: string; backupContents: Buffer } { return { backupPath, backupContents }; } +function restoreExecCalls() { + return execMock.mock.calls.filter( + ([request]) => + request.stdin === STATE_FILE_RESTORE_PYTHON || request.stdin === KEY_ALLOWLIST_MERGE_PYTHON, + ); +} + +function cleanupExecCalls() { + return execMock.mock.calls.filter( + ([request]) => request.stdin === SANDBOX_PAYLOAD_CLEANUP_PYTHON, + ); +} + +beforeEach(() => { + execMock.mockReset(); + execMock.mockImplementation(async (request) => ({ + status: 0, + stdout: + request.stdin === SANDBOX_PAYLOAD_CLEANUP_PYTHON + ? `${SANDBOX_PAYLOAD_CLEANUP_OK}\n` + : request.command[0] === "/opt/venv/bin/python3" + ? `${KEY_ALLOWLIST_RESTORE_OK}\n` + : `${STATE_FILE_RESTORE_OK}\n`, + stderr: "", + })); + mocks.upload.mockReset(); +}); + afterEach(() => { - vi.clearAllMocks(); for (const fixture of fixtures.splice(0)) { fs.rmSync(fixture, { recursive: true, force: true }); } @@ -45,6 +95,15 @@ afterEach(() => { describe("custom-image state-file restore capability (#6334)", () => { it("restores the complete backup without invoking the managed key allowlist", async () => { const { backupPath, backupContents } = createBackupFixture(); + let uploadedContents = Buffer.alloc(0); + mocks.upload.mockImplementation( + (gateway: string, sandbox: string, localPath: string, remotePath: string) => { + expect(gateway).toBe("nemoclaw-18080"); + expect(sandbox).toBe("alpha"); + uploadedContents = fs.readFileSync(localPath); + return { ok: true, remotePath }; + }, + ); const restored = await restoreStateFile( sandboxControl, @@ -55,19 +114,41 @@ describe("custom-image state-file restore capability (#6334)", () => { ownership, true, vi.fn(), + undefined, + undefined, + "nemoclaw-18080", ); expect(restored).toBe(true); const request = execMock.mock.calls[0]?.[0]; - const command = String(request?.command.at(-1)); - expect(command).toContain(".nemoclaw-restore.XXXXXX"); - expect(command).not.toContain("/opt/venv/bin/python3"); - expect(command).not.toContain("show_scrollbar"); - expect(request?.stdin).toEqual(backupContents); + expect(request?.command).toEqual([ + "python3", + "-I", + "-", + expect.stringMatching(/^\/tmp\/nemoclaw-state-restore-/), + "/sandbox/.deepagents", + "config.toml", + "copy", + "0", + expect.stringMatching(/^[0-9a-f]{64}$/), + ]); + expect(request?.stdin).toBe(STATE_FILE_RESTORE_PYTHON); + expect(request?.maxOutputBytes).toBe(64 * 1024); + expect(uploadedContents).toEqual(backupContents); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(restoreExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(0); }); it("requires the capability before bypassing the managed key allowlist", async () => { const { backupPath, backupContents } = createBackupFixture(); + let uploadedContents = Buffer.alloc(0); + mocks.upload.mockImplementation( + (_gateway: string, _sandbox: string, localPath: string, remotePath: string) => { + uploadedContents = fs.readFileSync(localPath); + return { ok: true, remotePath }; + }, + ); const restored = await restoreStateFile( sandboxControl, @@ -78,15 +159,139 @@ describe("custom-image state-file restore capability (#6334)", () => { ownership, false, vi.fn(), + undefined, + undefined, + "nemoclaw-18080", ); expect(restored).toBe(true); const request = execMock.mock.calls[0]?.[0]; - const command = String(request?.command.at(-1)); - expect(command).toContain("/opt/venv/bin/python3 -I -c"); - expect(command).toContain("show_scrollbar"); - expect(command).toContain("require_fresh_tables"); - expect(command).not.toContain(".nemoclaw-restore.XXXXXX"); - expect(request?.stdin).toEqual(backupContents); + expect(request?.command.slice(0, 6)).toEqual([ + "/opt/venv/bin/python3", + "-I", + "-", + "/sandbox/.deepagents", + "config.toml", + expect.stringContaining("show_scrollbar"), + ]); + expect(request?.command[6]).toEqual(expect.stringMatching(/^\/tmp\/nemoclaw-state-restore-/)); + expect(request?.command[7]).toEqual(expect.stringMatching(/^[0-9a-f]{64}$/)); + expect(request?.stdin).toBe(KEY_ALLOWLIST_MERGE_PYTHON); + expect(uploadedContents).toEqual(backupContents); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(restoreExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(0); + }); + + it("rejects an oversized sparse host backup before allocation or upload", async () => { + const { backupPath } = createBackupFixture(); + fs.truncateSync(path.join(backupPath, "config.toml"), MAX_STATE_FILE_RESTORE_BYTES + 1); + + const restored = await restoreStateFile( + sandboxControl, + "alpha", + "/sandbox/.deepagents", + { path: "config.toml", strategy: "copy" }, + backupPath, + ownership, + true, + vi.fn(), + ); + + expect(restored).toBe(false); + expect(mocks.upload).not.toHaveBeenCalled(); + expect(restoreExecCalls()).toHaveLength(0); + expect(cleanupExecCalls()).toHaveLength(0); + }); + + it.each([ + ["error result", { status: null, stdout: "", stderr: "", error: new Error("unknown") }], + [ + "signal result", + { status: null, stdout: "", stderr: "", signal: "SIGTERM" as NodeJS.Signals }, + ], + ])("does not replay an indeterminate selected-transport %s", async (_label, outcome) => { + const { backupPath } = createBackupFixture(); + mocks.upload.mockImplementation( + (_gateway: string, _sandbox: string, _localPath: string, remotePath: string) => ({ + ok: true, + remotePath, + }), + ); + execMock.mockResolvedValue(outcome); + + const restored = await restoreStateFile( + sandboxControl, + "alpha", + "/sandbox/.deepagents", + { path: "config.toml", strategy: "copy" }, + backupPath, + undefined, + true, + vi.fn(), + undefined, + undefined, + "nemoclaw-18080", + ); + + expect(restored).toBe(false); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(restoreExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(1); + }); + + it("rejects status zero without the fixed success sentinel", async () => { + const { backupPath } = createBackupFixture(); + mocks.upload.mockImplementation( + (_gateway: string, _sandbox: string, _localPath: string, remotePath: string) => ({ + ok: true, + remotePath, + }), + ); + execMock.mockResolvedValue({ status: 0, stdout: "unexpected output", stderr: "" }); + + const restored = await restoreStateFile( + sandboxControl, + "alpha", + "/sandbox/.deepagents", + { path: "config.toml", strategy: "copy" }, + backupPath, + undefined, + true, + vi.fn(), + ); + + expect(restored).toBe(false); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(restoreExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(1); + }); + + it("does not dispatch after a state-file upload failure", async () => { + const { backupPath } = createBackupFixture(); + mocks.upload.mockReturnValue({ + ok: false, + error: "upload failed", + remotePath: "/tmp/nemoclaw-state-restore-failed", + }); + + const restored = await restoreStateFile( + sandboxControl, + "alpha", + "/sandbox/.deepagents", + { path: "config.toml", strategy: "copy" }, + backupPath, + undefined, + true, + vi.fn(), + undefined, + undefined, + "nemoclaw-18080", + ); + + expect(restored).toBe(false); + expect(mocks.upload).toHaveBeenCalledOnce(); + expect(restoreExecCalls()).toHaveLength(0); + expect(cleanupExecCalls()).toHaveLength(1); }); }); diff --git a/src/lib/state/state-file-restore-python.test.ts b/src/lib/state/state-file-restore-python.test.ts new file mode 100644 index 00000000000..52aadaec2d2 --- /dev/null +++ b/src/lib/state/state-file-restore-python.test.ts @@ -0,0 +1,197 @@ +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import { createHash } from "node:crypto"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; + +import { afterEach, describe, expect, it } from "vitest"; + +import { STATE_FILE_RESTORE_PYTHON } from "./state-file-restore.js"; + +const fixtures: string[] = []; + +function fixture(): { base: string; remotePath: string; stateRoot: string } { + const base = fs.realpathSync( + fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-state-file-program-")), + ); + fixtures.push(base); + const stateRoot = path.join(base, "state-root"); + fs.mkdirSync(stateRoot); + return { + base, + stateRoot, + remotePath: path.join(base, "nemoclaw-state-restore-fixture"), + }; +} + +function runProgram( + remotePath: string, + stateRoot: string, + relativePath: string, + strategy: "copy" | "sqlite_backup", + refresh: boolean, + expectedDigest?: string, +) { + const digest = createHash("sha256").update(fs.readFileSync(remotePath)).digest("hex"); + return spawnSync( + "python3", + [ + "-I", + "-", + remotePath, + stateRoot, + relativePath, + strategy, + refresh ? "1" : "0", + expectedDigest ?? digest, + ], + { + input: STATE_FILE_RESTORE_PYTHON, + encoding: "utf8", + timeout: 30_000, + maxBuffer: 64 * 1024, + }, + ); +} + +afterEach(() => { + for (const item of fixtures.splice(0)) fs.rmSync(item, { recursive: true, force: true }); +}); + +describe("staged state-file restore program", () => { + it("copies through pinned descriptors and refreshes OpenClaw recovery anchors", () => { + const { remotePath, stateRoot } = fixture(); + const contents = Buffer.from('{"restored":true}\n'); + fs.writeFileSync(remotePath, contents, { mode: 0o600 }); + + const result = runProgram(remotePath, stateRoot, "nested/openclaw.json", "copy", true); + + expect(result.status, result.stderr).toBe(0); + expect(result.stdout.trim()).toBe("STATE_FILE_OK"); + expect(fs.existsSync(remotePath)).toBe(false); + const destination = path.join(stateRoot, "nested", "openclaw.json"); + expect(fs.readFileSync(destination)).toEqual(contents); + expect(fs.statSync(destination).mode & 0o777).toBe(0o640); + expect(fs.readFileSync(`${destination}.last-good`)).toEqual(contents); + expect(fs.readFileSync(path.join(stateRoot, "nested", ".config-hash"), "utf8")).toMatch( + /^[0-9a-f]{64} openclaw\.json\n$/, + ); + }); + + it("restores SQLite with backup and quick-check semantics", () => { + const { remotePath, stateRoot } = fixture(); + const create = spawnSync( + "python3", + [ + "-c", + "import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); c.execute('create table t(v text)'); c.execute(\"insert into t values ('restored')\"); c.commit(); c.close()", + remotePath, + ], + { encoding: "utf8" }, + ); + expect(create.status, create.stderr).toBe(0); + + const result = runProgram(remotePath, stateRoot, "db/state.sqlite", "sqlite_backup", false); + + expect(result.status, result.stderr).toBe(0); + const query = spawnSync( + "python3", + [ + "-c", + "import sqlite3,sys; c=sqlite3.connect(sys.argv[1]); print(c.execute('select v from t').fetchone()[0]); c.close()", + path.join(stateRoot, "db", "state.sqlite"), + ], + { encoding: "utf8" }, + ); + expect(query.status, query.stderr).toBe(0); + expect(query.stdout.trim()).toBe("restored"); + expect(fs.existsSync(remotePath)).toBe(false); + }); + + it("rejects malformed SQLite without changing the destination or leaking stages", () => { + const { remotePath, stateRoot } = fixture(); + const destinationDir = path.join(stateRoot, "db"); + const destination = path.join(destinationDir, "state.sqlite"); + fs.mkdirSync(destinationDir); + fs.writeFileSync(destination, "untouched destination\n"); + fs.writeFileSync(remotePath, "not a sqlite database\n", { mode: 0o600 }); + + const result = runProgram(remotePath, stateRoot, "db/state.sqlite", "sqlite_backup", false); + + expect(result.status).not.toBe(0); + expect(fs.readFileSync(destination, "utf8")).toBe("untouched destination\n"); + expect( + fs.readdirSync(destinationDir).filter((entry) => entry.startsWith(".nemoclaw-")), + ).toEqual([]); + }); + + it("preflights recovery anchors before replacing any live file", () => { + const { base, remotePath, stateRoot } = fixture(); + const destinationDir = path.join(stateRoot, "nested"); + const destination = path.join(destinationDir, "openclaw.json"); + const lastGood = `${destination}.last-good`; + const attackTarget = path.join(base, "hash-target"); + fs.mkdirSync(destinationDir); + fs.writeFileSync(destination, "live before\n"); + fs.writeFileSync(lastGood, "anchor before\n"); + fs.writeFileSync(attackTarget, "hash target before\n"); + fs.symlinkSync(attackTarget, path.join(destinationDir, ".config-hash")); + fs.writeFileSync(remotePath, "replacement\n", { mode: 0o600 }); + + const result = runProgram(remotePath, stateRoot, "nested/openclaw.json", "copy", true); + + expect(result.status).not.toBe(0); + expect(fs.readFileSync(destination, "utf8")).toBe("live before\n"); + expect(fs.readFileSync(lastGood, "utf8")).toBe("anchor before\n"); + expect(fs.readFileSync(attackTarget, "utf8")).toBe("hash target before\n"); + expect( + fs.readdirSync(destinationDir).filter((entry) => entry.startsWith(".nemoclaw-")), + ).toEqual([]); + }); + + it("rejects a staged payload whose uploaded digest does not match", () => { + const { remotePath, stateRoot } = fixture(); + const destination = path.join(stateRoot, "config.json"); + fs.writeFileSync(destination, "untouched\n"); + fs.writeFileSync(remotePath, "replacement\n", { mode: 0o600 }); + + const result = runProgram(remotePath, stateRoot, "config.json", "copy", false, "0".repeat(64)); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("digest mismatch"); + expect(fs.readFileSync(destination, "utf8")).toBe("untouched\n"); + }); + + it("rejects a staged payload writable by the sandbox group", () => { + const { remotePath, stateRoot } = fixture(); + fs.writeFileSync(remotePath, "replacement\n", { mode: 0o620 }); + fs.chmodSync(remotePath, 0o620); + + const result = runProgram(remotePath, stateRoot, "config.json", "copy", false); + + expect(result.status).not.toBe(0); + expect(result.stderr).toContain("unsafe staged state file"); + expect(fs.existsSync(path.join(stateRoot, "config.json"))).toBe(false); + }); + + it.each(["staged", "root"] as const)("rejects a symlinked %s component", (kind) => { + const { base, remotePath, stateRoot } = fixture(); + const destination = path.join(stateRoot, "config.json"); + fs.writeFileSync(destination, "untouched"); + const realPayload = path.join(base, "real-payload"); + fs.writeFileSync(realPayload, "replacement", { mode: 0o600 }); + const rootLink = path.join(base, "state-root-link"); + fs.symlinkSync(stateRoot, rootLink); + fs.symlinkSync(realPayload, remotePath); + const selectedRemote = kind === "staged" ? remotePath : realPayload; + const selectedRoot = kind === "root" ? rootLink : stateRoot; + + const result = runProgram(selectedRemote, selectedRoot, "config.json", "copy", false); + + expect(result.status).not.toBe(0); + expect(fs.readFileSync(destination, "utf8")).toBe("untouched"); + }); +}); diff --git a/src/lib/state/state-file-restore.ts b/src/lib/state/state-file-restore.ts index 84da15e56de..9e76ff66a89 100644 --- a/src/lib/state/state-file-restore.ts +++ b/src/lib/state/state-file-restore.ts @@ -1,104 +1,387 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { existsSync, readFileSync } from "node:fs"; +import { + closeSync, + existsSync, + constants as fsConstants, + fstatSync, + openSync, + readSync, +} from "node:fs"; import path from "node:path"; -import type { OpenShellSandboxControl } from "../adapters/openshell/sandbox-control.js"; +import { + type OpenShellSandboxControl, + type SandboxExecRequest, + validateOpenShellExecRequest, +} from "../adapters/openshell/sandbox-control.js"; +import { + cleanupSandboxPayloadAfterFailure, + createPrivateSandboxPayloadFile, + createPrivateSandboxPayloadFileFromPath, + createSandboxPayloadRemotePath, + uploadSandboxPayloadFile, +} from "../adapters/openshell/sandbox-upload.js"; import type { StateFileRestoreOwnership } from "../agent/defs.js"; -import { shellQuote } from "../runner.js"; import { buildOpenClawConfigRestoreInputFromSandbox } from "./openclaw-config-restore-input.js"; import type { OpenClawImagePluginInstall } from "./openclaw-plugin-restore.js"; -import { buildKeyAllowlistMergeRestoreCommand } from "./state-file-key-merge.js"; +import { KEY_ALLOWLIST_MERGE_PYTHON, stateFileKeyMergeSpec } from "./state-file-key-merge.js"; export interface StateFileRestoreSpec { path: string; strategy: "copy" | "sqlite_backup"; } -const SQLITE_RESTORE_PY = [ - "import os, sqlite3, sys", - "src, dst = sys.argv[1], sys.argv[2]", - "os.makedirs(os.path.dirname(dst), exist_ok=True)", - "src_conn = sqlite3.connect('file:' + src + '?mode=ro', uri=True, timeout=30)", - "dst_conn = sqlite3.connect(dst, timeout=30)", - "try:", - " dst_conn.execute('PRAGMA busy_timeout=30000')", - " src_conn.backup(dst_conn)", - " ok = dst_conn.execute('PRAGMA quick_check').fetchone()[0]", - " if ok != 'ok':", - " raise SystemExit('sqlite quick_check failed: ' + str(ok))", - "finally:", - " dst_conn.close()", - " src_conn.close()", - "os.chmod(dst, 0o660)", -].join("\n"); - -function stateFileRemotePath(dir: string, filePath: string): string { - return `${dir.replace(/\/+$/, "")}/${filePath}`; -} +const STATE_FILE_RESTORE_MAX_OUTPUT_BYTES = 64 * 1024; +export const MAX_STATE_FILE_RESTORE_BYTES = 256 * 1024 * 1024; +export const MAX_TRANSFORMED_STATE_FILE_RESTORE_BYTES = 16 * 1024 * 1024; +export const STATE_FILE_RESTORE_OK = "STATE_FILE_OK"; +export const KEY_ALLOWLIST_RESTORE_OK = "KEY_ALLOWLIST_OK"; -export function buildStateFileRestoreCommand( - dir: string, - spec: StateFileRestoreSpec, - refreshOpenClawConfigHash = false, -): string { - const remotePath = stateFileRemotePath(dir, spec.path); - const quotedRemotePath = shellQuote(remotePath); - if (spec.strategy === "sqlite_backup") { - return [ - `dst=${quotedRemotePath}`, - 'parent="$(dirname "$dst")"', - '[ ! -L "$parent" ] || { echo "refusing symlinked state parent: $parent" >&2; exit 10; }', - '[ ! -L "$dst" ] || { echo "refusing symlinked sqlite target: $dst" >&2; exit 11; }', - 'mkdir -p "$parent"', - 'tmp="$(mktemp /tmp/nemoclaw-sqlite-restore.XXXXXX)"', - "trap 'rm -f \"$tmp\"' EXIT", - 'cat > "$tmp"', - 'chmod 600 "$tmp"', - `umask 0007; python3 -c ${shellQuote(SQLITE_RESTORE_PY)} "$tmp" "$dst"`, - ].join("; "); - } +type BoundedStateFileReadResult = { ok: true; contents: Buffer } | { ok: false; error: string }; - const steps = [ - `dst=${quotedRemotePath}`, - 'parent="$(dirname "$dst")"', - '[ ! -L "$parent" ] || { echo "refusing symlinked state parent: $parent" >&2; exit 10; }', - '[ ! -L "$dst" ] || { echo "refusing symlinked state target: $dst" >&2; exit 11; }', - 'mkdir -p "$parent"', - 'tmp="$(mktemp "${parent}/.nemoclaw-restore.XXXXXX")"', - 'trap \'rm -f "$tmp" "${anchor_tmp:-}"\' EXIT', - 'cat > "$tmp"', - 'chmod 640 "$tmp"', - ]; - - if (refreshOpenClawConfigHash) { - // Stage the OpenClaw recovery anchor before swapping the live config so - // the integrity watcher can never observe a restored config paired with a - // stale `.last-good` recovery target. - steps.push( - 'last_good="${dst}.last-good"', - '[ ! -L "$last_good" ] || { echo "refusing symlinked last-good target: $last_good" >&2; exit 13; }', - 'anchor_tmp="$(mktemp "${parent}/.nemoclaw-lastgood.XXXXXX")" || { echo "failed to stage last-good anchor" >&2; exit 14; }', - 'cat "$tmp" > "$anchor_tmp" || { echo "failed to write last-good anchor" >&2; exit 14; }', - 'chmod 660 "$anchor_tmp" 2>/dev/null || true', - 'mv -f "$anchor_tmp" "$last_good" || { echo "failed to install last-good anchor" >&2; exit 14; }', - ); +function readBoundedStateFile(localPath: string, maxBytes: number): BoundedStateFileReadResult { + let fd: number | undefined; + try { + fd = openSync(localPath, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW); + const before = fstatSync(fd); + if (!before.isFile() || before.size > maxBytes) { + return { + ok: false, + error: `state file is not regular or exceeds ${String(maxBytes)} bytes`, + }; + } + const contents = Buffer.alloc(before.size); + let offset = 0; + while (offset < contents.length) { + const count = readSync(fd, contents, offset, contents.length - offset, null); + if (count === 0) return { ok: false, error: "state file changed while reading" }; + offset += count; + } + if (readSync(fd, Buffer.alloc(1), 0, 1, null) !== 0) { + return { ok: false, error: "state file exceeds bounded size while reading" }; + } + const after = fstatSync(fd); + if ( + after.size !== before.size || + after.mtimeMs !== before.mtimeMs || + after.ino !== before.ino || + after.dev !== before.dev + ) { + return { ok: false, error: "state file changed while reading" }; + } + return { ok: true, contents }; + } catch (cause) { + const detail = cause instanceof Error ? cause.message : String(cause); + return { ok: false, error: detail.substring(0, 200) }; + } finally { + if (fd !== undefined) closeSync(fd); } +} - steps.push('mv -f "$tmp" "$dst"'); +export const STATE_FILE_RESTORE_PYTHON = String.raw`import hashlib, json, os, posixpath, re, secrets, sqlite3, stat, sys, tempfile, urllib.parse - if (refreshOpenClawConfigHash) { - steps.push( - 'hash_file="${parent}/.config-hash"', - '[ ! -L "$hash_file" ] || { echo "refusing symlinked config hash target: $hash_file" >&2; exit 12; }', - '(cd "$parent" && sha256sum "$(basename "$dst")" > .config-hash)', - 'chmod 660 "$hash_file" 2>/dev/null || true', - ); - } +MAX_BYTES = 256 * 1024 * 1024 +CHUNK = 64 * 1024 +DIR_FLAGS = os.O_RDONLY | getattr(os, "O_DIRECTORY", 0) | getattr(os, "O_NOFOLLOW", 0) - return steps.join("; "); -} +def fail(message): + print(message, file=sys.stderr) + raise SystemExit(20) + +def safe_text(value): + return isinstance(value, str) and 0 < len(value) <= 4096 and not any(ord(c) < 32 or ord(c) == 127 for c in value) + +def open_absolute_parent(pathname): + if not safe_text(pathname) or not posixpath.isabs(pathname) or posixpath.normpath(pathname) != pathname or pathname == "/": + fail("invalid staged state file path") + parts = pathname.split("/")[1:] + parent = os.open("/", DIR_FLAGS) + try: + for component in parts[:-1]: + child = os.open(component, DIR_FLAGS, dir_fd=parent) + os.close(parent) + parent = child + return parent, parts[-1] + except BaseException: + os.close(parent) + raise + +def open_absolute_dir(pathname): + if not safe_text(pathname) or not posixpath.isabs(pathname) or posixpath.normpath(pathname) != pathname or pathname == "/": + fail("invalid state file root") + current = os.open("/", DIR_FLAGS) + try: + for component in pathname.split("/")[1:]: + child = os.open(component, DIR_FLAGS, dir_fd=current) + os.close(current) + current = child + return current + except BaseException: + os.close(current) + raise + +def open_relative_parent(root_fd, relative): + if not safe_text(relative) or posixpath.isabs(relative) or "\\" in relative or posixpath.normpath(relative) != relative or relative in (".", "..") or relative.startswith("../"): + fail("invalid state file path") + parts = relative.split("/") + current = os.dup(root_fd) + try: + for component in parts[:-1]: + try: + child = os.open(component, DIR_FLAGS, dir_fd=current) + except FileNotFoundError: + os.mkdir(component, 0o700, dir_fd=current) + child = os.open(component, DIR_FLAGS, dir_fd=current) + os.close(current) + current = child + return current, parts[-1] + except BaseException: + os.close(current) + raise + +def ensure_replaceable(parent_fd, name, label): + try: + metadata = os.stat(name, dir_fd=parent_fd, follow_symlinks=False) + except FileNotFoundError: + return + if not stat.S_ISREG(metadata.st_mode) or metadata.st_nlink != 1: + fail(label + " is not a single regular file") + +def private_name(prefix): + return prefix + secrets.token_hex(12) + +def copy_fd(source_fd, output_fd): + os.lseek(source_fd, 0, os.SEEK_SET) + total = 0 + digest = hashlib.sha256() + while True: + chunk = os.read(source_fd, CHUNK) + if not chunk: + break + total += len(chunk) + if total > MAX_BYTES: + fail("staged state file exceeds restore limit") + digest.update(chunk) + view = memoryview(chunk) + while view: + written = os.write(output_fd, view) + if written <= 0: + fail("could not write staged state file") + view = view[written:] + return digest.hexdigest() + +def private_snapshot(source_fd, expected_size): + snapshot = tempfile.TemporaryFile() + try: + digest = copy_fd(source_fd, snapshot.fileno()) + if os.fstat(snapshot.fileno()).st_size != expected_size: + fail("staged state file changed while snapshotting") + os.fsync(snapshot.fileno()) + os.fchmod(snapshot.fileno(), 0o400) + os.lseek(snapshot.fileno(), 0, os.SEEK_SET) + return snapshot, digest + except BaseException: + snapshot.close() + raise + +def write_copy(source_fd, parent_fd, destination, refresh): + ensure_replaceable(parent_fd, destination, "state file destination") + last_good = destination + ".last-good" + hash_name = ".config-hash" + if refresh: + ensure_replaceable(parent_fd, last_good, "last-good destination") + ensure_replaceable(parent_fd, hash_name, "config hash destination") + staged_name = None + anchor_name = None + hash_stage = None + try: + staged_name = private_name(".nemoclaw-restore-") + staged_fd = os.open(staged_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600, dir_fd=parent_fd) + try: + digest = copy_fd(source_fd, staged_fd) + os.fchmod(staged_fd, 0o640) + os.fsync(staged_fd) + finally: + os.close(staged_fd) + if refresh: + anchor_name = private_name(".nemoclaw-lastgood-") + anchor_fd = os.open(anchor_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600, dir_fd=parent_fd) + try: + copy_fd(source_fd, anchor_fd) + os.fchmod(anchor_fd, 0o660) + os.fsync(anchor_fd) + finally: + os.close(anchor_fd) + hash_stage = private_name(".nemoclaw-hash-") + hash_fd = os.open(hash_stage, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600, dir_fd=parent_fd) + try: + payload = (digest + " " + destination + "\n").encode("ascii") + view = memoryview(payload) + while view: + written = os.write(hash_fd, view) + if written <= 0: + fail("could not write config hash") + view = view[written:] + os.fchmod(hash_fd, 0o660) + os.fsync(hash_fd) + finally: + os.close(hash_fd) + + if refresh: + os.replace(anchor_name, last_good, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + anchor_name = None + os.replace(staged_name, destination, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + staged_name = None + if refresh: + os.replace(hash_stage, hash_name, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + hash_stage = None + os.fsync(parent_fd) + finally: + for name in (staged_name, anchor_name, hash_stage): + if name is not None: + try: + os.unlink(name, dir_fd=parent_fd) + except FileNotFoundError: + pass + +def write_sqlite(source_fd, parent_fd, destination): + ensure_replaceable(parent_fd, destination, "sqlite destination") + source_name = None + staged_name = None + portable_dir = None + source_path = None + staged_path = None + source_db = None + destination_db = None + try: + source_name = private_name(".nemoclaw-sqlite-source-") + source_copy = os.open(source_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600, dir_fd=parent_fd) + try: + copy_fd(source_fd, source_copy) + os.fsync(source_copy) + finally: + os.close(source_copy) + staged_name = private_name(".nemoclaw-sqlite-restore-") + if os.path.isdir("/proc/self/fd"): + source_path = "/proc/self/fd/" + str(parent_fd) + "/" + source_name + staged_path = "/proc/self/fd/" + str(parent_fd) + "/" + staged_name + else: + portable_dir = tempfile.mkdtemp(prefix="nemoclaw-sqlite-restore-") + os.chmod(portable_dir, 0o700) + source_path = os.path.join(portable_dir, "source.sqlite") + staged_path = os.path.join(portable_dir, "restored.sqlite") + portable_source = os.open(source_path, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600) + try: + copy_fd(source_fd, portable_source) + os.fsync(portable_source) + finally: + os.close(portable_source) + source_uri = "file:" + urllib.parse.quote(source_path, safe="/") + "?mode=ro&immutable=1" + source_db = sqlite3.connect(source_uri, uri=True, timeout=30) + destination_db = sqlite3.connect(staged_path, timeout=30) + destination_db.execute("PRAGMA busy_timeout=30000") + source_db.backup(destination_db) + row = destination_db.execute("PRAGMA quick_check").fetchone() + if not row or row[0] != "ok": + fail("sqlite quick_check failed") + destination_db.close() + destination_db = None + source_db.close() + source_db = None + if portable_dir is None: + staged_fd = os.open(staged_name, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0), dir_fd=parent_fd) + try: + os.fchmod(staged_fd, 0o660) + os.fsync(staged_fd) + finally: + os.close(staged_fd) + else: + portable_metadata = os.stat(staged_path, follow_symlinks=False) + portable_fd = os.open(staged_path, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0)) + try: + opened = os.fstat(portable_fd) + if not stat.S_ISREG(opened.st_mode) or (opened.st_dev, opened.st_ino) != (portable_metadata.st_dev, portable_metadata.st_ino): + fail("unsafe staged sqlite restore") + staged_fd = os.open(staged_name, os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0), 0o600, dir_fd=parent_fd) + try: + copy_fd(portable_fd, staged_fd) + os.fchmod(staged_fd, 0o660) + os.fsync(staged_fd) + finally: + os.close(staged_fd) + finally: + os.close(portable_fd) + os.replace(staged_name, destination, src_dir_fd=parent_fd, dst_dir_fd=parent_fd) + staged_name = None + os.fsync(parent_fd) + finally: + if destination_db is not None: + destination_db.close() + if source_db is not None: + source_db.close() + for name in (source_name, staged_name): + if name is not None: + try: + os.unlink(name, dir_fd=parent_fd) + except FileNotFoundError: + pass + if portable_dir is not None: + for entry in os.scandir(portable_dir): + if entry.is_dir(follow_symlinks=False): + fail("unexpected sqlite restore staging directory") + os.unlink(entry.path) + os.rmdir(portable_dir) + +if len(sys.argv) != 7: + fail("state file restore requires staged path, root, path, strategy, refresh flag, and digest") +remote_path, state_root, relative_path, strategy, refresh_raw, expected_digest = sys.argv[1:] +if not posixpath.basename(remote_path).startswith("nemoclaw-state-restore-"): + fail("invalid staged state file path") +if strategy not in ("copy", "sqlite_backup") or refresh_raw not in ("0", "1"): + fail("invalid state file restore strategy") +if not re.fullmatch(r"[0-9a-f]{64}", expected_digest): + fail("invalid staged state file digest") +remote_parent, remote_name = open_absolute_parent(remote_path) +source_fd = None +root_fd = None +target_parent = None +snapshot = None +try: + before = os.stat(remote_name, dir_fd=remote_parent, follow_symlinks=False) + source_fd = os.open(remote_name, os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0), dir_fd=remote_parent) + opened = os.fstat(source_fd) + if not stat.S_ISREG(opened.st_mode) or opened.st_nlink != 1 or opened.st_size > MAX_BYTES or opened.st_uid != os.geteuid() or opened.st_gid != os.getegid() or opened.st_mode & 0o022 or (opened.st_dev, opened.st_ino) != (before.st_dev, before.st_ino): + fail("unsafe staged state file") + os.unlink(remote_name, dir_fd=remote_parent) + source_baseline = os.fstat(source_fd) + snapshot, actual_digest = private_snapshot(source_fd, source_baseline.st_size) + source_after = os.fstat(source_fd) + if source_after.st_size != source_baseline.st_size or source_after.st_mtime_ns != source_baseline.st_mtime_ns or source_after.st_ctime_ns != source_baseline.st_ctime_ns: + fail("staged state file changed while snapshotting") + if actual_digest != expected_digest: + fail("staged state file digest mismatch") + os.close(source_fd) + source_fd = None + root_fd = open_absolute_dir(state_root) + target_parent, destination = open_relative_parent(root_fd, relative_path) + if strategy == "sqlite_backup": + write_sqlite(snapshot.fileno(), target_parent, destination) + else: + write_copy(snapshot.fileno(), target_parent, destination, refresh_raw == "1") +finally: + if target_parent is not None: + os.close(target_parent) + if root_fd is not None: + os.close(root_fd) + if source_fd is not None: + os.close(source_fd) + if snapshot is not None: + snapshot.close() + os.close(remote_parent) +print("STATE_FILE_OK") +`; export async function restoreStateFile( sandboxControl: OpenShellSandboxControl, @@ -111,19 +394,26 @@ export async function restoreStateFile( log: (message: string) => void, freshImagePluginInstalls?: readonly OpenClawImagePluginInstall[], previousImagePluginInstalls?: readonly OpenClawImagePluginInstall[], + gatewayName = "nemoclaw", ): Promise { const localPath = path.join(backupPath, spec.path); if (!existsSync(localPath)) return true; - const backupContents = readFileSync(localPath); log(`Restoring state file ${spec.path} (${spec.strategy})`); - let command: string; - let input: Buffer | null; + let input: Buffer | null | undefined; + let refreshOpenClawConfigHash = false; + let keyAllowlistOwnership: Extract | null = + null; if (ownership?.merge === "openclaw-config") { - command = buildStateFileRestoreCommand(dir, spec, true); + const boundedRead = readBoundedStateFile(localPath, MAX_TRANSFORMED_STATE_FILE_RESTORE_BYTES); + if (!boundedRead.ok) { + log(`FAILED: state file restore ${spec.path}: ${boundedRead.error}`); + return false; + } + refreshOpenClawConfigHash = true; const result = await buildOpenClawConfigRestoreInputFromSandbox({ - backupContents, + backupContents: boundedRead.contents, dir, freshImagePluginInstalls, log, @@ -139,24 +429,114 @@ export async function restoreStateFile( input = null; } } else if (ownership?.merge === "key-allowlist") { - command = allowCustomImageWholeStateFileRestore - ? buildStateFileRestoreCommand(dir, spec, false) - : buildKeyAllowlistMergeRestoreCommand(dir, spec, ownership); - input = backupContents; + if (!allowCustomImageWholeStateFileRestore) keyAllowlistOwnership = ownership; + input = undefined; } else { - command = buildStateFileRestoreCommand(dir, spec, false); - input = backupContents; + input = undefined; } if (input === null) return false; + if (input && input.length > MAX_TRANSFORMED_STATE_FILE_RESTORE_BYTES) { + log(`FAILED: state file restore ${spec.path}: transformed input exceeds restore limit`); + return false; + } - const result = await sandboxControl.exec({ - sandboxName, - command: ["sh", "-c", command], - stdin: input, - timeoutMs: 120_000, - }); + const remotePath = createSandboxPayloadRemotePath(); + const staged = + input !== undefined + ? createPrivateSandboxPayloadFile(input) + : createPrivateSandboxPayloadFileFromPath( + localPath, + keyAllowlistOwnership + ? MAX_TRANSFORMED_STATE_FILE_RESTORE_BYTES + : MAX_STATE_FILE_RESTORE_BYTES, + ); + if (!staged.ok) { + log(`FAILED: state file restore ${spec.path}: ${staged.error}`); + return false; + } + const request: SandboxExecRequest = keyAllowlistOwnership + ? { + sandboxName, + command: [ + "/opt/venv/bin/python3", + "-I", + "-", + dir, + spec.path, + JSON.stringify(stateFileKeyMergeSpec(keyAllowlistOwnership)), + remotePath, + staged.payload.sha256, + ], + stdin: KEY_ALLOWLIST_MERGE_PYTHON, + timeoutMs: 120_000, + maxOutputBytes: STATE_FILE_RESTORE_MAX_OUTPUT_BYTES, + } + : { + sandboxName, + command: [ + "python3", + "-I", + "-", + remotePath, + dir, + spec.path, + spec.strategy, + refreshOpenClawConfigHash ? "1" : "0", + staged.payload.sha256, + ], + stdin: STATE_FILE_RESTORE_PYTHON, + timeoutMs: 120_000, + maxOutputBytes: STATE_FILE_RESTORE_MAX_OUTPUT_BYTES, + }; + const validationError = validateOpenShellExecRequest(request); + if (validationError) { + staged.payload.cleanup(); + log(`FAILED: state file restore ${spec.path}: ${validationError.message}`); + return false; + } + let upload; + try { + upload = uploadSandboxPayloadFile( + gatewayName, + sandboxName, + staged.payload.localPath, + remotePath, + ); + } finally { + staged.payload.cleanup(); + } + const cleanupRemotePayload = async (): Promise => { + if (!(await cleanupSandboxPayloadAfterFailure(sandboxControl, sandboxName, remotePath))) { + log(`WARNING: could not confirm cleanup of staged state file ${spec.path}`); + } + }; + if (!upload.ok) { + await cleanupRemotePayload(); + log(`FAILED: state file restore ${spec.path} upload: ${upload.error}`); + return false; + } + + let result; + try { + result = await sandboxControl.exec(request); + } catch (cause) { + await cleanupRemotePayload(); + const detail = cause instanceof Error ? cause.message : String(cause); + log(`FAILED: state file restore ${spec.path}: ${detail.substring(0, 200)}`); + return false; + } + + const expectedSentinel = keyAllowlistOwnership ? KEY_ALLOWLIST_RESTORE_OK : STATE_FILE_RESTORE_OK; + if ( + result.status === 0 && + !result.error && + !result.signal && + result.stdout.trim() === expectedSentinel + ) { + return true; + } - if (result.status === 0 && !result.error && !result.signal) return true; + await cleanupRemotePayload(); const detail = result.stderr.trim() || diff --git a/test/openclaw-config-snapshot.test.ts b/test/openclaw-config-snapshot.test.ts index 23e531cabcf..5d8fae2ab61 100644 --- a/test/openclaw-config-snapshot.test.ts +++ b/test/openclaw-config-snapshot.test.ts @@ -1,13 +1,18 @@ // 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 { spawnSync } from "node:child_process"; import { pathToFileURL } from "node:url"; import { afterAll, describe, expect, it, vi } from "vitest"; +const transport = vi.hoisted(() => ({ + mutationRoot: "", + stagedRemotePaths: new Map(), +})); + vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { const exec = async (request: { command: readonly string[]; @@ -16,6 +21,24 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { timeoutMs?: number; stdoutEncoding?: "utf8" | "buffer"; }) => { + if (request.command[0] === "python3") { + const command = [...request.command]; + command[3] = transport.stagedRemotePaths.get(command[3]) ?? command[3]; + command[4] = transport.mutationRoot; + const result = spawnSync(command[0], command.slice(1), { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: "utf8", + }); + return { + status: result.status, + stdout: String(result.stdout ?? ""), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + } const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { input: request.stdin, maxBuffer: request.maxOutputBytes, @@ -45,6 +68,24 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { }; }); +vi.mock("../src/lib/adapters/openshell/sandbox-upload.js", async (importOriginal) => ({ + ...(await importOriginal()), + uploadSandboxPayloadFile: ( + _gateway: string, + _sandbox: string, + localPath: string, + remotePath: string, + ) => { + const stagedPath = path.join( + fs.realpathSync(path.dirname(remotePath)), + path.basename(remotePath), + ); + fs.copyFileSync(localPath, stagedPath); + transport.stagedRemotePaths.set(remotePath, stagedPath); + return { ok: true, remotePath }; + }, +})); + // sandbox-state computes its backup root from HOME at module load time. const ORIGINAL_HOME = process.env.HOME; const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-snapshot-home-")); @@ -69,9 +110,8 @@ function writeExecutable(filePath: string, source: string): void { } /** - * Write fake `openshell` and `ssh` executables that mirror the backup/restore - * SSH contract against a local sandbox-root directory, so backupSandboxState / - * restoreSandboxState exercise the real code path without a live sandbox. + * Write fake binaries for the read-only backup probes. Restore uses the mocked + * upload and selected gRPC fixed-program path against the local sandbox root. */ function writeFakeSandboxBins(binDir: string, fakeRoot: string): void { writeExecutable( @@ -248,6 +288,7 @@ describe("OpenClaw durable config file (#5027)", () => { 2, ), ); + transport.mutationRoot = fs.realpathSync(openclawDir); const restore = await sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); expect(restore.success).toBe(true); expect(restore.restoredFiles).toEqual(["openclaw.json"]); @@ -383,6 +424,7 @@ describe("OpenClaw durable config file (#5027)", () => { ), ); + transport.mutationRoot = fs.realpathSync(openclawDir); const restore = await sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); expect(restore.success).toBe(true); diff --git a/test/snapshot-openclaw-managed-extensions.test.ts b/test/snapshot-openclaw-managed-extensions.test.ts index a028495779b..c6347620ae6 100644 --- a/test/snapshot-openclaw-managed-extensions.test.ts +++ b/test/snapshot-openclaw-managed-extensions.test.ts @@ -2,51 +2,38 @@ // 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 { pathToFileURL } from "node:url"; import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; -vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", async () => { - const { spawnSync } = await import("node:child_process"); - const exec = async (request: { - command: readonly string[]; - stdin?: string | Buffer; - maxOutputBytes?: number; - timeoutMs?: number; - stdoutEncoding?: "utf8" | "buffer"; - }) => { - const binary = request.stdoutEncoding === "buffer"; - const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { - input: request.stdin, - maxBuffer: request.maxOutputBytes, - timeout: request.timeoutMs, - encoding: binary ? undefined : "utf8", - }); - 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 } : {}), - }; - }; - return { - execSandboxReadOnlyWithGrpcFallback: async ( - _gatewayName: string, - request: Parameters[0], - ) => exec(request), - selectOpenShellSandboxControlForMutation: () => ({ - control: { exec }, - transport: "grpc", - close: () => {}, - }), - }; -}); +import type { SandboxExecRequest } from "../src/lib/adapters/openshell/sandbox-control.js"; +import { restoreEnv } from "./helpers/env-test-helpers"; + +const mocks = vi.hoisted(() => ({ + exec: vi.fn(), + upload: vi.fn(), +})); -import { restoreEnv, restoreEnvBulk } from "./helpers/env-test-helpers"; +vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", async (importOriginal) => ({ + ...(await importOriginal< + typeof import("../src/lib/adapters/openshell/sandbox-control-routing.js") + >()), + execSandboxReadOnlyWithGrpcFallback: async (_gatewayName: string, request: SandboxExecRequest) => + mocks.exec(request), + selectOpenShellSandboxControlForMutation: () => ({ + control: { exec: mocks.exec }, + transport: "grpc", + close: () => {}, + }), +})); + +vi.mock("../src/lib/adapters/openshell/sandbox-upload.js", async (importOriginal) => ({ + ...(await importOriginal()), + uploadSandboxPayloadFile: mocks.upload, +})); const ORIGINAL_HOME = process.env.HOME; const TMP_HOME = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-managed-extensions-")); @@ -65,10 +52,6 @@ assert.equal( const sandboxState = loadedSandboxState as SandboxStateModule; const BACKUPS_ROOT = path.join(TMP_HOME, ".nemoclaw", "rebuild-backups"); -function writeExecutable(filePath: string, source: string): void { - fs.writeFileSync(filePath, source, { mode: 0o755 }); -} - function writeBackup( sandboxName: string, dirName: string, @@ -121,22 +104,6 @@ function writeOpenClawRegistry(sandboxName: string): void { ); } -function writeFakeOpenshell(binDir: string): string { - const openshell = path.join(binDir, "openshell"); - writeExecutable( - openshell, - `#!/usr/bin/env node -const args = process.argv.slice(2); -if (args[0] === "sandbox" && args[1] === "ssh-config") { - process.stdout.write("Host openshell-alpha\\n HostName 127.0.0.1\\n User sandbox\\n"); - process.exit(0); -} -process.exit(0); -`, - ); - return openshell; -} - afterAll(() => { restoreEnv("HOME", ORIGINAL_HOME); fs.rmSync(TMP_HOME, { recursive: true, force: true }); @@ -164,19 +131,18 @@ describe("OpenClaw managed extension snapshot restore", () => { freshPlugin, }) => { const fixture = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-openclaw-extension-restore-")); - 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 sandboxRoot = path.join(fs.realpathSync(fixture), "sandbox-root"); + fs.mkdirSync(sandboxRoot); + const openclawDir = path.join(fs.realpathSync(sandboxRoot), ".openclaw"); const freshRegistryPath = path.join(fixture, "fresh-installs.json"); - const sshLog = path.join(fixture, "ssh-log.jsonl"); const extensionsDir = path.join(openclawDir, "extensions"); + const requests: SandboxExecRequest[] = []; + const stagedRemotePaths = new Map(); const builtInManagedExtensions = "nemoclaw,diagnostics-otel,brave,discord,openclaw-weixin,slack,whatsapp,msteams".split(","); const freshImagePlugins = freshPlugin ? [freshPlugin] : []; const managedExtensions = [...builtInManagedExtensions, ...freshImagePlugins]; - fs.mkdirSync(binDir, { recursive: true }); for (const extensionName of managedExtensions) { const extensionDir = path.join(extensionsDir, extensionName); fs.mkdirSync(extensionDir, { recursive: true }); @@ -223,61 +189,49 @@ describe("OpenClaw managed extension snapshot restore", () => { "restored\n", ); - const openshell = writeFakeOpenshell(binDir); - writeExecutable( - path.join(binDir, "ssh"), - `#!/usr/bin/env node -const fs = require("node:fs"); -const path = require("node:path"); -const { spawnSync } = require("node:child_process"); -const cmd = process.argv[process.argv.length - 1] || ""; -const installIndexSource = ${JSON.stringify(installIndexSource)}; -fs.appendFileSync(${JSON.stringify(sshLog)}, JSON.stringify({ cmd }) + "\\n"); -function readStdin() { - const chunks = []; - for (;;) { - const buf = Buffer.alloc(65536); - const n = fs.readSync(0, buf, 0, buf.length, null); - if (n === 0) break; - chunks.push(buf.subarray(0, n)); - } - return Buffer.concat(chunks); -} -if (cmd.includes("installed_plugin_index") && cmd.includes("state/openclaw.sqlite")) { - if (installIndexSource === "sqlite") process.stdout.write(fs.readFileSync(${JSON.stringify(freshRegistryPath)})); - process.exit(installIndexSource === "sqlite" ? 0 : 2); -} -if (cmd.includes("plugins/installs.json") && cmd.includes("python3 -c")) { - if (installIndexSource === "legacy") process.stdout.write(fs.readFileSync(${JSON.stringify(freshRegistryPath)})); - process.exit(installIndexSource === "legacy" ? 0 : 2); -} -if (cmd.includes("/sandbox/.openclaw/extensions") && cmd.includes("-exec rm -rf")) { - const extensionsDir = ${JSON.stringify(extensionsDir)}; - const managedExtensions = new Set(${JSON.stringify(managedExtensions)}); - fs.mkdirSync(extensionsDir, { recursive: true }); - for (const entry of fs.readdirSync(extensionsDir)) { - if (managedExtensions.has(entry)) continue; - fs.rmSync(path.join(extensionsDir, entry), { recursive: true, force: true }); - } - process.exit(0); -} -if (cmd.includes("tar --no-same-owner -xf -")) { - const result = spawnSync("tar", ["--no-same-owner", "-xf", "-", "-C", ${JSON.stringify(openclawDir)}], { - input: readStdin(), - stdio: ["pipe", "pipe", "pipe"], - }); - if (result.stdout) fs.writeSync(1, result.stdout); - if (result.stderr) fs.writeSync(2, result.stderr); - process.exit(result.status || 0); -} -if (cmd.includes("chown") || cmd.includes("[ -d ")) process.exit(0); -process.exit(0); -`, + mocks.upload.mockImplementation( + (_gateway: string, _sandbox: string, localPath: string, remotePath: string) => { + const stagedPath = path.join( + fs.realpathSync(path.dirname(remotePath)), + path.basename(remotePath), + ); + fs.copyFileSync(localPath, stagedPath); + stagedRemotePaths.set(remotePath, stagedPath); + return { ok: true, remotePath }; + }, ); + mocks.exec.mockImplementation(async (request: SandboxExecRequest) => { + requests.push(request); + const shellCommand = String(request.command[2] ?? ""); + const registryRead = + (installIndexSource === "sqlite" && shellCommand.includes("state/openclaw.sqlite")) || + (installIndexSource === "legacy" && shellCommand.includes("plugins/installs.json")); + if (request.command[0] === "sh") { + return { + status: registryRead ? 0 : 2, + stdout: registryRead ? fs.readFileSync(freshRegistryPath, "utf8") : "", + stderr: "", + }; + } + const command = [...request.command]; + command[3] = stagedRemotePaths.get(command[3]) ?? command[3]; + command[4] = openclawDir; + const result = spawnSync(command[0], command.slice(1), { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: "utf8", + }); + return { + status: result.status, + stdout: String(result.stdout ?? ""), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + }); writeOpenClawRegistry("alpha"); - process.env.NEMOCLAW_OPENSHELL_BIN = openshell; - process.env.PATH = `${binDir}:${oldPath || ""}`; const restore = await sandboxState.restoreRecreatedSandboxState( "alpha", @@ -301,24 +255,13 @@ process.exit(0); fs.readFileSync(path.join(extensionsDir, "user-extension", "marker.txt"), "utf-8"), ).toBe("restored\n"); - const loggedCommands = fs - .readFileSync(sshLog, "utf-8") - .trim() - .split("\n") - .map((line) => JSON.parse(line).cmd as string); - const cleanupCommands = loggedCommands.filter( - (cmd) => cmd.includes("/sandbox/.openclaw/extensions") && cmd.includes("-exec rm -rf"), - ); - expect(cleanupCommands).toHaveLength(1); - expect(loggedCommands.some((cmd) => cmd.includes("installed_plugin_index"))).toBe(true); - expect(loggedCommands.some((cmd) => cmd.includes("plugins/installs.json"))).toBe( - installIndexSource === "legacy", - ); - const cleanupCommand = cleanupCommands[0]; - expect(cleanupCommand).not.toContain("rm -rf -- /sandbox/.openclaw/extensions"); - for (const extensionName of managedExtensions) { - expect(cleanupCommand).toContain(`! -name '${extensionName}'`); - } + expect(requests.filter((request) => request.command[0] === "python3")).toHaveLength(1); + expect( + requests.some((request) => request.command[2]?.includes("state/openclaw.sqlite")), + ).toBe(true); + expect( + requests.some((request) => request.command[2]?.includes("plugins/installs.json")), + ).toBe(installIndexSource === "legacy"); fs.writeFileSync( freshRegistryPath, @@ -351,18 +294,10 @@ process.exit(0); fs.readFileSync(path.join(extensionsDir, extensionName, "marker.txt"), "utf-8"), ).toBe(`fresh-${extensionName}\n`); } - const commandsAfterRejectedRestore = fs - .readFileSync(sshLog, "utf-8") - .trim() - .split("\n") - .map((line) => JSON.parse(line).cmd as string); - expect( - commandsAfterRejectedRestore.filter( - (cmd) => cmd.includes("/sandbox/.openclaw/extensions") && cmd.includes("-exec rm -rf"), - ), - ).toHaveLength(1); + expect(requests.filter((request) => request.command[0] === "python3")).toHaveLength(1); } finally { - restoreEnvBulk({ NEMOCLAW_OPENSHELL_BIN: oldOpenshell, PATH: oldPath }); + mocks.exec.mockReset(); + mocks.upload.mockReset(); fs.rmSync(fixture, { recursive: true, force: true }); } }); diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts index 05b8c8127c5..80b733956fe 100644 --- a/test/snapshot.test.ts +++ b/test/snapshot.test.ts @@ -1,11 +1,5 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -// -// Tests for snapshot versioning and naming added alongside the --name flag: -// - 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"; @@ -13,6 +7,11 @@ import path from "node:path"; import { pathToFileURL } from "node:url"; import { afterAll, beforeEach, describe, expect, it, vi } from "vitest"; +const transport = vi.hoisted(() => ({ + mutationRoot: "", + stagedRemotePaths: new Map(), +})); + vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { const exec = async (request: { command: readonly string[]; @@ -21,6 +20,29 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { timeoutMs?: number; stdoutEncoding?: "utf8" | "buffer"; }) => { + if (request.command[0] === "/opt/venv/bin/python3") { + const stagedPath = transport.stagedRemotePaths.get(request.command[6]); + if (stagedPath) fs.rmSync(stagedPath, { force: true }); + return { status: 0, stdout: "KEY_ALLOWLIST_OK\n", stderr: "" }; + } + if (request.command[0] === "python3") { + const command = [...request.command]; + command[3] = transport.stagedRemotePaths.get(command[3]) ?? command[3]; + command[4] = transport.mutationRoot; + const result = spawnSync(command[0], command.slice(1), { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: "utf8", + }); + return { + status: result.status, + stdout: String(result.stdout ?? ""), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), + }; + } const result = spawnSync("ssh", [String(request.command.at(-1) ?? "")], { input: request.stdin, maxBuffer: request.maxOutputBytes, @@ -50,6 +72,24 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { }; }); +vi.mock("../src/lib/adapters/openshell/sandbox-upload.js", async (importOriginal) => ({ + ...(await importOriginal()), + uploadSandboxPayloadFile: ( + _gateway: string, + _sandbox: string, + localPath: string, + remotePath: string, + ) => { + const stagedPath = path.join( + fs.realpathSync(path.dirname(remotePath)), + path.basename(remotePath), + ); + fs.copyFileSync(localPath, stagedPath); + transport.stagedRemotePaths.set(remotePath, stagedPath); + return { ok: true, remotePath }; + }, +})); + // Override HOME BEFORE importing sandbox-state — it reads process.env.HOME // at module-load time to compute REBUILD_BACKUPS_DIR. Captured original is // restored in afterAll so sibling tests running in the same worker don't @@ -114,6 +154,8 @@ afterAll(() => { }); beforeEach(() => { fs.rmSync(BACKUPS_ROOT, { recursive: true, force: true }); + transport.mutationRoot = ""; + transport.stagedRemotePaths.clear(); }); function writeExecutable(filePath: string, source: string): void { fs.writeFileSync(filePath, source, { mode: 0o755 }); @@ -572,7 +614,6 @@ process.exit(0); try { const binDir = path.join(fixture, "bin"); const openclawDir = path.join(fixture, "sandbox-root", ".openclaw"); - const sshLog = path.join(fixture, "ssh-log.jsonl"); const existingDirs = ["agents", "workspace", "extensions"]; fs.mkdirSync(binDir, { recursive: true }); fs.mkdirSync(path.join(openclawDir, "agents", "main", "sessions"), { recursive: true }); @@ -588,14 +629,6 @@ const fs = require("node:fs"); const { spawnSync } = require("node:child_process"); const cmd = process.argv[process.argv.length - 1] || ""; const existingDirs = ${JSON.stringify(existingDirs)}; -fs.appendFileSync(${JSON.stringify(sshLog)}, JSON.stringify({ cmd }) + "\\n"); -function readStdin() { - for (;;) { - const buf = Buffer.alloc(65536); - const n = fs.readSync(0, buf, 0, buf.length, null); - if (n === 0) break; - } -} if (cmd.includes("[ -d ")) { process.stdout.write(existingDirs.join("\\0") + "\\0"); process.exit(0); @@ -617,13 +650,6 @@ if (cmd.includes("tar -cf -")) { process.stderr.write("tar: Exiting with failure status due to previous errors\\n"); process.exit(2); } -if (cmd.includes("rm -rf") || cmd.includes("tar --no-same-owner")) { - readStdin(); - process.exit(0); -} -if (cmd.includes("chown") || cmd.includes("[ -r ")) { - process.exit(0); -} process.exit(0); `, ); @@ -643,22 +669,14 @@ process.exit(0); expect(backup.manifest?.backedUpDirs).toEqual(["extensions"]); expect(fs.existsSync(path.join(backup.manifest!.backupPath, "agents"))).toBe(true); + transport.mutationRoot = fs.realpathSync(openclawDir); const restore = await sandboxState.restoreSandboxState("alpha", backup.manifest!.backupPath); expect(restore.success).toBe(true); expect(restore.restoredDirs).toEqual(["extensions"]); - - const loggedCommands = fs - .readFileSync(sshLog, "utf-8") - .trim() - .split("\n") - .map((line) => JSON.parse(line).cmd as string); - const cleanupCommand = loggedCommands.find((cmd) => cmd.includes("rm -rf")); - expect(cleanupCommand).not.toContain("/sandbox/.openclaw/workspace"); - expect(cleanupCommand).not.toContain("rm -rf -- /sandbox/.openclaw/extensions"); - expect(cleanupCommand).toContain("/sandbox/.openclaw/extensions"); - expect(cleanupCommand).toContain("! -name 'nemoclaw'"); - expect(cleanupCommand).toContain("! -name 'openclaw-weixin'"); - expect(cleanupCommand).not.toContain("/sandbox/.openclaw/agents"); + expect(fs.readFileSync(path.join(openclawDir, "workspace", "marker.txt"), "utf8")).toBe( + "marker\n", + ); + expect(fs.existsSync(path.join(openclawDir, "agents", "main", "sessions"))).toBe(true); } finally { if (oldOpenshell === undefined) { delete process.env.NEMOCLAW_OPENSHELL_BIN; @@ -1226,14 +1244,6 @@ if (cmd.includes("tar -cf -")) { if (r.stderr) fs.writeSync(2, r.stderr); process.exit(r.status || 0); } -if (cmd.includes("tar --no-same-owner -xf -")) { - // drain the piped restore tarball in chunks (no full-stream buffering) - const buf = Buffer.alloc(65536); - while (fs.readSync(0, buf, 0, buf.length, null) > 0) { - // discard - } - process.exit(0); -} process.exit(0); `, ); @@ -1280,6 +1290,7 @@ process.exit(0); // #5753 is "lost after rebuild" (backup + recreate + restore): restore // must list agent/skills among the dirs it brings back into the sandbox. + transport.mutationRoot = fs.realpathSync(deepAgentsDir); const restore = await sandboxState.restoreSandboxState( "deepagents", backup.manifest!.backupPath, @@ -1388,19 +1399,6 @@ if (cmd.includes(".hermes_history") && cmd.includes("cat --")) { process.stdout.write(fs.readFileSync(path.join(hermesDir, ".hermes_history"))); process.exit(0); } -if (cmd.includes("nemoclaw-sqlite-restore")) { - fs.mkdirSync(path.join(hermesDir, "runtime"), { recursive: true }); - fs.writeFileSync(path.join(hermesDir, "runtime", "state.db"), readStdin()); - process.exit(0); -} -if (cmd.includes(".nemoclaw-restore") && cmd.includes("SOUL.md")) { - fs.writeFileSync(path.join(hermesDir, "SOUL.md"), readStdin()); - process.exit(0); -} -if (cmd.includes(".nemoclaw-restore") && cmd.includes(".hermes_history")) { - fs.writeFileSync(path.join(hermesDir, ".hermes_history"), readStdin()); - process.exit(0); -} process.exit(0); `, ); @@ -1464,6 +1462,7 @@ process.exit(0); fs.writeFileSync(path.join(hermesDir, "SOUL.md"), "changed soul\n"); fs.writeFileSync(path.join(hermesDir, ".hermes_history"), "changed history\n"); fs.writeFileSync(path.join(runtimeDir, "state.db"), "changed db\n"); + transport.mutationRoot = fs.realpathSync(hermesDir); const restore = await sandboxState.restoreSandboxState("hermes", backup.manifest!.backupPath); expect(restore.success).toBe(true); expect(restore.restoredFiles).toEqual(["SOUL.md", ".hermes_history", "runtime/state.db"]); diff --git a/test/state-file-restore-command.test.ts b/test/state-file-restore-command.test.ts deleted file mode 100644 index 11fc3bfdce4..00000000000 --- a/test/state-file-restore-command.test.ts +++ /dev/null @@ -1,46 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import path from "node:path"; -import { pathToFileURL } from "node:url"; -import { describe, expect, it } from "vitest"; - -const REPO_ROOT = path.join(import.meta.dirname, ".."); -const sandboxState = (await import( - pathToFileURL(path.join(REPO_ROOT, "src", "lib", "state", "sandbox.ts")).href -)) as typeof import("../src/lib/state/sandbox.js"); - -const spec = { path: "openclaw.json", strategy: "copy" } as const; - -describe("buildStateFileRestoreCommand (#5202)", () => { - it("refreshes the OpenClaw .last-good anchor before swapping the live config", () => { - const cmd = sandboxState.buildStateFileRestoreCommand("/sandbox/.openclaw", spec, true); - - // The anchor write targets openclaw.json.last-good and rejects symlinks. - expect(cmd).toContain('last_good="${dst}.last-good"'); - expect(cmd).toContain("refusing symlinked last-good target"); - - // The anchor is staged through a temp and installed via atomic rename, and - // fails closed (exit 14) so a partial write never reaches .last-good. - expect(cmd).toContain(".nemoclaw-lastgood.XXXXXX"); - expect(cmd).toContain('mv -f "$anchor_tmp" "$last_good"'); - expect(cmd).toContain("exit 14"); - - // Anchor must be installed BEFORE the live file is swapped, so OpenClaw's - // integrity watcher never observes a config that disagrees with .last-good. - const anchorIdx = cmd.indexOf('mv -f "$anchor_tmp" "$last_good"'); - const swapIdx = cmd.indexOf('mv -f "$tmp" "$dst"'); - expect(anchorIdx).toBeGreaterThanOrEqual(0); - expect(swapIdx).toBeGreaterThan(anchorIdx); - - // The .config-hash is still refreshed after the swap. - expect(cmd).toContain("sha256sum"); - }); - - it("does not touch the .last-good anchor for non-OpenClaw state restores", () => { - const cmd = sandboxState.buildStateFileRestoreCommand("/sandbox/.openclaw", spec, false); - expect(cmd).not.toContain("last-good"); - expect(cmd).not.toContain("sha256sum"); - expect(cmd).toContain('mv -f "$tmp" "$dst"'); - }); -}); From abc106e405687c78cc59f1a14dece3c9d06c367c Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 14:19:21 -0700 Subject: [PATCH 10/14] test(state): keep restore mocks branchless Signed-off-by: Aaron Erickson --- .../created-sandbox-finalization.test.ts | 16 +++--- ...sandbox-recreated-openclaw-restore.test.ts | 49 ++++++++++--------- test/openclaw-config-snapshot.test.ts | 35 +++++++------ ...apshot-openclaw-managed-extensions.test.ts | 41 ++++++++-------- test/snapshot.test.ts | 49 +++++++++---------- 5 files changed, 97 insertions(+), 93 deletions(-) diff --git a/src/lib/onboard/created-sandbox-finalization.test.ts b/src/lib/onboard/created-sandbox-finalization.test.ts index 65da553286b..03aa0a1f41c 100644 --- a/src/lib/onboard/created-sandbox-finalization.test.ts +++ b/src/lib/onboard/created-sandbox-finalization.test.ts @@ -31,13 +31,15 @@ vi.mock("../adapters/openshell/sandbox-control-routing.js", async () => { const command = [...request.command]; const keyMerge = command[0] === "/opt/venv/bin/python3"; const args = keyMerge ? command.slice(3) : command.slice(1); - if (keyMerge) { - args[0] = restoreTransport.liveDir; - args[3] = restoreTransport.stagedRemotePaths.get(args[3]) ?? args[3]; - } else { - args[2] = restoreTransport.stagedRemotePaths.get(args[2]) ?? args[2]; - args[3] = restoreTransport.liveDir; - } + (keyMerge + ? () => { + args[0] = restoreTransport.liveDir; + args[3] = restoreTransport.stagedRemotePaths.get(args[3]) ?? args[3]; + } + : () => { + args[2] = restoreTransport.stagedRemotePaths.get(args[2]) ?? args[2]; + args[3] = restoreTransport.liveDir; + })(); const result = spawnSync( keyMerge ? restoreTransport.pythonShim : restoreTransport.hostPython, keyMerge ? [String(request.stdin ?? ""), ...args] : args, diff --git a/src/lib/state/sandbox-recreated-openclaw-restore.test.ts b/src/lib/state/sandbox-recreated-openclaw-restore.test.ts index 4081cc18f02..1e5aac6afb6 100644 --- a/src/lib/state/sandbox-recreated-openclaw-restore.test.ts +++ b/src/lib/state/sandbox-recreated-openclaw-restore.test.ts @@ -138,33 +138,34 @@ async function runRestoreScenario(options: { }, ); mocks.exec.mockImplementation(async (request: SandboxExecRequest) => { - if (request.command[0] === "sh") { + const readConfig = () => ({ + status: 0, + stdout: "", + stdoutBytes: fs.readFileSync(path.join(openclawDir, "openclaw.json")), + stderr: "", + }); + const restoreState = () => { + const command = [...request.command]; + command[3] = stagedRemotePaths.get(command[3]) ?? command[3]; + command[4] = openclawDir; + const result = spawnSync(command[0], command.slice(1), { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: request.stdoutEncoding === "buffer" ? undefined : "utf8", + }); return { - status: 0, - stdout: "", - stdoutBytes: fs.readFileSync(path.join(openclawDir, "openclaw.json")), - stderr: "", + status: result.status, + stdout: request.stdoutEncoding === "buffer" ? "" : String(result.stdout ?? ""), + ...(request.stdoutEncoding === "buffer" + ? { stdoutBytes: Buffer.from(result.stdout ?? "") } + : {}), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), }; - } - const command = [...request.command]; - command[3] = stagedRemotePaths.get(command[3]) ?? command[3]; - command[4] = openclawDir; - const result = spawnSync(command[0], command.slice(1), { - input: request.stdin, - maxBuffer: request.maxOutputBytes, - timeout: request.timeoutMs, - encoding: request.stdoutEncoding === "buffer" ? undefined : "utf8", - }); - return { - status: result.status, - stdout: request.stdoutEncoding === "buffer" ? "" : String(result.stdout ?? ""), - ...(request.stdoutEncoding === "buffer" - ? { stdoutBytes: Buffer.from(result.stdout ?? "") } - : {}), - stderr: String(result.stderr ?? ""), - ...(result.error ? { error: result.error } : {}), - ...(result.signal ? { signal: result.signal } : {}), }; + return request.command[0] === "sh" ? readConfig() : restoreState(); }); const restore = await restoreRecreatedSandboxState("alpha", backupPath, { diff --git a/test/openclaw-config-snapshot.test.ts b/test/openclaw-config-snapshot.test.ts index 5d8fae2ab61..0a71e38804f 100644 --- a/test/openclaw-config-snapshot.test.ts +++ b/test/openclaw-config-snapshot.test.ts @@ -21,7 +21,7 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { timeoutMs?: number; stdoutEncoding?: "utf8" | "buffer"; }) => { - if (request.command[0] === "python3") { + const restoreState = () => { const command = [...request.command]; command[3] = transport.stagedRemotePaths.get(command[3]) ?? command[3]; command[4] = transport.mutationRoot; @@ -38,22 +38,25 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { ...(result.error ? { error: result.error } : {}), ...(result.signal ? { signal: result.signal } : {}), }; - } - 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 } : {}), }; + const readState = () => { + 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 } : {}), + }; + }; + return request.command[0] === "python3" ? restoreState() : readState(); }; return { execSandboxReadOnlyWithGrpcFallback: async ( diff --git a/test/snapshot-openclaw-managed-extensions.test.ts b/test/snapshot-openclaw-managed-extensions.test.ts index c6347620ae6..634b6ea9f18 100644 --- a/test/snapshot-openclaw-managed-extensions.test.ts +++ b/test/snapshot-openclaw-managed-extensions.test.ts @@ -206,29 +206,30 @@ describe("OpenClaw managed extension snapshot restore", () => { const registryRead = (installIndexSource === "sqlite" && shellCommand.includes("state/openclaw.sqlite")) || (installIndexSource === "legacy" && shellCommand.includes("plugins/installs.json")); - if (request.command[0] === "sh") { + const readRegistry = () => ({ + status: registryRead ? 0 : 2, + stdout: registryRead ? fs.readFileSync(freshRegistryPath, "utf8") : "", + stderr: "", + }); + const restoreState = () => { + const command = [...request.command]; + command[3] = stagedRemotePaths.get(command[3]) ?? command[3]; + command[4] = openclawDir; + const result = spawnSync(command[0], command.slice(1), { + input: request.stdin, + maxBuffer: request.maxOutputBytes, + timeout: request.timeoutMs, + encoding: "utf8", + }); return { - status: registryRead ? 0 : 2, - stdout: registryRead ? fs.readFileSync(freshRegistryPath, "utf8") : "", - stderr: "", + status: result.status, + stdout: String(result.stdout ?? ""), + stderr: String(result.stderr ?? ""), + ...(result.error ? { error: result.error } : {}), + ...(result.signal ? { signal: result.signal } : {}), }; - } - const command = [...request.command]; - command[3] = stagedRemotePaths.get(command[3]) ?? command[3]; - command[4] = openclawDir; - const result = spawnSync(command[0], command.slice(1), { - input: request.stdin, - maxBuffer: request.maxOutputBytes, - timeout: request.timeoutMs, - encoding: "utf8", - }); - return { - status: result.status, - stdout: String(result.stdout ?? ""), - stderr: String(result.stderr ?? ""), - ...(result.error ? { error: result.error } : {}), - ...(result.signal ? { signal: result.signal } : {}), }; + return request.command[0] === "sh" ? readRegistry() : restoreState(); }); writeOpenClawRegistry("alpha"); diff --git a/test/snapshot.test.ts b/test/snapshot.test.ts index 884bdb4c51e..e9ca322578c 100644 --- a/test/snapshot.test.ts +++ b/test/snapshot.test.ts @@ -20,44 +20,41 @@ vi.mock("../src/lib/adapters/openshell/sandbox-control-routing.js", () => { timeoutMs?: number; stdoutEncoding?: "utf8" | "buffer"; }) => { - if (request.command[0] === "/opt/venv/bin/python3") { - const stagedPath = transport.stagedRemotePaths.get(request.command[6]); - if (stagedPath) fs.rmSync(stagedPath, { force: true }); - return { status: 0, stdout: "KEY_ALLOWLIST_OK\n", stderr: "" }; - } - if (request.command[0] === "python3") { - const command = [...request.command]; - command[3] = transport.stagedRemotePaths.get(command[3]) ?? command[3]; - command[4] = transport.mutationRoot; + const run = (command: string[], binary = false) => { const result = spawnSync(command[0], command.slice(1), { input: request.stdin, maxBuffer: request.maxOutputBytes, timeout: request.timeoutMs, - encoding: "utf8", + encoding: binary ? undefined : "utf8", }); return { status: result.status, - stdout: String(result.stdout ?? ""), + 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 } : {}), }; - } - 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 } : {}), }; + const mergeKeyAllowlist = () => { + const removeStaged = (stagedPath?: string) => + stagedPath && fs.rmSync(stagedPath, { force: true }); + removeStaged(transport.stagedRemotePaths.get(request.command[6])); + return { status: 0, stdout: "KEY_ALLOWLIST_OK\n", stderr: "" }; + }; + const restoreState = () => { + const command = [...request.command]; + command[3] = transport.stagedRemotePaths.get(command[3]) ?? command[3]; + command[4] = transport.mutationRoot; + return run(command); + }; + const readState = () => + run(["ssh", String(request.command.at(-1) ?? "")], request.stdoutEncoding === "buffer"); + return request.command[0] === "/opt/venv/bin/python3" + ? mergeKeyAllowlist() + : request.command[0] === "python3" + ? restoreState() + : readState(); }; return { execSandboxReadOnlyWithGrpcFallback: async ( From 27cec693514ae8c2a1e54da3ba3bbf4804180423 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 14:47:50 -0700 Subject: [PATCH 11/14] fix(openshell): bound failed payload cleanup Signed-off-by: Aaron Erickson --- .../snapshot-restore-lifecycle.test.ts | 60 ++++++++++++++++--- src/lib/adapters/openshell/sandbox-upload.ts | 36 +++++++---- src/lib/state/sandbox-restore-upload.test.ts | 47 ++++++++++++++- src/lib/state/state-file-restore.ts | 2 +- test/legacy-sandbox-transports.test.ts | 7 ++- test/onboard-custom-dockerfile.test.ts | 25 ++++---- test/snapshot-gateway-guard.test.ts | 2 +- 7 files changed, 141 insertions(+), 38 deletions(-) diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index ff244e01b83..bf48c32d65a 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -58,6 +58,29 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { }); it("keeps active-timer restore, permission repair, and policy reconciliation serialized", async () => { + const order: string[] = []; + const lockReleased = vi.fn(() => order.push("lock released")); + const restoredState = { + success: true, + restoredDirs: ["workspace"], + restoredFiles: ["openclaw.json"], + failedDirs: [], + failedFiles: [], + }; + let releaseRestore = () => {}; + const pendingRestore = new Promise((resolve) => { + releaseRestore = () => resolve(restoredState); + }); + f.lifecycleMock.withTimerBoundMock.mockImplementation( + async (_sandboxName, command, operation) => { + f.lifecycleMock.events.push(`lock:${command}`); + try { + return await operation(); + } finally { + lockReleased(); + } + }, + ); f.lifecycleMock.readTimerMarkerMock.mockReturnValue({ pid: 4242, sandboxName: "alpha", @@ -70,21 +93,44 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { backupPath: "/tmp/backup-alpha", policyPresets: ["github"], }); - f.restoreSandboxStateMock.mockReturnValue({ - success: true, - restoredDirs: ["workspace"], - restoredFiles: ["openclaw.json"], - failedDirs: [], - failedFiles: [], + f.restoreSandboxStateMock.mockImplementation(() => { + order.push("restore"); + return pendingRestore; + }); + f.shieldsMock.repairMutableConfigPermsMock.mockImplementation(() => { + order.push("repair permissions"); + return { applied: true, verified: true, errors: [] }; + }); + f.applyPresetMock.mockImplementation(() => { + order.push("reconcile policy"); + return true; }); const { runSandboxSnapshot } = await import("./snapshot"); - await runSandboxSnapshot("alpha", { kind: "restore" }); + const restoreOperation = runSandboxSnapshot("alpha", { kind: "restore" }); + const completion = restoreOperation.then(() => order.push("complete")); + await vi.waitFor(() => expect(f.restoreSandboxStateMock).toHaveBeenCalledOnce()); expect(f.lifecycleMock.events).toContain("lock:restore sandbox snapshot"); expect(f.restoreSandboxStateMock).toHaveBeenCalledWith("alpha", "/tmp/backup-alpha"); + expect(f.shieldsMock.repairMutableConfigPermsMock).not.toHaveBeenCalled(); + expect(f.applyPresetMock).not.toHaveBeenCalled(); + expect(lockReleased).not.toHaveBeenCalled(); + expect(order).toEqual(["restore"]); + + releaseRestore(); + await completion; + expect(f.shieldsMock.repairMutableConfigPermsMock).toHaveBeenCalledWith("alpha"); expect(f.applyPresetMock).toHaveBeenCalledWith("alpha", "github"); + expect(lockReleased).toHaveBeenCalledOnce(); + expect(order).toEqual([ + "restore", + "repair permissions", + "reconcile policy", + "lock released", + "complete", + ]); }); it("hardens an active timer window before force-deleting a restore destination", async () => { diff --git a/src/lib/adapters/openshell/sandbox-upload.ts b/src/lib/adapters/openshell/sandbox-upload.ts index e343ee0d77a..f10b153c75b 100644 --- a/src/lib/adapters/openshell/sandbox-upload.ts +++ b/src/lib/adapters/openshell/sandbox-upload.ts @@ -35,6 +35,7 @@ export const SANDBOX_PAYLOAD_UPLOAD_TIMEOUT_MS = 120_000; export const SANDBOX_PAYLOAD_UPLOAD_MAX_OUTPUT_BYTES = 64 * 1024; export const SANDBOX_PAYLOAD_CLEANUP_TIMEOUT_MS = 30_000; export const SANDBOX_PAYLOAD_CLEANUP_MAX_OUTPUT_BYTES = 64 * 1024; +export const SANDBOX_PAYLOAD_CLEANUP_MAX_ATTEMPTS = 2; export const SANDBOX_PAYLOAD_CLEANUP_OK = "SANDBOX_PAYLOAD_CLEANUP_OK"; const SANDBOX_PAYLOAD_REMOTE_PATH_RE = @@ -249,7 +250,15 @@ export function uploadSandboxPayloadFile( } } -/** Best-effort, non-replaying cleanup for a possibly uploaded private payload. */ +/** + * Bounded, non-replaying cleanup for a possibly uploaded private payload. + * + * The exact-path unlink is idempotent, so an unconfirmed first attempt gets one + * identical cleanup-only recovery attempt. At most two 30-second calls can run; + * this recovery never redispatches the upload or restore operation. + * Remove this recovery when OpenShell provides transactional upload-and-restore, + * a server-confirmed idempotent delete, or lease expiry for staged payloads. + */ export async function cleanupSandboxPayloadAfterFailure( sandboxControl: OpenShellSandboxControl, sandboxName: string, @@ -264,15 +273,20 @@ export async function cleanupSandboxPayloadAfterFailure( maxOutputBytes: SANDBOX_PAYLOAD_CLEANUP_MAX_OUTPUT_BYTES, }; if (validateOpenShellExecRequest(request)) return false; - try { - const result = await sandboxControl.exec(request); - return ( - result.status === 0 && - !result.error && - !result.signal && - result.stdout.trim() === SANDBOX_PAYLOAD_CLEANUP_OK - ); - } catch { - return false; + for (let attempt = 0; attempt < SANDBOX_PAYLOAD_CLEANUP_MAX_ATTEMPTS; attempt += 1) { + try { + const result = await sandboxControl.exec(request); + if ( + result.status === 0 && + !result.error && + !result.signal && + result.stdout.trim() === SANDBOX_PAYLOAD_CLEANUP_OK + ) { + return true; + } + } catch { + // A failed attempt is unconfirmed; the loop remains cleanup-only and bounded above. + } } + return false; } diff --git a/src/lib/state/sandbox-restore-upload.test.ts b/src/lib/state/sandbox-restore-upload.test.ts index 7f8ba05ef8e..bcaac30983f 100644 --- a/src/lib/state/sandbox-restore-upload.test.ts +++ b/src/lib/state/sandbox-restore-upload.test.ts @@ -284,6 +284,47 @@ describe("state directory restore transport boundary", () => { expect(mocks.close).toHaveBeenCalledOnce(); }); + it.each([ + [ + "returns an unconfirmed result", + () => + mocks.exec.mockResolvedValueOnce({ status: 1, stdout: "", stderr: "cleanup unavailable" }), + ], + ["throws", () => mocks.exec.mockRejectedValueOnce(new Error("cleanup unavailable"))], + ])("retries only the exact staged cleanup path when the first attempt %s", async (_label, stageFirstCleanup) => { + const backupPath = writeDirectoryBackup(); + const stagedPaths = new Set(["/tmp/unrelated"]); + mocks.upload.mockImplementation( + (_gateway: string, _sandbox: string, _local: string, remotePath: string) => { + stagedPaths.add(remotePath); + return { ok: true, remotePath }; + }, + ); + mocks.exec.mockResolvedValueOnce({ status: 1, stdout: "", stderr: "restore failed" }); + stageFirstCleanup(); + mocks.exec.mockImplementationOnce(async (request) => { + stagedPaths.delete(String(request.command.at(-1))); + return cleanupCompleted(); + }); + + const result = await restoreRecreatedSandboxState("alpha", backupPath, { + targetAgentType: "fixture", + }); + + const restoreRequests = restoreExecCalls(); + const cleanupRequests = cleanupExecCalls(); + const exactStagedPath = restoreRequests[0]?.[0].command[3]; + expect(result).toMatchObject({ success: false, failedDirs: ["workspace"] }); + expect(restoreRequests).toHaveLength(1); + expect(cleanupRequests).toHaveLength(2); + expect(cleanupRequests[1]?.[0]).toBe(cleanupRequests[0]?.[0]); + expect(cleanupRequests.map(([request]) => request.command.at(-1))).toEqual([ + exactStagedPath, + exactStagedPath, + ]); + expect(stagedPaths).toEqual(new Set(["/tmp/unrelated"])); + }); + it.each([ ["error result", { status: null, stdout: "", stderr: "", error: new Error("unknown") }], ["signal result", { status: null, stdout: "", stderr: "", signal: "SIGTERM" }], @@ -298,7 +339,7 @@ describe("state directory restore transport boundary", () => { expect(result).toMatchObject({ success: false, failedDirs: ["workspace"] }); expect(mocks.upload).toHaveBeenCalledOnce(); expect(restoreExecCalls()).toHaveLength(1); - expect(cleanupExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(2); expect(mocks.close).toHaveBeenCalledOnce(); }); @@ -314,7 +355,7 @@ describe("state directory restore transport boundary", () => { expect(result.error).toContain("dispatch failed"); expect(mocks.upload).toHaveBeenCalledOnce(); expect(restoreExecCalls()).toHaveLength(1); - expect(cleanupExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(2); }); it.each([ @@ -338,7 +379,7 @@ describe("state directory restore transport boundary", () => { failedFiles: ["config.json"], }); expect(restoreExecCalls()).toHaveLength(1); - expect(cleanupExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(2); expect(mocks.upload).toHaveBeenCalledOnce(); }); diff --git a/src/lib/state/state-file-restore.ts b/src/lib/state/state-file-restore.ts index 9e76ff66a89..f76570448a8 100644 --- a/src/lib/state/state-file-restore.ts +++ b/src/lib/state/state-file-restore.ts @@ -507,7 +507,7 @@ export async function restoreStateFile( } const cleanupRemotePayload = async (): Promise => { if (!(await cleanupSandboxPayloadAfterFailure(sandboxControl, sandboxName, remotePath))) { - log(`WARNING: could not confirm cleanup of staged state file ${spec.path}`); + log(`WARNING: could not confirm cleanup of staged state file ${spec.path} at ${remotePath}`); } }; if (!upload.ok) { diff --git a/test/legacy-sandbox-transports.test.ts b/test/legacy-sandbox-transports.test.ts index 5f49b2327bd..3595d7bc9ed 100644 --- a/test/legacy-sandbox-transports.test.ts +++ b/test/legacy-sandbox-transports.test.ts @@ -7,9 +7,9 @@ import path from "node:path"; import { afterEach, describe, expect, it } from "vitest"; import { - REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES, auditLegacySandboxTransports, discoverLegacySandboxTransportSites, + REVIEWED_LEGACY_SANDBOX_TRANSPORT_SITES, } from "../scripts/checks/legacy-sandbox-transports"; const fixtures: string[] = []; @@ -161,6 +161,11 @@ describe("legacy sandbox transport inventory", () => { kind: "grpc-cli-read-only-fallback", calls: 1, }, + { + relativePath: "src/lib/state/openclaw-plugin-restore.ts", + kind: "grpc-cli-read-only-fallback", + calls: 1, + }, { relativePath: "src/lib/state/sandbox.ts", kind: "grpc-cli-read-only-fallback", diff --git a/test/onboard-custom-dockerfile.test.ts b/test/onboard-custom-dockerfile.test.ts index d6998bb45ef..6a5c3432856 100644 --- a/test/onboard-custom-dockerfile.test.ts +++ b/test/onboard-custom-dockerfile.test.ts @@ -186,6 +186,17 @@ describe("onboard custom Dockerfile", () => { fs.mkdirSync(fakeBin, { recursive: true }); writeOkOpenshell(fakeBin); + fs.writeFileSync( + path.join(fakeBin, "openshell"), + [ + "#!/bin/sh", + 'case "$*" in', + ' *"state/openclaw.sqlite"*openclaw.json*) printf \'%s\\n\' \'{"version":1,"installRecords":{},"loadPaths":[]}\' ;;', + "esac", + "exit 0", + ].join("\n"), + { mode: 0o755 }, + ); const gatewayDir = path.join(tmpDir, ".config", "openshell", "gateways", "nemoclaw"); fs.mkdirSync(gatewayDir, { recursive: true }); fs.writeFileSync( @@ -210,20 +221,6 @@ const { EventEmitter } = require("node:events"); const fs = require("node:fs"); const path = require("node:path"); -const originalSpawnSync = childProcess.spawnSync; -childProcess.spawnSync = (command, args, options) => { - const normalized = _n([command, ...(Array.isArray(args) ? args : [])]); - if (String(command).endsWith("openshell") && normalized.includes("sandbox exec") && normalized.includes("installed_plugin_index")) { - return { - status: 0, - signal: null, - stdout: Buffer.from(JSON.stringify({ version: 1, installRecords: {}, loadPaths: [] })), - stderr: Buffer.alloc(0), - }; - } - return originalSpawnSync(command, args, options); -}; - const commands = []; let hasExtraFileAtSpawn = false; let stagedIgnoredFilesAtSpawn = null; diff --git a/test/snapshot-gateway-guard.test.ts b/test/snapshot-gateway-guard.test.ts index d7312fb6edb..e4192bb0bc7 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -178,7 +178,7 @@ function makeVmRestoreToEnv( ` "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 ;;`, // Restore writes config bytes on stdin. Consume them before exiting so the // fake CLI cannot race its caller into a Linux-only EPIPE. - ' "sandbox exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *installed_plugin_index*) printf "{\\"version\\":1,\\"installRecords\\":{},\\"loadPaths\\":[]}" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; cat >/dev/null; exit 0 ;;', + ' "sandbox exec") case "$*" in *NEMOCLAW_DCODE_PROBE*) printf "NEMOCLAW_DCODE_PROBE=no-runtime\\n" ;; *installed_plugin_index*) printf "{\\"version\\":1,\\"installRecords\\":{},\\"loadPaths\\":[]}" ;; *"-- python3 -I - /tmp/nemoclaw-state-restore-"*"/sandbox/.openclaw openclaw.json copy"*) printf "STATE_FILE_OK\\n" ;; *openclaw.json*) printf "{\\"gateway\\":{\\"auth\\":{\\"token\\":\\"fresh\\"}}}" ;; esac; cat >/dev/null; exit 0 ;;', ` "sandbox create") touch ${JSON.stringify(cloneReadyMarker)}; printf "created clone-1\\n"; exit 0 ;;`, "esac", 'if [ "$1" = "status" ]; then exit 0; fi', From 80181a7a08ded3fd8890e5303af223903a8812a9 Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 15:24:21 -0700 Subject: [PATCH 12/14] test(state): model private backup fixtures Signed-off-by: Aaron Erickson --- .../adapters/openshell/sandbox-upload.test.ts | 49 +++++++++++++------ .../state-file-restore-custom-image.test.ts | 8 +-- 2 files changed, 38 insertions(+), 19 deletions(-) diff --git a/src/lib/adapters/openshell/sandbox-upload.test.ts b/src/lib/adapters/openshell/sandbox-upload.test.ts index 143ad1e6c6c..f0521dba54b 100644 --- a/src/lib/adapters/openshell/sandbox-upload.test.ts +++ b/src/lib/adapters/openshell/sandbox-upload.test.ts @@ -84,30 +84,49 @@ describe("OpenShell sandbox payload upload", () => { expect(staged.ok).toBe(true); assert(staged.ok); - expect(fs.statSync(path.dirname(staged.payload.localPath)).mode & 0o777).toBe(0o700); - expect(fs.statSync(staged.payload.localPath).mode & 0o777).toBe(0o600); - expect(fs.readFileSync(staged.payload.localPath)).toEqual(Buffer.from([0x00, 0xff, 0x41])); - staged.payload.cleanup(); + try { + expect(fs.statSync(path.dirname(staged.payload.localPath)).mode & 0o777).toBe(0o700); + const payloadFd = fs.openSync( + staged.payload.localPath, + fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW, + ); + try { + expect(fs.fstatSync(payloadFd).mode & 0o777).toBe(0o600); + expect(fs.readFileSync(payloadFd)).toEqual(Buffer.from([0x00, 0xff, 0x41])); + } finally { + fs.closeSync(payloadFd); + } + } finally { + staged.payload.cleanup(); + } staged.payload.cleanup(); expect(fs.existsSync(staged.payload.localPath)).toBe(false); }); it("removes private staging when the source file cannot be opened", () => { + const trustedSourceRoot = fs.mkdtempSync( + path.join(process.cwd(), ".nemoclaw-sandbox-upload-source-"), + ); + fs.chmodSync(trustedSourceRoot, 0o700); const before = new Set( fs.readdirSync(os.tmpdir()).filter((entry) => entry.startsWith("nemoclaw-state-upload-")), ); - const staged = createPrivateSandboxPayloadFileFromPath( - path.join(os.tmpdir(), `missing-${String(process.pid)}-${String(Date.now())}`), - 1024, - ); - - expect(staged.ok).toBe(false); - expect( - fs - .readdirSync(os.tmpdir()) - .filter((entry) => entry.startsWith("nemoclaw-state-upload-") && !before.has(entry)), - ).toEqual([]); + try { + const staged = createPrivateSandboxPayloadFileFromPath( + path.join(trustedSourceRoot, "missing"), + 1024, + ); + + expect(staged.ok).toBe(false); + expect( + fs + .readdirSync(os.tmpdir()) + .filter((entry) => entry.startsWith("nemoclaw-state-upload-") && !before.has(entry)), + ).toEqual([]); + } finally { + fs.rmSync(trustedSourceRoot, { recursive: true, force: true }); + } }); it("creates unguessable remote paths in the reviewed namespace", () => { diff --git a/src/lib/state/state-file-restore-custom-image.test.ts b/src/lib/state/state-file-restore-custom-image.test.ts index 713f1ca130c..6cef74b5ffb 100644 --- a/src/lib/state/state-file-restore-custom-image.test.ts +++ b/src/lib/state/state-file-restore-custom-image.test.ts @@ -2,7 +2,6 @@ // SPDX-License-Identifier: Apache-2.0 import fs from "node:fs"; -import os from "node:os"; import path from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -49,7 +48,8 @@ const ownership: StateFileKeyAllowlistRestoreOwnership = { }; function createBackupFixture(): { backupPath: string; backupContents: Buffer } { - const backupPath = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-custom-state-")); + const backupPath = fs.mkdtempSync(path.join(process.cwd(), ".nemoclaw-custom-state-")); + fs.chmodSync(backupPath, 0o700); fixtures.push(backupPath); const backupContents = Buffer.from( '[models]\ndefault = "backup-owned"\n\n[ui]\nshow_scrollbar = true\n', @@ -237,7 +237,7 @@ describe("custom-image state-file restore capability (#6334)", () => { expect(restored).toBe(false); expect(mocks.upload).toHaveBeenCalledOnce(); expect(restoreExecCalls()).toHaveLength(1); - expect(cleanupExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(2); }); it("rejects status zero without the fixed success sentinel", async () => { @@ -264,7 +264,7 @@ describe("custom-image state-file restore capability (#6334)", () => { expect(restored).toBe(false); expect(mocks.upload).toHaveBeenCalledOnce(); expect(restoreExecCalls()).toHaveLength(1); - expect(cleanupExecCalls()).toHaveLength(1); + expect(cleanupExecCalls()).toHaveLength(2); }); it("does not dispatch after a state-file upload failure", async () => { From 94c7f634a9ca0e022cde9e94100dd6fd6709822e Mon Sep 17 00:00:00 2001 From: Aaron Erickson Date: Tue, 14 Jul 2026 16:19:03 -0700 Subject: [PATCH 13/14] test(state): cover reconciliation tolerance Signed-off-by: Aaron Erickson --- .../rebuild-restore-forwarding.test.ts | 15 +++++- .../snapshot-restore-lifecycle.test.ts | 51 +++++++++++++++++++ 2 files changed, 64 insertions(+), 2 deletions(-) diff --git a/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts b/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts index 0ca949ffef2..fab2dfac224 100644 --- a/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts +++ b/src/lib/actions/sandbox/rebuild-restore-forwarding.test.ts @@ -1,17 +1,28 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 +import fs from "node:fs"; +import path from "node:path"; + import { afterEach, describe, expect, it, vi } from "vitest"; import * as sandboxState from "../../state/sandbox"; import { runRebuildRestorePhase } from "./rebuild-restore-phase"; +const fixtures: string[] = []; + afterEach(() => { + for (const fixture of fixtures.splice(0)) { + fs.rmSync(fixture, { recursive: true, force: true }); + } vi.restoreAllMocks(); }); describe("rebuild restore target forwarding", () => { it("forwards the recreated target identity and explicit custom-image capability", async () => { + const backupPath = fs.mkdtempSync(path.join(process.cwd(), ".nemoclaw-rebuild-restore-")); + fs.chmodSync(backupPath, 0o700); + fixtures.push(backupPath); vi.spyOn(console, "log").mockImplementation(() => undefined); const restoreRecreatedSandboxState = vi .spyOn(sandboxState, "restoreRecreatedSandboxState") @@ -27,14 +38,14 @@ describe("rebuild restore target forwarding", () => { sandboxName: "alpha", targetAgentType: "langchain-deepagents-code", targetImageIsCustom: true, - backupManifest: { agentType: "openclaw", backupPath: "/tmp/rebuild-backup" } as never, + backupManifest: { agentType: "openclaw", backupPath } as never, policyPresets: [], customPolicies: [], reconcileManagedDcodeObservability: false, log: vi.fn(), }); - expect(restoreRecreatedSandboxState).toHaveBeenCalledWith("alpha", "/tmp/rebuild-backup", { + expect(restoreRecreatedSandboxState).toHaveBeenCalledWith("alpha", backupPath, { targetAgentType: "langchain-deepagents-code", allowCustomImageWholeStateFileRestore: true, }); diff --git a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts index bf48c32d65a..fc2f75a9b8f 100644 --- a/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts +++ b/src/lib/actions/sandbox/snapshot-restore-lifecycle.test.ts @@ -34,6 +34,57 @@ describe("runSandboxSnapshot restore: lifecycle and destination safety", () => { expect(output).toContain("Restored 1 directories, 1 files"); }); + it("keeps a successful restore when every post-restore reconciliation warns", async () => { + const consoleLog = vi.spyOn(console, "log").mockImplementation(() => {}); + const consoleWarn = vi.spyOn(console, "warn").mockImplementation(() => {}); + const customPolicy = { + name: "corp-policy", + content: "network_policies:\n corp-policy: {}\n", + sourcePath: "/policies/corp-policy.yaml", + }; + f.getLatestBackupMock.mockReturnValue({ + timestamp: "2026-06-15T00:00:00.000Z", + backupPath: "/tmp/backup-alpha", + policyPresets: ["github", customPolicy.name], + customPolicies: [customPolicy], + }); + f.restoreSandboxStateMock.mockResolvedValue({ + success: true, + restoredDirs: ["workspace"], + restoredFiles: ["openclaw.json"], + failedDirs: [], + failedFiles: [], + }); + f.shieldsMock.repairMutableConfigPermsMock.mockImplementation(() => { + throw new Error("permission repair failed"); + }); + f.applyPresetContentMock.mockImplementation(() => { + throw new Error("custom replay failed"); + }); + f.applyPresetMock.mockImplementation(() => { + throw new Error("preset reconciliation failed"); + }); + const { runSandboxSnapshot } = await import("./snapshot"); + + await expect(runSandboxSnapshot("alpha", { kind: "restore" })).resolves.toBeUndefined(); + + expect(f.shieldsMock.repairMutableConfigPermsMock).toHaveBeenCalledWith("alpha"); + expect(f.applyPresetContentMock).toHaveBeenCalledWith( + "alpha", + customPolicy.name, + customPolicy.content, + { custom: { sourcePath: customPolicy.sourcePath } }, + ); + expect(f.applyPresetMock).toHaveBeenCalledWith("alpha", "github"); + expect(consoleLog.mock.calls.flat().join("\n")).toContain("Restored 1 directories, 1 files"); + const warnings = consoleWarn.mock.calls.flat().join("\n"); + expect(warnings).toContain( + "OpenClaw config permission repair errored: permission repair failed", + ); + expect(warnings).toContain("corp-policy (apply: custom replay failed)"); + expect(warnings).toContain("github (apply: preset reconciliation failed)"); + }); + it("delegates managed and custom-image snapshot restores to the state layer", async () => { f.getLatestBackupMock.mockReturnValue({ snapshotVersion: 4, From 901e2f9a1c77676e83e579b0e2f10a677457270d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Aaron=20Erickson=20=F0=9F=A6=9E?= Date: Sat, 18 Jul 2026 16:39:06 -0700 Subject: [PATCH 14/14] refactor(openshell): remove obsolete SSH classifier (#6803) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Deletes the state-layer SSH-only failure classifier that has no remaining production caller after backup and restore migration, while preserving OpenShell remote exit-code semantics. This is PR 11 of 21 in the OpenShell gRPC migration stack. ## Changes - Remove the unused classifier and its public re-export. - Delete classifier-only unit tests. - Document and test that a non-null OpenShell remote exit code, including 255, is an application result rather than transport-failure evidence. - Add no replacement compatibility code. ## Stack - Stack index: https://github.com/NVIDIA/NemoClaw/pull/6790 - Depends on: https://github.com/NVIDIA/NemoClaw/pull/6802 - Review this PR against base branch `refactor/openshell-grpc-state-restore/ae` to see only this slice. ## Type of Change - [x] Code change (feature, bug fix, or refactor) - [ ] Code change with doc updates - [ ] Doc only (prose changes, no code sample modifications) - [ ] Doc only (includes code sample changes) ## Quality Gates - [x] Tests added or updated for changed behavior - [ ] Existing tests cover changed behavior — justification: - [ ] Tests not applicable — justification: - [x] Docs not applicable — justification: this slice changes only internal transport implementation or tests. - [x] Sensitive paths changed (security, policy, credentials, preflight, onboarding, inference, runner, sandbox, or messaging) - [x] Sensitive-path review completed or maintainer-approved waiver recorded — reviewer/approval link/justification: transport-boundary self-review completed; mutations select one transport before dispatch and are never replayed automatically. - [ ] Non-success, skipped, or missing CI check accepted by maintainer — check name, approval link, and follow-up issue: ## Verification - [x] PR description includes the DCO sign-off declaration and every commit appears as `Verified` in GitHub - [x] Normal `pre-commit`, `commit-msg`, and `pre-push` hooks passed, or `npm run check:diff` passed when hooks were skipped or unavailable - [x] Targeted behavior tests pass for the current change set, or tests are marked not applicable above — direct gRPC and CLI adapter tests preserve remote exit 255; typecheck, repository checks, build, and exact-head hooks passed - [ ] Applicable broad gate passed — targeted and changed-graph tests were used; CI will run the repository-required broad gates - [x] Quality Gates section completed with required justifications or waivers - [x] No secrets, API keys, or credentials committed - [ ] `npm run docs` builds without warnings (doc changes only) — not applicable - [ ] Doc pages follow the [style guide](https://github.com/NVIDIA/NemoClaw/blob/main/docs/CONTRIBUTING.md) (doc changes only) - [ ] New doc pages include SPDX header and frontmatter (new pages only) --- Signed-off-by: Aaron Erickson --------- Signed-off-by: Aaron Erickson --- .../openshell/grpc-sandbox-control.test.ts | 6 +-- .../openshell/sandbox-control.test.ts | 6 +-- src/lib/state/sandbox-backup-grpc.test.ts | 8 ++-- .../state/sandbox-state-file-backup.test.ts | 28 +++++++++++++ src/lib/state/sandbox.ts | 8 ++-- src/lib/state/ssh-transport.test.ts | 42 ------------------- src/lib/state/ssh-transport.ts | 33 --------------- 7 files changed, 42 insertions(+), 89 deletions(-) delete mode 100644 src/lib/state/ssh-transport.test.ts delete mode 100644 src/lib/state/ssh-transport.ts diff --git a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts index 081a121f12d..242d271459b 100644 --- a/src/lib/adapters/openshell/grpc-sandbox-control.test.ts +++ b/src/lib/adapters/openshell/grpc-sandbox-control.test.ts @@ -205,7 +205,7 @@ describe("gRPC OpenShell sandbox control", () => { ).toEqual(["printf", boundaryArgument]); }); - it("resolves a sandbox id and normalizes streamed output", async () => { + it("resolves a sandbox id and preserves exit status 255 with normalized output", async () => { const euro = Buffer.from("€"); const fake = fakeApi({ emit(stream) { @@ -213,7 +213,7 @@ describe("gRPC OpenShell sandbox control", () => { stream.emit("data", { stdout: { data: euro.subarray(0, 1) } }); stream.emit("data", { stdout: { data: euro.subarray(1) } }); stream.emit("data", { stderr: { data: Buffer.from("warning\n") } }); - stream.emit("data", { exit: { exitCode: 7 } }); + stream.emit("data", { exit: { exitCode: 255 } }); stream.emit("end"); }, }); @@ -229,7 +229,7 @@ describe("gRPC OpenShell sandbox control", () => { stdin: "request body", }), ).resolves.toEqual({ - status: 7, + status: 255, stdout: "hello €", stderr: "warning\n", }); diff --git a/src/lib/adapters/openshell/sandbox-control.test.ts b/src/lib/adapters/openshell/sandbox-control.test.ts index 55131e2ce1a..98c1f58c6ab 100644 --- a/src/lib/adapters/openshell/sandbox-control.test.ts +++ b/src/lib/adapters/openshell/sandbox-control.test.ts @@ -226,10 +226,10 @@ describe("OpenShell exec request validation", () => { }); describe("CLI OpenShell sandbox control", () => { - it("maps a typed exec request to the existing CLI contract", async () => { + it("maps a typed exec request and preserves exit status 255", async () => { const capture = vi.fn( (): CaptureOpenshellBinaryResult => ({ - status: 0, + status: 255, stdout: Buffer.from("hello\n"), stderr: Buffer.from("warning\n"), }), @@ -253,7 +253,7 @@ describe("CLI OpenShell sandbox control", () => { }, ); expect(result).toEqual({ - status: 0, + status: 255, stdout: "hello\n", stderr: "warning\n", }); diff --git a/src/lib/state/sandbox-backup-grpc.test.ts b/src/lib/state/sandbox-backup-grpc.test.ts index 8b684641f93..7f8e7de89cf 100644 --- a/src/lib/state/sandbox-backup-grpc.test.ts +++ b/src/lib/state/sandbox-backup-grpc.test.ts @@ -510,9 +510,9 @@ describe("backupSandboxState OpenShell directory transport", () => { }); 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) => { + ["transport error", { error: new Error("sandbox exec stream reset") }, true], + ["stale signal", { signal: "SIGTERM" as const }, false], + ])("rejects tar bytes returned with a %s even when tar reports success", async (_failureKind, transportFailure, expectedUnreachable) => { const { archive } = createBinaryTarArchive(); queueSuccessfulProbeAndAudit(); mocks.execSandboxReadOnlyWithGrpcFallback.mockResolvedValueOnce({ @@ -525,7 +525,7 @@ describe("backupSandboxState OpenShell directory transport", () => { expect(result).toMatchObject({ success: false, - unreachable: true, + unreachable: expectedUnreachable, backedUpDirs: [], failedDirs: ["state"], }); diff --git a/src/lib/state/sandbox-state-file-backup.test.ts b/src/lib/state/sandbox-state-file-backup.test.ts index bed1677fba1..6df3afb1891 100644 --- a/src/lib/state/sandbox-state-file-backup.test.ts +++ b/src/lib/state/sandbox-state-file-backup.test.ts @@ -166,12 +166,40 @@ describe("state-file backup exec request", () => { expect(isSandboxExecTransportFailure({ status: null, error: outputLimit })).toBe(false); expect(isSandboxExecTransportFailure({ status: null, error: invalidRequest })).toBe(false); + expect(isSandboxExecTransportFailure({ status: 255 })).toBe(false); + expect(isSandboxExecTransportFailure({ status: 0, signal: "SIGKILL" })).toBe(false); + expect(isSandboxExecTransportFailure({ status: 1, signal: "SIGINT" })).toBe(false); + expect(isSandboxExecTransportFailure({ status: null })).toBe(true); expect(isSandboxExecTransportFailure({ status: null, error: new Error("UNAVAILABLE") })).toBe( true, ); expect(isSandboxExecTransportFailure({ status: null, signal: "SIGKILL" })).toBe(true); }); + it.each([ + ["a non-zero status", "terminal-status", { status: 255, stdout: "", stderr: "" }], + [ + "a terminal signal", + "terminal-signal", + { status: 0, stdout: "", stderr: "", signal: "SIGKILL" as const }, + ], + ])("keeps state-file backup failure from %s reachable without persisting bytes", async (_failureKind, backupName, execResult) => { + execReadOnly.mockResolvedValue(execResult); + + const result = await backupSandboxState("hermes", { name: backupName }); + + expect(result).toMatchObject({ + success: false, + backedUpFiles: [], + failedFiles: ["runtime/state.db"], + unreachable: false, + }); + expect(execReadOnly).toHaveBeenCalledTimes(1); + expect(fs.existsSync(path.join(result.manifest!.backupPath, "runtime", "state.db"))).toBe( + false, + ); + }); + 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({ diff --git a/src/lib/state/sandbox.ts b/src/lib/state/sandbox.ts index 5b63b4583a3..80e00bf2522 100644 --- a/src/lib/state/sandbox.ts +++ b/src/lib/state/sandbox.ts @@ -1081,9 +1081,11 @@ export function isSandboxExecTransportFailure(result: { 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. + // repaired by retrying or by treating the sandbox as unreachable. OpenShell + // status 255 and stale signal fields are terminal remote results, not SSH + // transport conventions. if (code === "ENOBUFS" || code === "OPENSHELL_EXEC_INVALID_ARGUMENT") return false; - return Boolean(result.error || result.signal || result.status === null); + return Boolean(result.error || result.status === null); } /** @internal Pin the binary state-file result contract independently of filesystem writes. */ @@ -1146,8 +1148,6 @@ async function backupStateFile( * Uses the agent manifest to determine which directories contain state. */ -export { isSshTransportFailure } from "./ssh-transport.js"; - export async function backupSandboxState( sandboxName: string, options: BackupOptions = {}, diff --git a/src/lib/state/ssh-transport.test.ts b/src/lib/state/ssh-transport.test.ts deleted file mode 100644 index b982bbcbc01..00000000000 --- a/src/lib/state/ssh-transport.test.ts +++ /dev/null @@ -1,42 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -import { describe, expect, it } from "vitest"; - -import { isSshTransportFailure } from "./ssh-transport"; - -describe("isSshTransportFailure", () => { - it("treats an ssh transport failure exit code (255) as unreachable", () => { - expect(isSshTransportFailure({ status: 255 })).toBe(true); - }); - - it("treats a timed-out or signal-killed probe (null status) as unreachable", () => { - expect(isSshTransportFailure({ status: null })).toBe(true); - }); - - it("treats a spawn error as unreachable", () => { - expect(isSshTransportFailure({ status: null, error: new Error("spawn ETIMEDOUT") })).toBe(true); - }); - - it("does not treat a reachable non-zero remote exit as unreachable", () => { - expect(isSshTransportFailure({ status: 1 })).toBe(false); - expect(isSshTransportFailure({ status: 2 })).toBe(false); - }); - - it("does not treat a successful probe as unreachable", () => { - expect(isSshTransportFailure({ status: 0 })).toBe(false); - }); - - it("treats SIGHUP/SIGPIPE terminated probes as transport failures", () => { - // spawnSync surfaces signal-killed processes with status=null + signal set. - // Match connect.ts by naming the transport-level signals explicitly. - expect(isSshTransportFailure({ status: null, signal: "SIGHUP" })).toBe(true); - expect(isSshTransportFailure({ status: null, signal: "SIGPIPE" })).toBe(true); - }); - - it("does not treat a reachable exit accompanied by a benign signal as unreachable", () => { - // A remote exit-1 with a stale/benign signal field must still be classified - // by exit code, not by the signal field. - expect(isSshTransportFailure({ status: 1, signal: "SIGINT" })).toBe(false); - }); -}); diff --git a/src/lib/state/ssh-transport.ts b/src/lib/state/ssh-transport.ts deleted file mode 100644 index 4f1bbb14165..00000000000 --- a/src/lib/state/ssh-transport.ts +++ /dev/null @@ -1,33 +0,0 @@ -// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. -// SPDX-License-Identifier: Apache-2.0 - -/** - * Pure classifiers for SSH probe outcomes into transport-level failures - * (unreachable) vs application-level failures (reachable but exit-non-zero). - * - * A "transport-level" failure means the SSH tunnel itself could not carry - * data — the process never reached a shell that could return a real exit - * code. Typical shapes reported by `spawnSync("ssh", …)`: - * - * - `error` set on the result (spawn-time failure: ENOENT, EACCES, …) - * - `status === 255` (ssh's own transport-error convention) - * - `status === null` with a signal (killed by SIGHUP/SIGPIPE from a - * dying gateway) or with no signal (timed out / SIGTERM) - * - * Callers use this to promote a sandbox-level `unreachable` flag so the - * NEMOCLAW_SKIP_UNREACHABLE_SANDBOX_BACKUP=1 opt-in can activate. See #6188. - */ -export function isSshTransportFailure(result: { - status: number | null; - error?: Error; - signal?: NodeJS.Signals | null; -}): boolean { - if (result.error) return true; - // Signal termination (e.g. SIGHUP/SIGPIPE from a dying gateway) reports - // status=null; match connect.ts and treat these as transport-level - // failures explicitly so the diagnostic path is unambiguous. Any other - // null-status result (timeout, killed) is also transport-level. - if (result.signal === "SIGHUP" || result.signal === "SIGPIPE") return true; - if (result.status === null) return true; - return result.status === 255; -}