diff --git a/src/lib/actions/sandbox/rebuild-config-hash-command.ts b/src/lib/actions/sandbox/rebuild-config-hash-command.ts index 1490fb18a09..f1d87ad6826 100644 --- a/src/lib/actions/sandbox/rebuild-config-hash-command.ts +++ b/src/lib/actions/sandbox/rebuild-config-hash-command.ts @@ -15,9 +15,9 @@ export function buildRefreshMutableOpenClawConfigHashCommand( '[ ! -L "$config_file" ] || { echo "refusing symlinked OpenClaw config file: $config_file" >&2; exit 11; }', '[ ! -L "$hash_file" ] || { echo "refusing symlinked OpenClaw config hash: $hash_file" >&2; exit 12; }', 'owner="$(stat -c "%U" "$config_dir" 2>/dev/null || echo unknown)"', - '[ "$owner" != "root" ] || exit 0', '[ -f "$config_file" ] || exit 0', 'cd "$config_dir" || exit 13', + '[ "$owner" != "root" ] || { expected_hash="$(sha256sum openclaw.json 2>/dev/null)" && actual_hash="$(cat .config-hash 2>/dev/null)" && [ "$actual_hash" = "$expected_hash" ] || { echo "root-owned OpenClaw config hash does not match openclaw.json" >&2; exit 15; }; exit 0; }', "sha256sum openclaw.json > .config-hash || exit 14", "chmod 660 .config-hash 2>/dev/null || true", ].join("; "); diff --git a/src/lib/actions/sandbox/rebuild-config-hash.test.ts b/src/lib/actions/sandbox/rebuild-config-hash.test.ts index 6b9978c3b2c..d3b3421e55d 100644 --- a/src/lib/actions/sandbox/rebuild-config-hash.test.ts +++ b/src/lib/actions/sandbox/rebuild-config-hash.test.ts @@ -26,6 +26,13 @@ function runRefresh( }); } +function installRootOwnerStat(binDir: string): void { + const statCommand = path.join(binDir, "stat"); + fs.mkdirSync(binDir, { recursive: true }); + fs.writeFileSync(statCommand, "#!/bin/sh\nprintf '%s\\n' root\n"); + fs.chmodSync(statCommand, 0o755); +} + describe.skipIf(process.platform !== "linux")("OpenClaw rebuild config hash refresh", () => { it("refreshes .config-hash for the current openclaw.json", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-rebuild-hash-")); @@ -47,6 +54,55 @@ describe.skipIf(process.platform !== "linux")("OpenClaw rebuild config hash refr } }); + it.each([ + { + title: "rejects a stale hash when the config directory is root-owned (#9530)", + initialHash: () => `${"0".repeat(64)} openclaw.json\n`, + expectedStatus: 15, + expectedStderr: "root-owned OpenClaw config hash does not match openclaw.json\n", + }, + { + title: "accepts a matching hash when the config directory is root-owned (#9530)", + initialHash: (configPath: string) => `${sha256Hex(configPath)} openclaw.json\n`, + expectedStatus: 0, + expectedStderr: "", + }, + { + title: "rejects a valid hash that names another file in a root-owned directory (#9530)", + initialHash: (configPath: string) => { + const decoyPath = path.join(path.dirname(configPath), "decoy.json"); + fs.writeFileSync(decoyPath, '{"decoy":true}\n'); + return `${sha256Hex(decoyPath)} decoy.json\n`; + }, + expectedStatus: 15, + expectedStderr: "root-owned OpenClaw config hash does not match openclaw.json\n", + }, + ])("$title", ({ initialHash, expectedStatus, expectedStderr }) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-rebuild-root-hash-")); + const configDir = path.join(tmpDir, ".openclaw"); + const binDir = path.join(tmpDir, "bin"); + const configPath = path.join(configDir, "openclaw.json"); + const hashPath = path.join(configDir, ".config-hash"); + try { + fs.mkdirSync(configDir, { recursive: true }); + fs.writeFileSync(configPath, '{"gateway":{"auth":{"token":"fresh"}}}\n'); + const expectedHash = initialHash(configPath); + fs.writeFileSync(hashPath, expectedHash); + installRootOwnerStat(binDir); + + const result = runRefresh(configDir, { + ...process.env, + PATH: `${binDir}:${process.env.PATH ?? ""}`, + }); + + expect(result.status).toBe(expectedStatus); + expect(result.stderr).toBe(expectedStderr); + expect(fs.readFileSync(hashPath, "utf-8")).toBe(expectedHash); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + it("refuses to refresh through a symlinked config file", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-rebuild-hash-symlink-")); const configDir = path.join(tmpDir, ".openclaw"); diff --git a/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts b/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts index 7cb6c275441..2d3fb270307 100644 --- a/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts +++ b/src/lib/actions/sandbox/rebuild-flow-recovery.test.ts @@ -18,7 +18,6 @@ import { describe("rebuildSandbox flow: recovery", () => { installRebuildFlowTestHooks(); - it("uses marked manifest provenance when the custom-image registry baseline is missing (#6108)", async () => { const customDockerfile = path.join(process.cwd(), "Dockerfile"); const recoveryManifest = { @@ -55,12 +54,6 @@ describe("rebuildSandbox flow: recovery", () => { ); }); - - - - - - it("keeps an explicit default choice made while the replacement was in flight (#7734)", async () => { let harness!: ReturnType; harness = createRebuildFlowHarness({ @@ -167,32 +160,34 @@ describe("rebuildSandbox flow: recovery", () => { return restarted; } - it.each( - POST_DELETE_PHASES, - )("keeps a registered replacement when a rebuild restarts from '%s' (#7734)", async (phase) => { - const restarted = restartRebuild(REPLACEMENT_PROBE, await interruptAfterCreate(phase)); + it.each(POST_DELETE_PHASES)( + "keeps a registered replacement when a rebuild restarts from '%s' (#7734)", + async (phase) => { + const restarted = restartRebuild(REPLACEMENT_PROBE, await interruptAfterCreate(phase)); - await restarted.rebuildSandbox("alpha", ["--yes"]); + await restarted.rebuildSandbox("alpha", ["--yes"]); - expectNoSandboxDelete(restarted.runOpenshellSpy); - expect(restarted.onboardSpy).not.toHaveBeenCalled(); - expect( - (restarted.session.checkpoint as { sandboxRecreate: unknown }).sandboxRecreate, - ).toBeNull(); - }); + expectNoSandboxDelete(restarted.runOpenshellSpy); + expect(restarted.onboardSpy).not.toHaveBeenCalled(); + expect( + (restarted.session.checkpoint as { sandboxRecreate: unknown }).sandboxRecreate, + ).toBeNull(); + }, + ); - it.each( - POST_DELETE_PHASES, - )("refuses a foreign same-name sandbox when a rebuild restarts from '%s' (#7734)", async (phase) => { - const restarted = restartRebuild(FOREIGN_PROBE, await interruptAfterCreate(phase)); + it.each(POST_DELETE_PHASES)( + "refuses a foreign same-name sandbox when a rebuild restarts from '%s' (#7734)", + async (phase) => { + const restarted = restartRebuild(FOREIGN_PROBE, await interruptAfterCreate(phase)); - await expect(restarted.rebuildSandbox("alpha", ["--yes"])).rejects.toThrow( - /not the journaled replacement/, - ); + await expect(restarted.rebuildSandbox("alpha", ["--yes"])).rejects.toThrow( + /not the journaled replacement/, + ); - expectNoSandboxDelete(restarted.runOpenshellSpy); - expect(restarted.onboardSpy).not.toHaveBeenCalled(); - }); + expectNoSandboxDelete(restarted.runOpenshellSpy); + expect(restarted.onboardSpy).not.toHaveBeenCalled(); + }, + ); const SOURCE_PROBE = "Name: alpha\nId: sbx-source\nPhase: Ready\n"; const MISSING_SOURCE = { @@ -242,65 +237,69 @@ describe("rebuildSandbox flow: recovery", () => { return restarted; } - it.each( - LIVE_SOURCE_PHASES, - )("deletes the journaled source when a rebuild restarts from '%s' (#7734)", async (phase) => { - const restarted = restartFromJournaledSource( - [SOURCE_PROBE, SOURCE_PROBE, null], - await interruptBeforeCreate(phase), - ); - - await restarted.rebuildSandbox("alpha", ["--yes"]); - - expect(restarted.runOpenshellSpy).toHaveBeenCalledWith( - ["sandbox", "delete", "-g", "nemoclaw", "alpha"], - expect.objectContaining({ ignoreError: true }), - ); - expect(restarted.onboardSpy).toHaveBeenCalled(); - }); - - it.each( - PRE_CREATE_PHASES, - )("creates the replacement without a second delete when a rebuild restarts from '%s' with the source already absent (#7734)", async (phase) => { - const restarted = restartFromJournaledSource([null], await interruptBeforeCreate(phase)); - - await restarted.rebuildSandbox("alpha", ["--yes"]); - - expectNoSandboxDelete(restarted.runOpenshellSpy); - expect(restarted.onboardSpy).toHaveBeenCalled(); - }); - - it.each( - LIVE_SOURCE_PHASES, - )("stops before deletion when a same-name sandbox appears after a '%s' restart probe (#7734)", async (phase) => { - const restarted = restartFromJournaledSource( - [null, FOREIGN_PROBE], - await interruptBeforeCreate(phase), - ); - - await expect( - restarted.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).rejects.toThrow(/the live same-name sandbox is not the journaled source/); - - expectNoSandboxDelete(restarted.runOpenshellSpy); - expect(restarted.onboardSpy).not.toHaveBeenCalled(); - }); + it.each(LIVE_SOURCE_PHASES)( + "deletes the journaled source when a rebuild restarts from '%s' (#7734)", + async (phase) => { + const restarted = restartFromJournaledSource( + [SOURCE_PROBE, SOURCE_PROBE, null], + await interruptBeforeCreate(phase), + ); + + await restarted.rebuildSandbox("alpha", ["--yes"]); + + expect(restarted.runOpenshellSpy).toHaveBeenCalledWith( + ["sandbox", "delete", "-g", "nemoclaw", "alpha"], + expect.objectContaining({ ignoreError: true }), + ); + expect(restarted.onboardSpy).toHaveBeenCalled(); + }, + ); - it.each( - LIVE_SOURCE_PHASES, - )("refuses a changed same-name sandbox when a rebuild restarts from '%s' (#7734)", async (phase) => { - const restarted = restartFromJournaledSource( - [FOREIGN_PROBE, null], - await interruptBeforeCreate(phase), - ); + it.each(PRE_CREATE_PHASES)( + "creates the replacement without a second delete when a rebuild restarts from '%s' with the source already absent (#7734)", + async (phase) => { + const restarted = restartFromJournaledSource([null], await interruptBeforeCreate(phase)); - await expect(restarted.rebuildSandbox("alpha", ["--yes"])).rejects.toThrow( - /no longer has the journaled source identity/, - ); + await restarted.rebuildSandbox("alpha", ["--yes"]); - expectNoSandboxDelete(restarted.runOpenshellSpy); - expect(restarted.onboardSpy).not.toHaveBeenCalled(); - }); + expectNoSandboxDelete(restarted.runOpenshellSpy); + expect(restarted.onboardSpy).toHaveBeenCalled(); + }, + ); + + it.each(LIVE_SOURCE_PHASES)( + "stops before deletion when a same-name sandbox appears after a '%s' restart probe (#7734)", + async (phase) => { + const restarted = restartFromJournaledSource( + [null, FOREIGN_PROBE], + await interruptBeforeCreate(phase), + ); + + await expect( + restarted.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), + ).rejects.toThrow(/the live same-name sandbox is not the journaled source/); + + expectNoSandboxDelete(restarted.runOpenshellSpy); + expect(restarted.onboardSpy).not.toHaveBeenCalled(); + }, + ); + + it.each(LIVE_SOURCE_PHASES)( + "refuses a changed same-name sandbox when a rebuild restarts from '%s' (#7734)", + async (phase) => { + const restarted = restartFromJournaledSource( + [FOREIGN_PROBE, null], + await interruptBeforeCreate(phase), + ); + + await expect(restarted.rebuildSandbox("alpha", ["--yes"])).rejects.toThrow( + /no longer has the journaled source identity/, + ); + + expectNoSandboxDelete(restarted.runOpenshellSpy); + expect(restarted.onboardSpy).not.toHaveBeenCalled(); + }, + ); it("refuses a live same-name sandbox when a rebuild restarts from 'deleted' (#7734)", async () => { const restarted = restartFromJournaledSource( @@ -542,7 +541,7 @@ describe("rebuildSandbox flow: recovery", () => { ).toBeGreaterThan(harness.onboardSpy.mock.invocationCallOrder[0]); }); - it("finishes the rebuild while surfacing incomplete post-restore work", async () => { + it("fails the rebuild while surfacing incomplete OpenClaw post-restore work", async () => { const harness = createRebuildFlowHarness({ sandboxEntry: { policyPresetsFinalized: true, policyTier: "balanced" }, executeSandboxCommand: () => ({ status: 1, stdout: "", stderr: "hash refresh failed" }), @@ -562,7 +561,7 @@ describe("rebuildSandbox flow: recovery", () => { await expect( harness.rebuildSandbox("alpha", ["--yes"], { throwOnError: true }), - ).resolves.toBeUndefined(); + ).rejects.toThrow("OpenClaw config integrity verification failed after rebuild"); const output = harness.logSpy.mock.calls.map((call) => String(call[0])).join("\n"); expect(output).toContain("rebuilt but some post-restore steps were incomplete"); diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts index 33eb2a60368..10c89cf87ca 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.test.ts @@ -84,6 +84,7 @@ describe("rebuild post-restore phase", () => { vi.spyOn(registry, "getSandbox").mockImplementation( () => ({ agent: agentName === "openclaw" ? null : agentName }) as never, ); + vi.spyOn(registry, "getBaselineExclusions").mockReturnValue([]); vi.spyOn(registry, "updateSandbox").mockReturnValue(true); vi.spyOn(messagingHostForward, "ensureMessagingHostForwardAfterRebuild").mockReturnValue(true); }); @@ -123,6 +124,28 @@ describe("rebuild post-restore phase", () => { expect(order).toEqual(["doctor", "reconcile", "messaging", "config-hash"]); }); + it("fails when doctor returns 255 and the final OpenClaw config hash is unverified (#9530)", async () => { + vi.mocked(processRecovery.executeSandboxCommand).mockReturnValue({ + status: 255, + stdout: "", + stderr: "", + }); + vi.mocked( + rebuildConfigHash.refreshMutableOpenClawConfigHashAfterPostRestoreWrites, + ).mockReturnValue(false); + const args = input(); + + await runRebuildPostRestorePhase(args); + + expect(args.relockShieldsIfNeeded).toHaveBeenCalledWith(true); + expect(args.bail).toHaveBeenCalledWith( + "OpenClaw config integrity verification failed after rebuild.", + ); + expect(vi.mocked(console.log).mock.calls.flat().join("\n")).not.toContain( + "rebuilt successfully", + ); + }); + it("does not run OpenClaw session reconciliation for another agent (#7102)", async () => { agentName = "hermes"; const args = input(); diff --git a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts index 74c14dbe47f..82d196f3437 100644 --- a/src/lib/actions/sandbox/rebuild-post-restore-phase.ts +++ b/src/lib/actions/sandbox/rebuild-post-restore-phase.ts @@ -465,6 +465,10 @@ export async function runRebuildPostRestorePhase( bail(`Rebuild completed with unverified live policy reconciliation for '${sandboxName}'.`); return; } + if (targetAgentName === "openclaw" && mutableConfigHashRefreshUnverified) { + bail("OpenClaw config integrity verification failed after rebuild."); + return; + } if ( targetAgentName === "hermes" && (hermesGatewayRestoreUnverified || mcpBridgeRestoreUnverified)