From 212196a62149a16ecfe7f43a5b4505945faf642f Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sun, 26 Jul 2026 22:24:01 -0700 Subject: [PATCH 01/14] fix(restore): restart gateway after pairing approval Signed-off-by: Carlos Villela --- .../sandbox/restore-gateway-pairing.test.ts | 53 +++++++++++++------ .../sandbox/restore-gateway-pairing.ts | 21 ++++---- 2 files changed, 49 insertions(+), 25 deletions(-) diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index 2be59c268ca..98e7a692d44 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -13,7 +13,7 @@ afterEach(() => { }); describe("establishRestoredSandboxGatewayPairing", () => { - it("restarts the restored gateway before provoking and approving the scope upgrade (#7431)", async () => { + it("restarts the restored gateway before warm-up and after approval (#7431)", async () => { const order: string[] = []; const restartRestoredSandboxGateway = vi.fn(() => { order.push("restart"); @@ -36,7 +36,8 @@ describe("establishRestoredSandboxGatewayPairing", () => { expect(warmupScopeUpgrade).toHaveBeenCalledWith("beta"); expect(autoPairScopeApproval).toHaveBeenCalledWith("beta"); expect(verifyGatewayPairing).toHaveBeenCalledWith("beta"); - expect(order).toEqual(["restart", "warmup", "approve", "verify"]); + expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); + expect(order).toEqual(["restart", "warmup", "approve", "restart", "verify"]); }); it("repeats the handshake once when verification creates a remaining scope upgrade (#7431)", async () => { @@ -65,31 +66,40 @@ describe("establishRestoredSandboxGatewayPairing", () => { "restart", "warmup", "approve", - "verify", "restart", + "verify", "warmup", "approve", + "restart", "verify", ]); }); - it("restarts the gateway before verifying registration approved by the first attempt (#7431)", async () => { - let lifecycleGeneration = 0; - let approvedGeneration: number | null = null; - let approvalPending = false; + it("restarts after each of two successive approved transitions before verification (#7431)", async () => { + const transitions = ["pairing", "operator.write"]; + const order: string[] = []; + let approvedTransitions = 0; + let runningTransitions = 0; + let pendingTransition: string | null = null; const restartRestoredSandboxGateway = vi.fn(() => { - lifecycleGeneration += 1; + runningTransitions = approvedTransitions; + order.push(`restart:${runningTransitions}`); }); const warmupScopeUpgrade = vi.fn(() => { - approvalPending = approvedGeneration === null; + pendingTransition = transitions[approvedTransitions] ?? null; + order.push(`warmup:${pendingTransition ?? "none"}`); }); const autoPairScopeApproval = vi.fn(() => { - approvedGeneration = approvalPending ? lifecycleGeneration : approvedGeneration; - approvalPending = false; + order.push(`approve:${pendingTransition ?? "none"}`); + if (pendingTransition !== null) { + approvedTransitions += 1; + pendingTransition = null; + } + }); + const verifyGatewayPairing = vi.fn(() => { + order.push(`verify:${runningTransitions}`); + return runningTransitions === transitions.length; }); - const verifyGatewayPairing = vi.fn( - () => approvedGeneration !== null && lifecycleGeneration > approvedGeneration, - ); await establishRestoredSandboxGatewayPairing("beta", { restartRestoredSandboxGateway, @@ -98,7 +108,18 @@ describe("establishRestoredSandboxGatewayPairing", () => { verifyGatewayPairing, }); - expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); + expect(order).toEqual([ + "restart:0", + "warmup:pairing", + "approve:pairing", + "restart:1", + "verify:1", + "warmup:operator.write", + "approve:operator.write", + "restart:2", + "verify:2", + ]); + expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(3); expect(warmupScopeUpgrade).toHaveBeenCalledTimes(2); expect(autoPairScopeApproval).toHaveBeenCalledTimes(2); expect(verifyGatewayPairing).toHaveBeenCalledTimes(2); @@ -157,7 +178,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { verifyGatewayPairing, }), ).rejects.toThrow("authenticated gateway verification run did not succeed"); - expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); + expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(3); expect(warmupScopeUpgrade).toHaveBeenCalledTimes(2); expect(autoPairScopeApproval).toHaveBeenCalledTimes(2); expect(verifyGatewayPairing).toHaveBeenCalledTimes(2); diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.ts b/src/lib/actions/sandbox/restore-gateway-pairing.ts index f1b00bbad4c..472973d23a1 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.ts @@ -12,10 +12,12 @@ export type RestoreGatewayPairingDeps = { verifyGatewayPairing: (sandboxName: string) => boolean; }; -// A restored clone starts without runtime device credentials. Its first pass -// can approve initial pairing, while strict verification can provoke the -// remaining operator.write upgrade. Permit one bounded recovery pass. -const RESTORE_GATEWAY_PAIRING_ATTEMPTS = 2; +// A restored clone starts without runtime device credentials. Restart once so +// its gateway serves the restored state. Each warm-up can provoke one +// allowlisted transition, but approved state is not visible until the gateway +// restarts. Strict verification can then provoke the remaining operator.write +// upgrade, so permit one bounded recovery cycle. +const RESTORE_GATEWAY_PAIRING_CYCLES = 2; type RestoredSandboxGatewayRestartDeps = { restartSandboxGateway: ( @@ -57,13 +59,14 @@ export async function establishRestoredSandboxGatewayPairing( deps: RestoreGatewayPairingDeps = defaultRestoreGatewayPairingDeps(), ): Promise { try { - for (let attempt = 0; attempt < RESTORE_GATEWAY_PAIRING_ATTEMPTS; attempt += 1) { - // Registration approved by the first pass is not visible until the - // gateway restarts. Repeat supervisor-mediated restart and host-forward - // recovery before every bounded attempt. - deps.restartRestoredSandboxGateway(targetSandbox); + deps.restartRestoredSandboxGateway(targetSandbox); + for (let cycle = 0; cycle < RESTORE_GATEWAY_PAIRING_CYCLES; cycle += 1) { deps.warmupScopeUpgrade(targetSandbox); deps.autoPairScopeApproval(targetSandbox); + // Publish the approved transition to the running gateway before strict + // verification. This also recovers the host forward through the existing + // supervisor-mediated restart path. + deps.restartRestoredSandboxGateway(targetSandbox); if (deps.verifyGatewayPairing(targetSandbox)) { return; } From 3e123dc53f75e9efa2e428cbff59afcbdacd4b04 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sun, 26 Jul 2026 22:34:32 -0700 Subject: [PATCH 02/14] test(restore): keep pairing model linear Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/restore-gateway-pairing.test.ts | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index 98e7a692d44..8d41150f74b 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -91,10 +91,9 @@ describe("establishRestoredSandboxGatewayPairing", () => { }); const autoPairScopeApproval = vi.fn(() => { order.push(`approve:${pendingTransition ?? "none"}`); - if (pendingTransition !== null) { - approvedTransitions += 1; - pendingTransition = null; - } + expect(pendingTransition).toBe(transitions[approvedTransitions]); + approvedTransitions += 1; + pendingTransition = null; }); const verifyGatewayPairing = vi.fn(() => { order.push(`verify:${runningTransitions}`); From 790b4d13bab91e64f05324a4c91ea25dcec1cca7 Mon Sep 17 00:00:00 2001 From: Apurv Kumaria Date: Sun, 26 Jul 2026 23:05:51 -0700 Subject: [PATCH 03/14] test(restore): align VM pairing restart expectation Signed-off-by: Apurv Kumaria --- 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 5f8331c8c24..4449a692b29 100644 --- a/test/snapshot-gateway-guard.test.ts +++ b/test/snapshot-gateway-guard.test.ts @@ -302,7 +302,7 @@ describe("snapshot VM-driver gateway guard", () => { // `snapshot restore --to ` on VM driver must use the registered // imageTag, not the legacy `docker exec ... kubectl` probe. - it("snapshot restore --to uses registered imageTag for VM-driver auto-create instead of kubectl probe", () => { + it("snapshot restore --to uses registered imageTag and restarts the VM gateway before pairing verification", () => { const env = makeVmRestoreToEnv("nemoclaw-snap-vm-gw-restore-to-"); const seed = runCli("alpha snapshot create --name baseline", env); @@ -315,7 +315,7 @@ describe("snapshot VM-driver gateway guard", () => { expect(r.out).not.toContain("kubectl-must-not-run"); expect(r.out).toContain("openshell/sandbox-from:fast-path-test"); expect(fs.readFileSync(path.join(env.HOME, "gateway-lifecycle.log"), "utf8")).toBe( - "restart clone-1\n", + "restart clone-1\nrestart clone-1\n", ); }, 15000); From 3f669da77f44f43260df72dfd1c75a3f100b1236 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sun, 26 Jul 2026 22:49:47 -0700 Subject: [PATCH 04/14] test(restore): cover pairing restart regressions Signed-off-by: Carlos Villela --- .../sandbox/restore-gateway-pairing.test.ts | 29 ++++++++++++++++ test/pr-risk-plan.test.ts | 34 +++++++++++++++++++ tools/e2e/workflow-boundary.mts | 8 +++++ 3 files changed, 71 insertions(+) diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index 8d41150f74b..ac77cbcb2bf 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -144,6 +144,35 @@ describe("establishRestoredSandboxGatewayPairing", () => { expect(verifyGatewayPairing).not.toHaveBeenCalled(); }); + it("fails without verification when the post-approval gateway restart fails (#7431)", async () => { + const order: string[] = []; + const restartRestoredSandboxGateway = vi + .fn() + .mockImplementationOnce(() => order.push("restart:initial")) + .mockImplementationOnce(() => { + order.push("restart:approved"); + throw new Error("gateway did not restart after approval"); + }); + const warmupScopeUpgrade = vi.fn(() => order.push("warmup")); + const autoPairScopeApproval = vi.fn(() => order.push("approve")); + const verifyGatewayPairing = vi.fn(() => { + order.push("verify"); + return true; + }); + + await expect( + establishRestoredSandboxGatewayPairing("beta", { + restartRestoredSandboxGateway, + warmupScopeUpgrade, + autoPairScopeApproval, + verifyGatewayPairing, + }), + ).rejects.toThrow("gateway did not restart after approval"); + expect(order).toEqual(["restart:initial", "warmup", "approve", "restart:approved"]); + expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); + expect(verifyGatewayPairing).not.toHaveBeenCalled(); + }); + it("fails when the pairing warm-up does not complete (#7431)", async () => { const warmupScopeUpgrade = vi.fn(() => { throw new Error("gateway not up"); diff --git a/test/pr-risk-plan.test.ts b/test/pr-risk-plan.test.ts index 97d55e18400..c4733ba631a 100644 --- a/test/pr-risk-plan.test.ts +++ b/test/pr-risk-plan.test.ts @@ -87,6 +87,40 @@ describe("deterministic PR risk plan", () => { expect(result.planHash).not.toBe(withoutFocusedSelection.planHash); }); + it("runs snapshot commands for restored-gateway pairing runtime changes (#7431)", () => { + const runtimeFiles = [ + "src/lib/actions/sandbox/restore-gateway-pairing.ts", + "src/lib/adapters/openshell/restore-gateway-pairing.ts", + ]; + const changedFiles = [ + ...runtimeFiles, + "src/lib/actions/sandbox/restore-gateway-pairing.test.ts", + ]; + const focusedE2eJobs = focusedE2eJobsForChangedFiles(changedFiles); + const result = buildRiskPlan({ headSha: HEAD_SHA, changedFiles, focusedE2eJobs }); + + expect(focusedE2eJobs).toEqual([ + { + id: "snapshot-commands", + matchedFiles: runtimeFiles, + }, + ]); + expect(result.families).toContainEqual( + expect.objectContaining({ + id: "focused-e2e", + matchedFiles: runtimeFiles, + requiredJobs: ["snapshot-commands"], + }), + ); + expect(result.requiredJobs).toContainEqual( + expect.objectContaining({ + id: "snapshot-commands", + families: ["focused-e2e"], + matchedFiles: runtimeFiles, + }), + ); + }); + it("hashes the Deep Agents headless check into its exact typed target", () => { const changedFile = "test/e2e/e2e-cloud-experimental/checks/07-deepagents-code-headless-inference.sh"; diff --git a/tools/e2e/workflow-boundary.mts b/tools/e2e/workflow-boundary.mts index b66d3769374..63b464a762b 100644 --- a/tools/e2e/workflow-boundary.mts +++ b/tools/e2e/workflow-boundary.mts @@ -561,6 +561,11 @@ export function readFreeStandingJobsInventory( return inventory; } +const RESTORED_GATEWAY_PAIRING_RUNTIME_FILES = new Set([ + "src/lib/actions/sandbox/restore-gateway-pairing.ts", + "src/lib/adapters/openshell/restore-gateway-pairing.ts", +]); + export function focusedE2eJobsForChangedFiles( changedFiles: readonly string[], inventory: FreeStandingJobsInventory = readFreeStandingJobsInventory(), @@ -570,6 +575,9 @@ export function focusedE2eJobsForChangedFiles( for (const job of inventory.liveTestToJobs.get(file) ?? []) { addMapValue(matchedFilesByJob, job, file); } + if (RESTORED_GATEWAY_PAIRING_RUNTIME_FILES.has(file)) { + addMapValue(matchedFilesByJob, "snapshot-commands", file); + } } return [...matchedFilesByJob] .sort(([left], [right]) => left.localeCompare(right)) From 8b04fce9d8ff5247710c64353591b9833c437e05 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Sun, 26 Jul 2026 23:47:25 -0700 Subject: [PATCH 05/14] test(restore): verify paired clone after snapshot restore Signed-off-by: Carlos Villela --- test/e2e/live/snapshot-commands.test.ts | 45 +++++++++++++++++++++++-- 1 file changed, 43 insertions(+), 2 deletions(-) diff --git a/test/e2e/live/snapshot-commands.test.ts b/test/e2e/live/snapshot-commands.test.ts index f580b15c394..e1c7886932d 100644 --- a/test/e2e/live/snapshot-commands.test.ts +++ b/test/e2e/live/snapshot-commands.test.ts @@ -44,6 +44,8 @@ const BASELINE_EXCLUSION_KEY = "openclaw_docs"; const LIVE_TIMEOUT_MS = 36 * 60_000; const INFERENCE_API_KEY = "nvapi-snapshot-commands-fixture-credential"; const INFERENCE_MODEL = "snapshot-commands-model"; +const RESTORED_GATEWAY_REJECTION = + /EMBEDDED FALLBACK|gateway connect failed|scope upgrade pending approval|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded/i; function commandEnv(inference?: SnapshotInferenceFixture): NodeJS.ProcessEnv { return buildSnapshotCommandEnv(SANDBOX_NAME, inference); @@ -103,6 +105,31 @@ async function expectSandboxFileContent( expect(result.stdout.trim()).toBe(expected); } +async function expectAuthenticatedGatewayPairing( + sandbox: SandboxClient, + sandboxName: string, + artifactName: string, +): Promise { + const result = await sandbox.execShell( + sandboxName, + trustedSandboxShellScript(` +set -eu +PROXY_ENV=/tmp/nemoclaw-proxy-env.sh +[ -r "$PROXY_ENV" ] && . "$PROXY_ENV" +openclaw agent --agent main --json -m "ping" \ + --session-id "snapshot-restore-verify-$$-$(date +%s)" +`), + { + artifactName, + env: commandEnv(), + timeoutMs: 60_000, + }, + ); + expect(result.exitCode, resultText(result)).toBe(0); + expect(resultText(result).trim()).not.toBe(""); + expect(resultText(result)).not.toMatch(RESTORED_GATEWAY_REJECTION); +} + async function expectBaselineExclusionAgreement( host: HostCliClient, sandbox: SandboxClient, @@ -163,7 +190,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- e2ePhases: [ "confirm Docker and start hermetic inference", "onboard the snapshot sandbox", - "create and list the first snapshot", + "create, list, and restore the first snapshot into a paired clone", "create a second snapshot from changed workspace", "restore latest and timestamped snapshots", "audit snapshot credentials and command help", @@ -184,6 +211,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- "snapshot list shows versioned snapshots and parseable timestamps", "baseline exclusions remain active in registry and live policy across rebuild", "snapshot restore --to carries baseline exclusions into clone registry and live policy", + "snapshot restore --to returns only after restored gateway pairing is authenticated", "latest snapshot restore recovers latest workspace state", "timestamp-targeted restore recovers the first snapshot state", "snapshot directory excludes credential-bearing env/json files", @@ -355,7 +383,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- "phase-2-read-marker", ); - progress.phase("create and list the first snapshot"); + progress.phase("create, list, and restore the first snapshot into a paired clone"); const firstCreate = await host.command("nemoclaw", [SANDBOX_NAME, "snapshot", "create"], { artifactName: "phase-3-snapshot-create-first", env: commandEnv(), @@ -399,6 +427,19 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- CLONE_SANDBOX_NAME, "phase-4-clone-baseline-exclusion", ); + const clonePairingRequestOffset = inference.requests().length; + await expectAuthenticatedGatewayPairing( + sandbox, + CLONE_SANDBOX_NAME, + "phase-4-verify-clone-gateway-pairing", + ); + expect(inference.requests().slice(clonePairingRequestOffset)).toContainEqual( + expect.objectContaining({ + auth: "ok", + model: INFERENCE_MODEL, + path: "/v1/chat/completions", + }), + ); const destroyClone = await host.command("nemoclaw", [CLONE_SANDBOX_NAME, "destroy", "--yes"], { artifactName: "phase-4-destroy-clone", env: commandEnv(), From 2193b9ea83e001bcca6b92cb6467eda7d835f037 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 01:06:49 -0700 Subject: [PATCH 06/14] fix(restore): classify gateway pairing failures --- .../sandbox/restore-gateway-pairing.test.ts | 29 +++++-- .../sandbox/restore-gateway-pairing.ts | 16 +++- .../openshell/restore-gateway-pairing.test.ts | 85 ++++++++++++++++--- .../openshell/restore-gateway-pairing.ts | 74 +++++++++++++--- 4 files changed, 166 insertions(+), 38 deletions(-) diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index ac77cbcb2bf..7327c5793cc 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -22,7 +22,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { const autoPairScopeApproval = vi.fn(() => order.push("approve")); const verifyGatewayPairing = vi.fn(() => { order.push("verify"); - return true; + return { ok: true as const }; }); await establishRestoredSandboxGatewayPairing("beta", { @@ -46,11 +46,11 @@ describe("establishRestoredSandboxGatewayPairing", () => { .fn() .mockImplementationOnce(() => { order.push("verify"); - return false; + return { ok: false as const, failureLayer: "scope-upgrade-pending" as const }; }) .mockImplementationOnce(() => { order.push("verify"); - return true; + return { ok: true as const }; }); await establishRestoredSandboxGatewayPairing("beta", { @@ -97,7 +97,9 @@ describe("establishRestoredSandboxGatewayPairing", () => { }); const verifyGatewayPairing = vi.fn(() => { order.push(`verify:${runningTransitions}`); - return runningTransitions === transitions.length; + return runningTransitions === transitions.length + ? { ok: true as const } + : { ok: false as const, failureLayer: "scope-upgrade-pending" as const }; }); await establishRestoredSandboxGatewayPairing("beta", { @@ -127,7 +129,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { it("fails before pairing when the restored gateway cannot restart (#7431)", async () => { const warmupScopeUpgrade = vi.fn(); const autoPairScopeApproval = vi.fn(); - const verifyGatewayPairing = vi.fn(() => true); + const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); await expect( establishRestoredSandboxGatewayPairing("beta", { @@ -157,7 +159,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { const autoPairScopeApproval = vi.fn(() => order.push("approve")); const verifyGatewayPairing = vi.fn(() => { order.push("verify"); - return true; + return { ok: true as const }; }); await expect( @@ -178,7 +180,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { throw new Error("gateway not up"); }); const autoPairScopeApproval = vi.fn(); - const verifyGatewayPairing = vi.fn(() => true); + const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); await expect( establishRestoredSandboxGatewayPairing("beta", { @@ -196,7 +198,16 @@ describe("establishRestoredSandboxGatewayPairing", () => { const restartRestoredSandboxGateway = vi.fn(); const warmupScopeUpgrade = vi.fn(); const autoPairScopeApproval = vi.fn(); - const verifyGatewayPairing = vi.fn(() => false); + const verifyGatewayPairing = vi + .fn() + .mockReturnValueOnce({ + ok: false as const, + failureLayer: "device-pairing-required" as const, + }) + .mockReturnValueOnce({ + ok: false as const, + failureLayer: "scope-upgrade-pending" as const, + }); await expect( establishRestoredSandboxGatewayPairing("beta", { @@ -205,7 +216,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { autoPairScopeApproval, verifyGatewayPairing, }), - ).rejects.toThrow("authenticated gateway verification run did not succeed"); + ).rejects.toThrow("authenticated gateway verification run failed (scope-upgrade-pending)"); expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(3); expect(warmupScopeUpgrade).toHaveBeenCalledTimes(2); expect(autoPairScopeApproval).toHaveBeenCalledTimes(2); diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.ts b/src/lib/actions/sandbox/restore-gateway-pairing.ts index 472973d23a1..144d876a60d 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.ts @@ -1,7 +1,10 @@ // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 -import { verifyRestoredSandboxGatewayPairing } from "../../adapters/openshell/restore-gateway-pairing"; +import { + type RestoreGatewayPairingVerificationResult, + verifyRestoredSandboxGatewayPairing, +} from "../../adapters/openshell/restore-gateway-pairing"; import type { GatewayRestartResult } from "./gateway-restart"; import { WARMUP_SESSION_ID_PREFIX } from "./warmup-session"; @@ -9,7 +12,7 @@ export type RestoreGatewayPairingDeps = { restartRestoredSandboxGateway: (sandboxName: string) => void; warmupScopeUpgrade: (sandboxName: string) => void; autoPairScopeApproval: (sandboxName: string) => void; - verifyGatewayPairing: (sandboxName: string) => boolean; + verifyGatewayPairing: (sandboxName: string) => RestoreGatewayPairingVerificationResult; }; // A restored clone starts without runtime device credentials. Restart once so @@ -59,6 +62,7 @@ export async function establishRestoredSandboxGatewayPairing( deps: RestoreGatewayPairingDeps = defaultRestoreGatewayPairingDeps(), ): Promise { try { + let lastFailure: Extract | null = null; deps.restartRestoredSandboxGateway(targetSandbox); for (let cycle = 0; cycle < RESTORE_GATEWAY_PAIRING_CYCLES; cycle += 1) { deps.warmupScopeUpgrade(targetSandbox); @@ -67,11 +71,15 @@ export async function establishRestoredSandboxGatewayPairing( // verification. This also recovers the host forward through the existing // supervisor-mediated restart path. deps.restartRestoredSandboxGateway(targetSandbox); - if (deps.verifyGatewayPairing(targetSandbox)) { + const verification = deps.verifyGatewayPairing(targetSandbox); + if (verification.ok) { return; } + lastFailure = verification; } - throw new Error("the authenticated gateway verification run did not succeed"); + throw new Error( + `the authenticated gateway verification run failed (${lastFailure?.failureLayer ?? "unknown"})`, + ); } catch (err) { throw new Error( `could not establish gateway pairing for '${targetSandbox}': ${ diff --git a/src/lib/adapters/openshell/restore-gateway-pairing.test.ts b/src/lib/adapters/openshell/restore-gateway-pairing.test.ts index 3e7dc43fcfb..d85d5c95fd2 100644 --- a/src/lib/adapters/openshell/restore-gateway-pairing.test.ts +++ b/src/lib/adapters/openshell/restore-gateway-pairing.test.ts @@ -23,7 +23,9 @@ describe("verifyRestoredSandboxGatewayPairing", () => { it("accepts an authenticated gateway verification run that exits successfully (#7431)", () => { const deps = verifierDeps({ status: 0, stdout: '{"result":"pong"}', stderr: "" }); - expect(verifyRestoredSandboxGatewayPairing("beta", SESSION_ID_PREFIX, deps)).toBe(true); + expect(verifyRestoredSandboxGatewayPairing("beta", SESSION_ID_PREFIX, deps)).toEqual({ + ok: true, + }); expect(deps.spawnSync).toHaveBeenCalledWith( "/usr/bin/openshell", expect.arrayContaining(["sandbox", "exec", "--name", "beta"]), @@ -34,23 +36,28 @@ describe("verifyRestoredSandboxGatewayPairing", () => { it("rejects an authenticated gateway verification run that exits unsuccessfully (#7431)", () => { expect( verifyRestoredSandboxGatewayPairing("beta", SESSION_ID_PREFIX, verifierDeps({ status: 1 })), - ).toBe(false); + ).toEqual({ ok: false, failureLayer: "command-failure" }); }); it.each([ - "EMBEDDED FALLBACK: gateway unavailable", - '{"fallbackFrom":"gateway"}', - '{"transport":"embedded"}', - "gateway connect failed: device pairing required", - "scope upgrade pending approval", - ])("rejects a zero-exit verification run with fallback or pairing output (#7431)", (output) => { + ["EMBEDDED FALLBACK: gateway unavailable", "embedded-fallback"], + ['{"fallbackFrom":"gateway"}', "embedded-fallback"], + ['{"transport":"embedded"}', "embedded-fallback"], + ["gateway connect failed", "gateway-connect-failure"], + ["gateway connect failed: device pairing required", "device-pairing-required"], + ["scope upgrade pending approval", "scope-upgrade-pending"], + [ + "gateway connect failed: pairing required: device is asking for more scopes", + "scope-upgrade-pending", + ], + ] as const)("classifies a verification run with fallback or pairing output (#7431)", (output, failureLayer) => { expect( verifyRestoredSandboxGatewayPairing( "beta", SESSION_ID_PREFIX, verifierDeps({ status: 0, stdout: output }), ), - ).toBe(false); + ).toEqual({ ok: false, failureLayer }); }); it("accepts changed output when the gateway run exits successfully without a failure signal (#7431)", () => { @@ -60,7 +67,27 @@ describe("verifyRestoredSandboxGatewayPairing", () => { SESSION_ID_PREFIX, verifierDeps({ status: 0, stdout: '{"futureResult":"ok"}' }), ), - ).toBe(true); + ).toEqual({ ok: true }); + }); + + it("rejects an empty successful verification run (#7431)", () => { + expect( + verifyRestoredSandboxGatewayPairing( + "beta", + SESSION_ID_PREFIX, + verifierDeps({ status: 0, stdout: "", stderr: "" }), + ), + ).toEqual({ ok: false, failureLayer: "empty-output" }); + }); + + it("rejects a successful verification run with only a stderr warning (#7431)", () => { + expect( + verifyRestoredSandboxGatewayPairing( + "beta", + SESSION_ID_PREFIX, + verifierDeps({ status: 0, stdout: "", stderr: "unrelated warning" }), + ), + ).toEqual({ ok: false, failureLayer: "empty-output" }); }); it("rejects an authenticated gateway verification run that times out (#7431)", () => { @@ -71,9 +98,9 @@ describe("verifyRestoredSandboxGatewayPairing", () => { verifyRestoredSandboxGatewayPairing( "beta", SESSION_ID_PREFIX, - verifierDeps({ status: null, error }), + verifierDeps({ status: null, error, stdout: '{"result":"pong"}' }), ), - ).toBe(false); + ).toEqual({ ok: false, failureLayer: "execution-timeout" }); }); it("rejects verification when the OpenShell executable cannot be resolved (#7431)", () => { @@ -84,7 +111,7 @@ describe("verifyRestoredSandboxGatewayPairing", () => { resolveOpenshell: () => null, spawnSync: spawn, }), - ).toBe(false); + ).toEqual({ ok: false, failureLayer: "openshell-unavailable" }); expect(spawn).not.toHaveBeenCalled(); }); @@ -96,6 +123,36 @@ describe("verifyRestoredSandboxGatewayPairing", () => { throw new Error("spawn failed"); }, }), - ).toBe(false); + ).toEqual({ ok: false, failureLayer: "spawn-failure" }); + }); + + it("rejects a returned process error before inspecting buffered output (#7431)", () => { + const error = new Error("not found") as NodeJS.ErrnoException; + error.code = "ENOENT"; + + expect( + verifyRestoredSandboxGatewayPairing( + "beta", + SESSION_ID_PREFIX, + verifierDeps({ + status: 0, + error, + stdout: '{"result":"pong"}', + stderr: "token=do-not-report", + }), + ), + ).toEqual({ ok: false, failureLayer: "spawn-failure" }); + }); + + it("does not expose verifier output in a classified failure (#7431)", () => { + const secretOutput = "scope upgrade pending approval token=do-not-report"; + + expect( + verifyRestoredSandboxGatewayPairing( + "beta", + SESSION_ID_PREFIX, + verifierDeps({ status: 0, stderr: secretOutput }), + ), + ).toEqual({ ok: false, failureLayer: "scope-upgrade-pending" }); }); }); diff --git a/src/lib/adapters/openshell/restore-gateway-pairing.ts b/src/lib/adapters/openshell/restore-gateway-pairing.ts index 540fc01ace8..291bd32a741 100644 --- a/src/lib/adapters/openshell/restore-gateway-pairing.ts +++ b/src/lib/adapters/openshell/restore-gateway-pairing.ts @@ -16,12 +16,48 @@ openclaw agent --agent main --json -m "ping" \ --session-id "$1restore-verify-$$-$(date +%s)" `; +export type RestoreGatewayPairingFailureLayer = + | "openshell-unavailable" + | "execution-timeout" + | "spawn-failure" + | "command-failure" + | "empty-output" + | "embedded-fallback" + | "gateway-connect-failure" + | "scope-upgrade-pending" + | "device-pairing-required"; + +export type RestoreGatewayPairingVerificationResult = + | { ok: true } + | { ok: false; failureLayer: RestoreGatewayPairingFailureLayer }; + // OpenClaw can currently exit zero after using its embedded fallback, and its // JSON output does not expose a supported, stable transport discriminator. -// These compatibility signals match the gateway-auth live tests. Remove this -// classifier once OpenClaw provides a machine-readable gateway-only result. -const RESTORE_GATEWAY_PAIRING_REJECTION = - /EMBEDDED FALLBACK|gateway connect failed|scope upgrade pending approval|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded/i; +// These compatibility signals match the gateway-auth live tests. Keep the +// returned classification fixed and output-free so restore diagnostics never +// expose agent output or credentials. Remove this classifier once OpenClaw +// provides a machine-readable gateway-only result. +const RESTORE_GATEWAY_PAIRING_REJECTIONS: ReadonlyArray<{ + pattern: RegExp; + failureLayer: RestoreGatewayPairingFailureLayer; +}> = [ + { + pattern: /scope upgrade pending approval|pairing required: device is asking for more scopes/i, + failureLayer: "scope-upgrade-pending", + }, + { + pattern: /device pairing required|pairing required/i, + failureLayer: "device-pairing-required", + }, + { + pattern: /gateway connect failed/i, + failureLayer: "gateway-connect-failure", + }, + { + pattern: /EMBEDDED FALLBACK|fallbackFrom[": ]+gateway|transport[": ]+embedded/i, + failureLayer: "embedded-fallback", + }, +]; type RestoreGatewayPairingSpawnResult = { status: number | null; @@ -48,10 +84,12 @@ export function verifyRestoredSandboxGatewayPairing( targetSandbox: string, sessionIdPrefix: string, deps: RestoreGatewayPairingVerifierDeps = defaultDeps, -): boolean { +): RestoreGatewayPairingVerificationResult { try { const openshellBinary = deps.resolveOpenshell(); - if (!openshellBinary) return false; + if (!openshellBinary) { + return { ok: false, failureLayer: "openshell-unavailable" }; + } const result = deps.spawnSync( openshellBinary, @@ -75,13 +113,27 @@ export function verifyRestoredSandboxGatewayPairing( timeout: RESTORE_GATEWAY_PAIRING_VERIFY_TIMEOUT_MS, }, ); + if ((result.error as NodeJS.ErrnoException | undefined)?.code === "ETIMEDOUT") { + return { ok: false, failureLayer: "execution-timeout" }; + } + if (result.error) { + return { ok: false, failureLayer: "spawn-failure" }; + } const output = `${result.stdout ?? ""}\n${result.stderr ?? ""}`; - return ( - result.status === 0 && - result.error === undefined && - !RESTORE_GATEWAY_PAIRING_REJECTION.test(output) + const rejection = RESTORE_GATEWAY_PAIRING_REJECTIONS.find(({ pattern }) => + pattern.test(output), ); + if (rejection) { + return { ok: false, failureLayer: rejection.failureLayer }; + } + if (result.status !== 0) { + return { ok: false, failureLayer: "command-failure" }; + } + if (!result.stdout?.trim()) { + return { ok: false, failureLayer: "empty-output" }; + } + return { ok: true }; } catch { - return false; + return { ok: false, failureLayer: "spawn-failure" }; } } From 2ee85623679effc570135443dd712c72e96586ba Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 02:36:45 -0700 Subject: [PATCH 07/14] fix(restore): scope pairing approval to clone Signed-off-by: Carlos Villela --- .../sandbox/auto-pair-approval.test.ts | 150 ++++++++++++++++++ src/lib/actions/sandbox/auto-pair-approval.ts | 149 ++++++++++++++++- .../sandbox/restore-gateway-pairing.test.ts | 138 +++------------- .../sandbox/restore-gateway-pairing.ts | 57 ++++--- test/e2e/live/snapshot-commands-helpers.ts | 44 +++++ test/e2e/live/snapshot-commands.test.ts | 18 ++- .../support/snapshot-commands-helpers.test.ts | 46 +++++- 7 files changed, 451 insertions(+), 151 deletions(-) diff --git a/src/lib/actions/sandbox/auto-pair-approval.test.ts b/src/lib/actions/sandbox/auto-pair-approval.test.ts index 2693cf9d434..c6a3654deec 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.test.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.test.ts @@ -30,6 +30,20 @@ describe("buildAutoPairApprovalScript (#4263/#4616)", () => { expect(script).toContain("'UE9MSUNZ'"); }); + it("adds local-device filtering only for restored-clone approval", () => { + const ordinary = buildAutoPairApprovalScript("UE9MSUNZ"); + const restoredClone = buildAutoPairApprovalScript("UE9MSUNZ", { + localDeviceOnly: true, + budget: { maxApprovals: 1 }, + }); + + expect(ordinary).not.toContain("local_identity_public_key"); + expect(restoredClone).toContain("local_identity_public_key"); + expect(restoredClone).toContain("len(related_pending) != 1"); + expect(restoredClone).toContain("pending = related_pending"); + expect(restoredClone).toContain("MAX_APPROVALS = 1"); + }); + it("omits the summary marker by default and appends it when requested", () => { const silent = buildAutoPairApprovalScript("UE9MSUNZ"); const reporting = buildAutoPairApprovalScript("UE9MSUNZ", { emitSummary: true }); @@ -165,6 +179,142 @@ process.exit(2); } }); + it("approves only one exact local clone pairing transition on a shared gateway", () => { + if (spawnSync("sh", ["-c", "command -v python3"], { stdio: "ignore" }).status !== 0) { + return; + } + const policy = readAutoPairApprovalPolicyModule(); + expect(policy).toBeTruthy(); + const script = buildAutoPairApprovalScript( + Buffer.from(policy as string, "utf-8").toString("base64"), + { + emitSummary: true, + localDeviceOnly: true, + budget: { maxApprovals: 1 }, + }, + ); + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-restored-clone-pair-")); + try { + const stateDir = path.join(tmpDir, "openclaw-state"); + const identityDir = path.join(stateDir, "identity"); + const approvalsFile = path.join(tmpDir, "approvals.log"); + const approveEnvFile = path.join(tmpDir, "approve-env.log"); + fs.mkdirSync(identityDir, { recursive: true }); + const publicKey = "y3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8"; + const deviceId = "04a4c561c730435e9f6a2e38d2e7b929bcbec2ea1c37d3dd053f3341ecce4e47"; + fs.writeFileSync( + path.join(identityDir, "device.json"), + JSON.stringify({ + deviceId, + publicKeyPem: + "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAy3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8=\n-----END PUBLIC KEY-----\n", + }), + ); + fs.writeFileSync( + path.join(tmpDir, "openclaw"), + `#!${process.execPath} +const fs = require("fs"); +const args = process.argv.slice(2); +if (args[0] === "devices" && args[1] === "list") { + process.stdout.write(process.env.NEMOCLAW_LIST_RESPONSE + "\\n"); + process.exit(0); +} +if (args[0] === "devices" && args[1] === "approve") { + fs.appendFileSync(${JSON.stringify(approvalsFile)}, args[2] + "\\n"); + fs.appendFileSync( + ${JSON.stringify(approveEnvFile)}, + [ + process.env.OPENCLAW_GATEWAY_URL || "unset", + process.env.OPENCLAW_GATEWAY_PORT || "unset", + process.env.OPENCLAW_GATEWAY_TOKEN || "unset", + ].join(":") + "\\n", + ); + process.stdout.write("{}\\n"); + process.exit(0); +} +process.exit(2); +`, + { mode: 0o755 }, + ); + const run = (pending: unknown[]) => + spawnSync("sh", ["-c", script], { + encoding: "utf-8", + env: { + ...process.env, + PATH: `${tmpDir}:/usr/bin:/bin`, + NEMOCLAW_LIST_RESPONSE: JSON.stringify({ pending, paired: [] }), + OPENCLAW_GATEWAY_URL: "ws://127.0.0.1:18789", + OPENCLAW_GATEWAY_PORT: "18789", + OPENCLAW_GATEWAY_TOKEN: "secret-token", + OPENCLAW_STATE_DIR: stateDir, + }, + timeout: 10_000, + }); + const readApprovals = () => + fs.existsSync(approvalsFile) + ? fs.readFileSync(approvalsFile, "utf-8").trim().split("\n").filter(Boolean) + : []; + const resetLogs = () => { + fs.rmSync(approvalsFile, { force: true }); + fs.rmSync(approveEnvFile, { force: true }); + }; + const localRequest = { + requestId: "clone-pairing", + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + }; + const foreignRequest = { + ...localRequest, + requestId: "primary-pairing", + deviceId: "f".repeat(64), + publicKey: "foreign-public-key", + }; + + const initial = run([foreignRequest, localRequest]); + expect(initial.status).toBe(0); + expect(initial.stdout).toContain(`${SUMMARY_MARKER}=1`); + expect(readApprovals()).toEqual(["clone-pairing"]); + expect(fs.readFileSync(approveEnvFile, "utf-8").trim()).toBe("unset:unset:unset"); + + resetLogs(); + const repairRequest = { + ...localRequest, + requestId: "clone-write-upgrade", + isRepair: true, + scopes: ["operator.pairing", "operator.write"], + requestedScopes: ["operator.pairing", "operator.write"], + }; + const repair = run([foreignRequest, repairRequest]); + expect(repair.status).toBe(0); + expect(repair.stdout).toContain(`${SUMMARY_MARKER}=1`); + expect(readApprovals()).toEqual(["clone-write-upgrade"]); + + const { scopes: _ignoredScopes, ...repairWithoutScopes } = repairRequest; + for (const rejected of [ + [foreignRequest], + [{ ...repairRequest, publicKey: "mismatched-public-key" }], + [repairRequest, { ...repairRequest, requestId: "second-clone-upgrade" }], + [repairRequest, { ...foreignRequest, requestId: repairRequest.requestId }], + [{ ...repairRequest, requestedScopes: ["operator.admin"] }], + [{ ...repairRequest, scopes: [] }], + [repairWithoutScopes], + ]) { + resetLogs(); + const result = run(rejected); + expect(result.status).toBe(0); + expect(result.stdout).not.toContain(`${SUMMARY_MARKER}=1`); + expect(readApprovals()).toEqual([]); + } + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }); + it("leaves a failed compatibility-shaped approval retryable without editing device state", () => { if (spawnSync("sh", ["-c", "command -v python3"], { stdio: "ignore" }).status !== 0) { return; diff --git a/src/lib/actions/sandbox/auto-pair-approval.ts b/src/lib/actions/sandbox/auto-pair-approval.ts index 7c011b64b3a..fe99d2a0022 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.ts @@ -102,7 +102,11 @@ export function readAutoPairApprovalPolicyModule(): string | null { */ export function buildAutoPairApprovalScript( approvalPolicyModuleB64: string, - options: { emitSummary?: boolean; budget?: AutoPairApprovalBudget } = {}, + options: { + emitSummary?: boolean; + budget?: AutoPairApprovalBudget; + localDeviceOnly?: boolean; + } = {}, ): string { const summaryLine = options.emitSummary ? "print(f'__NEMOCLAW_AUTO_PAIR_APPROVED__={approved_count}')\n" @@ -110,6 +114,140 @@ export function buildAutoPairApprovalScript( const maxApprovals = options.budget?.maxApprovals ?? AUTO_PAIR_MAX_APPROVALS; const listTimeoutS = options.budget?.listTimeoutS ?? AUTO_PAIR_LIST_TIMEOUT_S; const approveTimeoutS = options.budget?.approveTimeoutS ?? AUTO_PAIR_APPROVE_TIMEOUT_S; + const localDeviceFilter = options.localDeviceOnly + ? ` +# Snapshot restore shares one gateway across the source sandbox and its clone. +# Select exactly one pending CLI transition whose device identity matches the +# clone executing this script. Ambiguous or malformed state approves nothing; +# OpenClaw remains the only writer through the canonical approve command. +import binascii +import hashlib +import re + +REQUEST_ID_RE = re.compile(r'^[A-Za-z0-9._:-]{1,128}$') +ALLOWED_LOCAL_SCOPES = {'operator.pairing', 'operator.read', 'operator.write'} + +def local_identity_public_key(identity): + raw = str(identity.get('publicKey', '') or '').strip() + if raw: + return raw + pem = str(identity.get('publicKeyPem', '') or '') + body = ''.join(line.strip() for line in pem.splitlines() if '---' not in line) + if not body: + return '' + try: + der = base64.b64decode(body, validate=True) + except (ValueError, binascii.Error): + return '' + if len(der) < 32: + return '' + return base64.urlsafe_b64encode(der[-32:]).decode('ascii').rstrip('=') + +def normalized_roles(device): + roles = set() + if device.get('role') is not None: + role = device.get('role') + if not isinstance(role, str) or not role.strip(): + return None + roles.add(role.strip()) + if device.get('roles') is not None: + raw_roles = device.get('roles') + if not isinstance(raw_roles, list): + return None + for role in raw_roles: + if not isinstance(role, str) or not role.strip(): + return None + roles.add(role.strip()) + return roles + +def consistent_scope_view(device): + if 'scopes' not in device: + return None + views = [] + for key in ('scopes', 'requestedScopes'): + if key not in device: + continue + raw_scopes = device.get(key) + if not isinstance(raw_scopes, list) or not raw_scopes: + return None + scopes = [] + for scope in raw_scopes: + if not isinstance(scope, str) or not scope.strip(): + return None + scopes.append(scope.strip()) + if len(scopes) != len(set(scopes)) or not set(scopes).issubset(ALLOWED_LOCAL_SCOPES): + return None + views.append(set(scopes)) + if not views or any(view != views[0] for view in views[1:]): + return None + return views[0] + +state_dir = os.environ.get('OPENCLAW_STATE_DIR') or '/sandbox/.openclaw' +try: + with open(os.path.join(state_dir, 'identity', 'device.json'), encoding='utf-8') as handle: + local_identity = json.load(handle) +except (OSError, ValueError): + sys.exit(0) +if not isinstance(local_identity, dict): + sys.exit(0) +local_device_id = str(local_identity.get('deviceId', '') or '').strip() +local_public_key = local_identity_public_key(local_identity) +if not local_device_id or not local_public_key: + sys.exit(0) +try: + local_public_key_raw = base64.urlsafe_b64decode( + local_public_key + '=' * (-len(local_public_key) % 4), + ) +except (ValueError, binascii.Error): + sys.exit(0) +if ( + len(local_public_key_raw) != 32 + or hashlib.sha256(local_public_key_raw).hexdigest() != local_device_id +): + sys.exit(0) + +def is_local_pairing_transition(device): + request_id = device.get('requestId') + if not isinstance(request_id, str) or not REQUEST_ID_RE.fullmatch(request_id): + return False + if str(device.get('deviceId', '') or '').strip() != local_device_id: + return False + if str(device.get('publicKey', '') or '').strip() != local_public_key: + return False + if str(device.get('clientId', '') or '').strip() != 'cli': + return False + if str(device.get('clientMode', '') or '').strip() != 'cli': + return False + if normalized_roles(device) != {'operator'}: + return False + scopes = consistent_scope_view(device) + if scopes is None: + return False + is_repair = device.get('isRepair') + if is_repair is True: + return 'operator.write' in scopes + if is_repair not in (None, False): + return False + return scopes == {'operator.pairing'} + +related_pending = [ + device for device in pending + if isinstance(device, dict) and ( + str(device.get('deviceId', '') or '').strip() == local_device_id + or str(device.get('publicKey', '') or '').strip() == local_public_key + ) +] +if len(related_pending) != 1 or not is_local_pairing_transition(related_pending[0]): + sys.exit(0) +local_request_id = related_pending[0].get('requestId') +if sum( + 1 for device in pending + if isinstance(device, dict) and device.get('requestId') == local_request_id +) != 1: + sys.exit(0) +pending = related_pending +` + : ""; return ` PROXY_ENV=/tmp/nemoclaw-proxy-env.sh [ -r "$PROXY_ENV" ] && . "$PROXY_ENV" @@ -153,7 +291,7 @@ if not isinstance(data, dict): sys.exit(0) pending = data.get('pending') if not isinstance(pending, list): - sys.exit(0) + sys.exit(0)${localDeviceFilter} approved_count = 0 attempted_count = 0 seen_request_ids = set() @@ -197,7 +335,11 @@ exit 0 */ export function runSandboxAutoPairApprovalPass( sandboxName: string, - options: { capture?: boolean; budget?: AutoPairApprovalBudget } = {}, + options: { + capture?: boolean; + budget?: AutoPairApprovalBudget; + localDeviceOnly?: boolean; + } = {}, ): AutoPairApprovalResult { const capture = options.capture === true; const approvalPolicyModule = readAutoPairApprovalPolicyModule(); @@ -208,6 +350,7 @@ export function runSandboxAutoPairApprovalPass( const script = buildAutoPairApprovalScript(approvalPolicyModuleB64, { emitSummary: capture, budget: options.budget, + localDeviceOnly: options.localDeviceOnly, }); const outerTimeoutMs = options.budget?.timeoutMs ?? AUTO_PAIR_APPROVAL_TIMEOUT_MS; // Lazy require: `adapters/openshell/runtime` pulls in `runner`, whose diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index 7327c5793cc..abb770e544d 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -19,7 +19,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { order.push("restart"); }); const warmupScopeUpgrade = vi.fn(() => order.push("warmup")); - const autoPairScopeApproval = vi.fn(() => order.push("approve")); + const approveRestoredClonePairing = vi.fn(() => order.push("approve")); const verifyGatewayPairing = vi.fn(() => { order.push("verify"); return { ok: true as const }; @@ -28,107 +28,23 @@ describe("establishRestoredSandboxGatewayPairing", () => { await establishRestoredSandboxGatewayPairing("beta", { restartRestoredSandboxGateway, warmupScopeUpgrade, - autoPairScopeApproval, + approveRestoredClonePairing, verifyGatewayPairing, }); expect(restartRestoredSandboxGateway).toHaveBeenCalledWith("beta"); expect(warmupScopeUpgrade).toHaveBeenCalledWith("beta"); - expect(autoPairScopeApproval).toHaveBeenCalledWith("beta"); + expect(approveRestoredClonePairing).toHaveBeenCalledWith("beta"); expect(verifyGatewayPairing).toHaveBeenCalledWith("beta"); expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); + expect(approveRestoredClonePairing).toHaveBeenCalledOnce(); + expect(verifyGatewayPairing).toHaveBeenCalledOnce(); expect(order).toEqual(["restart", "warmup", "approve", "restart", "verify"]); }); - it("repeats the handshake once when verification creates a remaining scope upgrade (#7431)", async () => { - const order: string[] = []; - const verifyGatewayPairing = vi - .fn() - .mockImplementationOnce(() => { - order.push("verify"); - return { ok: false as const, failureLayer: "scope-upgrade-pending" as const }; - }) - .mockImplementationOnce(() => { - order.push("verify"); - return { ok: true as const }; - }); - - await establishRestoredSandboxGatewayPairing("beta", { - restartRestoredSandboxGateway: vi.fn(() => { - order.push("restart"); - }), - warmupScopeUpgrade: vi.fn(() => order.push("warmup")), - autoPairScopeApproval: vi.fn(() => order.push("approve")), - verifyGatewayPairing, - }); - - expect(order).toEqual([ - "restart", - "warmup", - "approve", - "restart", - "verify", - "warmup", - "approve", - "restart", - "verify", - ]); - }); - - it("restarts after each of two successive approved transitions before verification (#7431)", async () => { - const transitions = ["pairing", "operator.write"]; - const order: string[] = []; - let approvedTransitions = 0; - let runningTransitions = 0; - let pendingTransition: string | null = null; - const restartRestoredSandboxGateway = vi.fn(() => { - runningTransitions = approvedTransitions; - order.push(`restart:${runningTransitions}`); - }); - const warmupScopeUpgrade = vi.fn(() => { - pendingTransition = transitions[approvedTransitions] ?? null; - order.push(`warmup:${pendingTransition ?? "none"}`); - }); - const autoPairScopeApproval = vi.fn(() => { - order.push(`approve:${pendingTransition ?? "none"}`); - expect(pendingTransition).toBe(transitions[approvedTransitions]); - approvedTransitions += 1; - pendingTransition = null; - }); - const verifyGatewayPairing = vi.fn(() => { - order.push(`verify:${runningTransitions}`); - return runningTransitions === transitions.length - ? { ok: true as const } - : { ok: false as const, failureLayer: "scope-upgrade-pending" as const }; - }); - - await establishRestoredSandboxGatewayPairing("beta", { - restartRestoredSandboxGateway, - warmupScopeUpgrade, - autoPairScopeApproval, - verifyGatewayPairing, - }); - - expect(order).toEqual([ - "restart:0", - "warmup:pairing", - "approve:pairing", - "restart:1", - "verify:1", - "warmup:operator.write", - "approve:operator.write", - "restart:2", - "verify:2", - ]); - expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(3); - expect(warmupScopeUpgrade).toHaveBeenCalledTimes(2); - expect(autoPairScopeApproval).toHaveBeenCalledTimes(2); - expect(verifyGatewayPairing).toHaveBeenCalledTimes(2); - }); - it("fails before pairing when the restored gateway cannot restart (#7431)", async () => { const warmupScopeUpgrade = vi.fn(); - const autoPairScopeApproval = vi.fn(); + const approveRestoredClonePairing = vi.fn(); const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); await expect( @@ -137,12 +53,12 @@ describe("establishRestoredSandboxGatewayPairing", () => { throw new Error("gateway did not restart"); }), warmupScopeUpgrade, - autoPairScopeApproval, + approveRestoredClonePairing, verifyGatewayPairing, }), ).rejects.toThrow("gateway did not restart"); expect(warmupScopeUpgrade).not.toHaveBeenCalled(); - expect(autoPairScopeApproval).not.toHaveBeenCalled(); + expect(approveRestoredClonePairing).not.toHaveBeenCalled(); expect(verifyGatewayPairing).not.toHaveBeenCalled(); }); @@ -156,7 +72,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { throw new Error("gateway did not restart after approval"); }); const warmupScopeUpgrade = vi.fn(() => order.push("warmup")); - const autoPairScopeApproval = vi.fn(() => order.push("approve")); + const approveRestoredClonePairing = vi.fn(() => order.push("approve")); const verifyGatewayPairing = vi.fn(() => { order.push("verify"); return { ok: true as const }; @@ -166,7 +82,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { establishRestoredSandboxGatewayPairing("beta", { restartRestoredSandboxGateway, warmupScopeUpgrade, - autoPairScopeApproval, + approveRestoredClonePairing, verifyGatewayPairing, }), ).rejects.toThrow("gateway did not restart after approval"); @@ -179,48 +95,42 @@ describe("establishRestoredSandboxGatewayPairing", () => { const warmupScopeUpgrade = vi.fn(() => { throw new Error("gateway not up"); }); - const autoPairScopeApproval = vi.fn(); + const approveRestoredClonePairing = vi.fn(); const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); await expect( establishRestoredSandboxGatewayPairing("beta", { restartRestoredSandboxGateway: vi.fn(() => {}), warmupScopeUpgrade, - autoPairScopeApproval, + approveRestoredClonePairing, verifyGatewayPairing, }), ).rejects.toThrow("gateway not up"); - expect(autoPairScopeApproval).not.toHaveBeenCalled(); + expect(approveRestoredClonePairing).not.toHaveBeenCalled(); expect(verifyGatewayPairing).not.toHaveBeenCalled(); }); - it("fails when two authenticated verification runs cannot use the restored gateway (#7431)", async () => { + it("fails after one ordinary verifier without retrying the handshake (#7431)", async () => { const restartRestoredSandboxGateway = vi.fn(); const warmupScopeUpgrade = vi.fn(); - const autoPairScopeApproval = vi.fn(); - const verifyGatewayPairing = vi - .fn() - .mockReturnValueOnce({ - ok: false as const, - failureLayer: "device-pairing-required" as const, - }) - .mockReturnValueOnce({ - ok: false as const, - failureLayer: "scope-upgrade-pending" as const, - }); + const approveRestoredClonePairing = vi.fn(); + const verifyGatewayPairing = vi.fn(() => ({ + ok: false as const, + failureLayer: "scope-upgrade-pending" as const, + })); await expect( establishRestoredSandboxGatewayPairing("beta", { restartRestoredSandboxGateway, warmupScopeUpgrade, - autoPairScopeApproval, + approveRestoredClonePairing, verifyGatewayPairing, }), ).rejects.toThrow("authenticated gateway verification run failed (scope-upgrade-pending)"); - expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(3); - expect(warmupScopeUpgrade).toHaveBeenCalledTimes(2); - expect(autoPairScopeApproval).toHaveBeenCalledTimes(2); - expect(verifyGatewayPairing).toHaveBeenCalledTimes(2); + expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); + expect(warmupScopeUpgrade).toHaveBeenCalledOnce(); + expect(approveRestoredClonePairing).toHaveBeenCalledOnce(); + expect(verifyGatewayPairing).toHaveBeenCalledOnce(); }); }); diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.ts b/src/lib/actions/sandbox/restore-gateway-pairing.ts index 144d876a60d..dbf2c738998 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.ts @@ -5,22 +5,29 @@ import { type RestoreGatewayPairingVerificationResult, verifyRestoredSandboxGatewayPairing, } from "../../adapters/openshell/restore-gateway-pairing"; +import { runSandboxAutoPairApprovalPass } from "./auto-pair-approval"; +import { + CONNECT_AUTO_PAIR_APPROVE_TIMEOUT_S, + CONNECT_AUTO_PAIR_LIST_TIMEOUT_S, + CONNECT_AUTO_PAIR_MAX_APPROVALS, + CONNECT_AUTO_PAIR_TIMEOUT_MS, +} from "./connect-autopair-budget"; import type { GatewayRestartResult } from "./gateway-restart"; import { WARMUP_SESSION_ID_PREFIX } from "./warmup-session"; export type RestoreGatewayPairingDeps = { restartRestoredSandboxGateway: (sandboxName: string) => void; warmupScopeUpgrade: (sandboxName: string) => void; - autoPairScopeApproval: (sandboxName: string) => void; + approveRestoredClonePairing: (sandboxName: string) => void; verifyGatewayPairing: (sandboxName: string) => RestoreGatewayPairingVerificationResult; }; -// A restored clone starts without runtime device credentials. Restart once so -// its gateway serves the restored state. Each warm-up can provoke one -// allowlisted transition, but approved state is not visible until the gateway -// restarts. Strict verification can then provoke the remaining operator.write -// upgrade, so permit one bounded recovery cycle. -const RESTORE_GATEWAY_PAIRING_CYCLES = 2; +const RESTORED_CLONE_PAIRING_BUDGET = { + maxApprovals: CONNECT_AUTO_PAIR_MAX_APPROVALS, + listTimeoutS: CONNECT_AUTO_PAIR_LIST_TIMEOUT_S, + approveTimeoutS: CONNECT_AUTO_PAIR_APPROVE_TIMEOUT_S, + timeoutMs: CONNECT_AUTO_PAIR_TIMEOUT_MS, +} as const; type RestoredSandboxGatewayRestartDeps = { restartSandboxGateway: ( @@ -45,13 +52,19 @@ export function restartRestoredSandboxGateway( } } +export function approveRestoredClonePairing(sandboxName: string): void { + runSandboxAutoPairApprovalPass(sandboxName, { + budget: RESTORED_CLONE_PAIRING_BUDGET, + localDeviceOnly: true, + }); +} + function defaultRestoreGatewayPairingDeps(): RestoreGatewayPairingDeps { const warmup: typeof import("./auto-pair-warmup") = require("./auto-pair-warmup"); - const connect: typeof import("./connect") = require("./connect"); return { restartRestoredSandboxGateway, warmupScopeUpgrade: warmup.runSandboxScopeWarmupRun, - autoPairScopeApproval: connect.runConnectAutoPairApprovalPass, + approveRestoredClonePairing, verifyGatewayPairing: (sandboxName) => verifyRestoredSandboxGatewayPairing(sandboxName, WARMUP_SESSION_ID_PREFIX), }; @@ -62,24 +75,18 @@ export async function establishRestoredSandboxGatewayPairing( deps: RestoreGatewayPairingDeps = defaultRestoreGatewayPairingDeps(), ): Promise { try { - let lastFailure: Extract | null = null; deps.restartRestoredSandboxGateway(targetSandbox); - for (let cycle = 0; cycle < RESTORE_GATEWAY_PAIRING_CYCLES; cycle += 1) { - deps.warmupScopeUpgrade(targetSandbox); - deps.autoPairScopeApproval(targetSandbox); - // Publish the approved transition to the running gateway before strict - // verification. This also recovers the host forward through the existing - // supervisor-mediated restart path. - deps.restartRestoredSandboxGateway(targetSandbox); - const verification = deps.verifyGatewayPairing(targetSandbox); - if (verification.ok) { - return; - } - lastFailure = verification; + deps.warmupScopeUpgrade(targetSandbox); + deps.approveRestoredClonePairing(targetSandbox); + // Publish the clone's approved pairing transition before the one ordinary + // authenticated verifier. The verifier alone decides success. + deps.restartRestoredSandboxGateway(targetSandbox); + const verification = deps.verifyGatewayPairing(targetSandbox); + if (!verification.ok) { + throw new Error( + `the authenticated gateway verification run failed (${verification.failureLayer})`, + ); } - throw new Error( - `the authenticated gateway verification run failed (${lastFailure?.failureLayer ?? "unknown"})`, - ); } catch (err) { throw new Error( `could not establish gateway pairing for '${targetSandbox}': ${ diff --git a/test/e2e/live/snapshot-commands-helpers.ts b/test/e2e/live/snapshot-commands-helpers.ts index 9f7f078009e..4e7df1de19f 100644 --- a/test/e2e/live/snapshot-commands-helpers.ts +++ b/test/e2e/live/snapshot-commands-helpers.ts @@ -9,6 +9,50 @@ export interface SnapshotInferenceFixture { model: string; } +export type SnapshotGatewayProbeClassification = + | "authenticated" + | "command-failure" + | "empty-output" + | "embedded-fallback" + | "gateway-connect-failure" + | "scope-upgrade-pending" + | "device-pairing-required"; + +const SNAPSHOT_GATEWAY_PROBE_REJECTIONS: ReadonlyArray<{ + pattern: RegExp; + classification: SnapshotGatewayProbeClassification; +}> = [ + { + pattern: /scope upgrade pending approval|pairing required: device is asking for more scopes/i, + classification: "scope-upgrade-pending", + }, + { + pattern: /device pairing required|pairing required/i, + classification: "device-pairing-required", + }, + { + pattern: /gateway connect failed/i, + classification: "gateway-connect-failure", + }, + { + pattern: /EMBEDDED FALLBACK|fallbackFrom[": ]+gateway|transport[": ]+embedded/i, + classification: "embedded-fallback", + }, +]; + +export function classifySnapshotGatewayProbe(result: { + exitCode: number | null; + stdout: string; + stderr: string; +}): SnapshotGatewayProbeClassification { + const output = `${result.stdout}\n${result.stderr}`; + const rejection = SNAPSHOT_GATEWAY_PROBE_REJECTIONS.find(({ pattern }) => pattern.test(output)); + if (rejection) return rejection.classification; + if (result.exitCode !== 0) return "command-failure"; + if (!output.trim()) return "empty-output"; + return "authenticated"; +} + /** * Builds the child env for the snapshot-commands live target. * diff --git a/test/e2e/live/snapshot-commands.test.ts b/test/e2e/live/snapshot-commands.test.ts index e1c7886932d..43d45a583b3 100644 --- a/test/e2e/live/snapshot-commands.test.ts +++ b/test/e2e/live/snapshot-commands.test.ts @@ -25,6 +25,7 @@ import { startFakeOpenAiCompatibleServer } from "../fixtures/fake-openai-compati import { REPO_ROOT } from "../fixtures/paths.ts"; import { buildSnapshotCommandEnv, + classifySnapshotGatewayProbe, type SnapshotInferenceFixture, } from "./snapshot-commands-helpers.ts"; import { scanSnapshotCredentialLeaks } from "./snapshot-credential-scanner.ts"; @@ -44,11 +45,12 @@ const BASELINE_EXCLUSION_KEY = "openclaw_docs"; const LIVE_TIMEOUT_MS = 36 * 60_000; const INFERENCE_API_KEY = "nvapi-snapshot-commands-fixture-credential"; const INFERENCE_MODEL = "snapshot-commands-model"; -const RESTORED_GATEWAY_REJECTION = - /EMBEDDED FALLBACK|gateway connect failed|scope upgrade pending approval|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded/i; -function commandEnv(inference?: SnapshotInferenceFixture): NodeJS.ProcessEnv { - return buildSnapshotCommandEnv(SANDBOX_NAME, inference); +function commandEnv( + inference?: SnapshotInferenceFixture, + sandboxName = SANDBOX_NAME, +): NodeJS.ProcessEnv { + return buildSnapshotCommandEnv(sandboxName, inference); } async function bestEffortPreclean(run: () => Promise): Promise { @@ -108,6 +110,7 @@ async function expectSandboxFileContent( async function expectAuthenticatedGatewayPairing( sandbox: SandboxClient, sandboxName: string, + inference: SnapshotInferenceFixture, artifactName: string, ): Promise { const result = await sandbox.execShell( @@ -121,13 +124,11 @@ openclaw agent --agent main --json -m "ping" \ `), { artifactName, - env: commandEnv(), + env: commandEnv(inference, sandboxName), timeoutMs: 60_000, }, ); - expect(result.exitCode, resultText(result)).toBe(0); - expect(resultText(result).trim()).not.toBe(""); - expect(resultText(result)).not.toMatch(RESTORED_GATEWAY_REJECTION); + expect(classifySnapshotGatewayProbe(result)).toBe("authenticated"); } async function expectBaselineExclusionAgreement( @@ -431,6 +432,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- await expectAuthenticatedGatewayPairing( sandbox, CLONE_SANDBOX_NAME, + inferenceConfig, "phase-4-verify-clone-gateway-pairing", ); expect(inference.requests().slice(clonePairingRequestOffset)).toContainEqual( diff --git a/test/e2e/support/snapshot-commands-helpers.test.ts b/test/e2e/support/snapshot-commands-helpers.test.ts index fb629828a6a..9b613d53a30 100644 --- a/test/e2e/support/snapshot-commands-helpers.test.ts +++ b/test/e2e/support/snapshot-commands-helpers.test.ts @@ -4,10 +4,14 @@ import { afterEach, describe, expect, it } from "vitest"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; -import { buildSnapshotCommandEnv } from "../live/snapshot-commands-helpers.ts"; +import { + buildSnapshotCommandEnv, + classifySnapshotGatewayProbe, +} from "../live/snapshot-commands-helpers.ts"; const HOSTED_FLAG = "NEMOCLAW_E2E_USE_HOSTED_INFERENCE"; const SANDBOX_NAME = "e2e-snapshot"; +const CLONE_SANDBOX_NAME = `${SANDBOX_NAME}-clone`; const INFERENCE = { apiKey: "nvapi-snapshot-commands-fixture-credential", @@ -61,6 +65,20 @@ describe("snapshot commands live env helper", () => { }); }); + it("binds the restored clone probe to its name and hermetic inference fixture", () => { + const env = buildSnapshotCommandEnv(CLONE_SANDBOX_NAME, INFERENCE); + + expect(env).toMatchObject({ + COMPATIBLE_API_KEY: INFERENCE.apiKey, + NEMOCLAW_COMPAT_MODEL: INFERENCE.model, + NEMOCLAW_ENDPOINT_URL: INFERENCE.endpointUrl, + NEMOCLAW_MODEL: INFERENCE.model, + NEMOCLAW_PROVIDER: "custom", + NEMOCLAW_SANDBOX_NAME: CLONE_SANDBOX_NAME, + }); + expect(env.NEMOCLAW_SANDBOX_NAME).not.toBe(SANDBOX_NAME); + }); + it("leaves inference selection unset when no fixture is staged", () => { const env = buildSnapshotCommandEnv(SANDBOX_NAME); @@ -85,3 +103,29 @@ describe("snapshot commands live env helper", () => { } }); }); + +describe("snapshot restored-gateway probe classification", () => { + it.each([ + [{ exitCode: 0, stdout: '{"ok":true}', stderr: "" }, "authenticated"], + [{ exitCode: 1, stdout: "", stderr: "opaque command failure" }, "command-failure"], + [{ exitCode: 0, stdout: "", stderr: "" }, "empty-output"], + [{ exitCode: 0, stdout: "EMBEDDED FALLBACK secret-output", stderr: "" }, "embedded-fallback"], + [ + { exitCode: 1, stdout: "", stderr: "gateway connect failed token=secret-output" }, + "gateway-connect-failure", + ], + [ + { exitCode: 0, stdout: "scope upgrade pending approval secret-output", stderr: "" }, + "scope-upgrade-pending", + ], + [ + { exitCode: 0, stdout: "device pairing required secret-output", stderr: "" }, + "device-pairing-required", + ], + ] as const)("returns only fixed classification %#", (result, expected) => { + const classification = classifySnapshotGatewayProbe(result); + + expect(classification).toBe(expected); + expect(classification).not.toContain("secret-output"); + }); +}); From b5c6baf02abd6ee17d88e819e25fecf6ff77cb2f Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 03:02:21 -0700 Subject: [PATCH 08/14] test(restore): keep clone pairing test linear Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/auto-pair-approval.test.ts | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/lib/actions/sandbox/auto-pair-approval.test.ts b/src/lib/actions/sandbox/auto-pair-approval.test.ts index c6a3654deec..9418bbc62be 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.test.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.test.ts @@ -179,10 +179,10 @@ process.exit(2); } }); - it("approves only one exact local clone pairing transition on a shared gateway", () => { - if (spawnSync("sh", ["-c", "command -v python3"], { stdio: "ignore" }).status !== 0) { - return; - } + const pyIt = + spawnSync("sh", ["-c", "command -v python3"], { stdio: "ignore" }).status === 0 ? it : it.skip; + + pyIt("approves only one exact local clone pairing transition on a shared gateway", () => { const policy = readAutoPairApprovalPolicyModule(); expect(policy).toBeTruthy(); const script = buildAutoPairApprovalScript( From d9c56ca81a6bcf758cb582793b8f9d9e83fa16cc Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 04:23:45 -0700 Subject: [PATCH 09/14] fix(restore): approve merged clone pairing request Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/auto-pair-approval.test.ts | 14 +++++++++++++- src/lib/actions/sandbox/auto-pair-approval.ts | 7 +++++-- test/e2e/live/snapshot-commands-helpers.ts | 14 ++++++++++++++ test/e2e/live/snapshot-commands.test.ts | 13 +++++-------- test/e2e/support/snapshot-commands-helpers.test.ts | 14 ++++++++++++++ 5 files changed, 51 insertions(+), 11 deletions(-) diff --git a/src/lib/actions/sandbox/auto-pair-approval.test.ts b/src/lib/actions/sandbox/auto-pair-approval.test.ts index 9418bbc62be..8902dc203c3 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.test.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.test.ts @@ -287,12 +287,22 @@ process.exit(2); requestId: "clone-write-upgrade", isRepair: true, scopes: ["operator.pairing", "operator.write"], - requestedScopes: ["operator.pairing", "operator.write"], }; const repair = run([foreignRequest, repairRequest]); expect(repair.status).toBe(0); expect(repair.stdout).toContain(`${SUMMARY_MARKER}=1`); expect(readApprovals()).toEqual(["clone-write-upgrade"]); + resetLogs(); + const combinedInitialRequest = { + ...localRequest, + requestId: "clone-pairing-with-write", + isRepair: false, + scopes: ["operator.pairing", "operator.write"], + }; + const combinedInitial = run([foreignRequest, combinedInitialRequest]); + expect(combinedInitial.status).toBe(0); + expect(combinedInitial.stdout).toContain(`${SUMMARY_MARKER}=1`); + expect(readApprovals()).toEqual(["clone-pairing-with-write"]); const { scopes: _ignoredScopes, ...repairWithoutScopes } = repairRequest; for (const rejected of [ @@ -301,7 +311,9 @@ process.exit(2); [repairRequest, { ...repairRequest, requestId: "second-clone-upgrade" }], [repairRequest, { ...foreignRequest, requestId: repairRequest.requestId }], [{ ...repairRequest, requestedScopes: ["operator.admin"] }], + [{ ...repairRequest, requestedScopes: repairRequest.scopes }], [{ ...repairRequest, scopes: [] }], + [{ ...localRequest, requestId: "unpaired-write-only", scopes: ["operator.write"] }], [repairWithoutScopes], ]) { resetLogs(); diff --git a/src/lib/actions/sandbox/auto-pair-approval.ts b/src/lib/actions/sandbox/auto-pair-approval.ts index fe99d2a0022..1c6acdd9240 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.ts @@ -161,7 +161,7 @@ def normalized_roles(device): return roles def consistent_scope_view(device): - if 'scopes' not in device: + if 'scopes' not in device or 'requestedScopes' in device: return None views = [] for key in ('scopes', 'requestedScopes'): @@ -228,7 +228,10 @@ def is_local_pairing_transition(device): return 'operator.write' in scopes if is_repair not in (None, False): return False - return scopes == {'operator.pairing'} + return ( + scopes == {'operator.pairing'} + or {'operator.pairing', 'operator.write'}.issubset(scopes) + ) related_pending = [ device for device in pending diff --git a/test/e2e/live/snapshot-commands-helpers.ts b/test/e2e/live/snapshot-commands-helpers.ts index 4e7df1de19f..89cacf65082 100644 --- a/test/e2e/live/snapshot-commands-helpers.ts +++ b/test/e2e/live/snapshot-commands-helpers.ts @@ -17,6 +17,10 @@ export type SnapshotGatewayProbeClassification = | "gateway-connect-failure" | "scope-upgrade-pending" | "device-pairing-required"; +export type SnapshotRestoreResultClassification = + | "restored" + | "command-failure" + | "missing-restored-marker"; const SNAPSHOT_GATEWAY_PROBE_REJECTIONS: ReadonlyArray<{ pattern: RegExp; @@ -52,6 +56,16 @@ export function classifySnapshotGatewayProbe(result: { if (!output.trim()) return "empty-output"; return "authenticated"; } +export function classifySnapshotRestoreResult(result: { + exitCode: number | null; + stdout: string; + stderr: string; +}): SnapshotRestoreResultClassification { + if (result.exitCode !== 0) return "command-failure"; + return /\bRestored\b/.test(`${result.stdout}\n${result.stderr}`) + ? "restored" + : "missing-restored-marker"; +} /** * Builds the child env for the snapshot-commands live target. diff --git a/test/e2e/live/snapshot-commands.test.ts b/test/e2e/live/snapshot-commands.test.ts index 43d45a583b3..aa6bd504d15 100644 --- a/test/e2e/live/snapshot-commands.test.ts +++ b/test/e2e/live/snapshot-commands.test.ts @@ -26,6 +26,7 @@ import { REPO_ROOT } from "../fixtures/paths.ts"; import { buildSnapshotCommandEnv, classifySnapshotGatewayProbe, + classifySnapshotRestoreResult, type SnapshotInferenceFixture, } from "./snapshot-commands-helpers.ts"; import { scanSnapshotCredentialLeaks } from "./snapshot-credential-scanner.ts"; @@ -413,8 +414,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- timeoutMs: 5 * 60_000, }, ); - expect(cloneRestore.exitCode, resultText(cloneRestore)).toBe(0); - expect(resultText(cloneRestore)).toContain("Restored"); + expect(classifySnapshotRestoreResult(cloneRestore)).toBe("restored"); await expectSandboxFileContent( sandbox, CLONE_SANDBOX_NAME, @@ -493,8 +493,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- env: commandEnv(), timeoutMs: 120_000, }); - expect(latestRestore.exitCode, resultText(latestRestore)).toBe(0); - expect(resultText(latestRestore)).toContain("Restored"); + expect(classifySnapshotRestoreResult(latestRestore)).toBe("restored"); await expectSandboxFileContent( sandbox, SANDBOX_NAME, @@ -522,8 +521,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- timeoutMs: 120_000, }, ); - expect(targetedRestore.exitCode, resultText(targetedRestore)).toBe(0); - expect(resultText(targetedRestore)).toContain("Restored"); + expect(classifySnapshotRestoreResult(targetedRestore)).toBe("restored"); await expectSandboxFileContent( sandbox, SANDBOX_NAME, @@ -660,8 +658,7 @@ test("snapshot commands preserve create/list/latest restore/targeted restore/no- timeoutMs: 120_000, }, ); - expect(restoreStoppedBackup.exitCode, resultText(restoreStoppedBackup)).toBe(0); - expect(resultText(restoreStoppedBackup)).toContain("Restored"); + expect(classifySnapshotRestoreResult(restoreStoppedBackup)).toBe("restored"); await expectSandboxFileContent( sandbox, SANDBOX_NAME, diff --git a/test/e2e/support/snapshot-commands-helpers.test.ts b/test/e2e/support/snapshot-commands-helpers.test.ts index 9b613d53a30..fd6de5e41b3 100644 --- a/test/e2e/support/snapshot-commands-helpers.test.ts +++ b/test/e2e/support/snapshot-commands-helpers.test.ts @@ -7,6 +7,7 @@ import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { buildSnapshotCommandEnv, classifySnapshotGatewayProbe, + classifySnapshotRestoreResult, } from "../live/snapshot-commands-helpers.ts"; const HOSTED_FLAG = "NEMOCLAW_E2E_USE_HOSTED_INFERENCE"; @@ -129,3 +130,16 @@ describe("snapshot restored-gateway probe classification", () => { expect(classification).not.toContain("secret-output"); }); }); + +describe("snapshot restore result classification", () => { + it.each([ + [{ exitCode: 0, stdout: "Restored secret-output", stderr: "" }, "restored"], + [{ exitCode: 1, stdout: "Restored secret-output", stderr: "" }, "command-failure"], + [{ exitCode: 0, stdout: "secret-output", stderr: "" }, "missing-restored-marker"], + ] as const)("returns only fixed classification %#", (result, expected) => { + const classification = classifySnapshotRestoreResult(result); + + expect(classification).toBe(expected); + expect(classification).not.toContain("secret-output"); + }); +}); From c45892130795ce1e22143af00046b386bb24ee72 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 04:39:51 -0700 Subject: [PATCH 10/14] test(restore): reject invalid clone identity Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/auto-pair-approval.test.ts | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/lib/actions/sandbox/auto-pair-approval.test.ts b/src/lib/actions/sandbox/auto-pair-approval.test.ts index 8902dc203c3..f288fbc173e 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.test.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.test.ts @@ -322,6 +322,18 @@ process.exit(2); expect(result.stdout).not.toContain(`${SUMMARY_MARKER}=1`); expect(readApprovals()).toEqual([]); } + + resetLogs(); + const hashMismatchedDeviceId = "0".repeat(64); + fs.writeFileSync( + path.join(identityDir, "device.json"), + JSON.stringify({ deviceId: hashMismatchedDeviceId, publicKey }), + ); + const invalidIdentity = run([{ ...localRequest, deviceId: hashMismatchedDeviceId }]); + expect(invalidIdentity.status).toBe(0); + expect(invalidIdentity.stdout).not.toContain(`${SUMMARY_MARKER}=1`); + expect(readApprovals()).toEqual([]); + expect(fs.existsSync(approveEnvFile)).toBe(false); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } From d80817e350f2a2b0915603c20c2d58ac97d6a090 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 05:30:09 -0700 Subject: [PATCH 11/14] fix(restore): approve bounded write-only clone request Signed-off-by: Carlos Villela --- src/lib/actions/sandbox/auto-pair-approval.test.ts | 13 ++++++++++++- src/lib/actions/sandbox/auto-pair-approval.ts | 5 +---- 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/lib/actions/sandbox/auto-pair-approval.test.ts b/src/lib/actions/sandbox/auto-pair-approval.test.ts index f288fbc173e..9f3e2876018 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.test.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.test.ts @@ -303,6 +303,17 @@ process.exit(2); expect(combinedInitial.status).toBe(0); expect(combinedInitial.stdout).toContain(`${SUMMARY_MARKER}=1`); expect(readApprovals()).toEqual(["clone-pairing-with-write"]); + resetLogs(); + const writeOnlyInitialRequest = { + ...localRequest, + requestId: "clone-write-only", + isRepair: false, + scopes: ["operator.write"], + }; + const writeOnlyInitial = run([foreignRequest, writeOnlyInitialRequest]); + expect(writeOnlyInitial.status).toBe(0); + expect(writeOnlyInitial.stdout).toContain(`${SUMMARY_MARKER}=1`); + expect(readApprovals()).toEqual(["clone-write-only"]); const { scopes: _ignoredScopes, ...repairWithoutScopes } = repairRequest; for (const rejected of [ @@ -313,7 +324,7 @@ process.exit(2); [{ ...repairRequest, requestedScopes: ["operator.admin"] }], [{ ...repairRequest, requestedScopes: repairRequest.scopes }], [{ ...repairRequest, scopes: [] }], - [{ ...localRequest, requestId: "unpaired-write-only", scopes: ["operator.write"] }], + [{ ...localRequest, requestId: "unpaired-read-only", scopes: ["operator.read"] }], [repairWithoutScopes], ]) { resetLogs(); diff --git a/src/lib/actions/sandbox/auto-pair-approval.ts b/src/lib/actions/sandbox/auto-pair-approval.ts index 1c6acdd9240..a03fae2a7b7 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.ts @@ -228,10 +228,7 @@ def is_local_pairing_transition(device): return 'operator.write' in scopes if is_repair not in (None, False): return False - return ( - scopes == {'operator.pairing'} - or {'operator.pairing', 'operator.write'}.issubset(scopes) - ) + return scopes == {'operator.pairing'} or 'operator.write' in scopes related_pending = [ device for device in pending From 9f439dfd418d89be4870c4f3378c57af8a530b3c Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 07:00:11 -0700 Subject: [PATCH 12/14] fix(openclaw): approve bounded pre-convergence write Signed-off-by: Carlos Villela --- .../patch-openclaw-device-self-approval.mts | 28 ++++++++++---- ...penclaw-real-device-self-approval-proof.ts | 9 +++-- ...penclaw-device-self-approval-patch.test.ts | 31 +++++++++------ .../openclaw-device-stored-auth-patch.test.ts | 38 +++++++++++-------- 4 files changed, 68 insertions(+), 38 deletions(-) diff --git a/scripts/patch-openclaw-device-self-approval.mts b/scripts/patch-openclaw-device-self-approval.mts index 5ba994a0874..efb059a56ca 100644 --- a/scripts/patch-openclaw-device-self-approval.mts +++ b/scripts/patch-openclaw-device-self-approval.mts @@ -18,10 +18,11 @@ * signed identity keeps the paired-device scope check authoritative and lets * OpenClaw create a canonical pending scope-upgrade request. Keep the entire * approval in OpenClaw instead: for the exact bounded CLI mismatch, continue - * only into OpenClaw's pairing gate; for the resulting same-device repair, - * explicitly use OpenClaw's stored device credential with operator.pairing, - * then let the gateway's canonical approveDevicePairing path reload, lock, - * rotate the token, persist, broadcast, and respond. + * only into OpenClaw's pairing gate. For the resulting same-device scope + * transition, including an operator.write request created before paired-state + * convergence, explicitly use OpenClaw's stored device credential with + * operator.pairing. Then let the gateway's canonical approveDevicePairing path + * reload, lock, rotate the token, persist, broadcast, and respond. * * Remove this patch when upstream OpenClaw supports same-device, operator-only * scope approval through the gateway using the already-approved pairing scope @@ -180,13 +181,17 @@ const CLI_HELPER = [ "\tconst nemoclawPairedScopes = resolvePairedOperatorScopes(nemoclawPairedView);", "\tconst nemoclawPairingBaselineVisible = nemoclawPairedScopes.length > 0;", '\tconst nemoclawNormalizedRawScopes = Array.isArray(nemoclawRawScopes) ? nemoclawRawScopes.map((scope) => typeof scope === "string" ? scope.trim() : "") : [];', + "\tconst nemoclawNonRepairWriteTransition =", + "\t\trequest.isRepair === false &&", + '\t\tnemoclawNormalizedRawScopes.includes("operator.write") &&', + "\t\tnemoclawPairedScopes.includes(PAIRING_SCOPE);", "\tconst nemoclawUsePairingTransport =", "\t\tArray.isArray(nemoclawRawScopes) &&", "\t\tnemoclawRawScopes.length > 0 &&", '\t\tnemoclawRawScopes.every((scope) => typeof scope === "string" && scope.trim() && isKnownNonAdminOperatorScope(scope.trim())) &&', "\t\trequest.clientId === GATEWAY_CLIENT_NAMES.CLI &&", "\t\trequest.clientMode === GATEWAY_CLIENT_MODES.CLI &&", - "\t\trequest.isRepair === true &&", + "\t\t(request.isRepair === true || nemoclawNonRepairWriteTransition) &&", "\t\tnemoclawRoles.length === 1 &&", "\t\tnemoclawRoles[0] === OPERATOR_ROLE &&", "\t\t(!nemoclawPairingBaselineVisible || nemoclawPairedScopes.includes(PAIRING_SCOPE));", @@ -373,7 +378,7 @@ const AUTH_DEVICE_TOKEN_REPLACEMENT = [ const HANDLER_HELPER = [ "function resolveNemoClawSelfApprovalIdentity(pending, authz, client) {", - "\tif (authz.isAdminCaller || client?.isDeviceTokenAuth !== true || pending?.isRepair !== true) return null;", + "\tif (authz.isAdminCaller || client?.isDeviceTokenAuth !== true) return null;", '\tconst callerDeviceId = typeof authz.callerDeviceId === "string" ? authz.callerDeviceId.trim() : "";', '\tconst clientDeviceId = typeof client?.connect?.device?.id === "string" ? client.connect.device.id.trim() : "";', '\tconst pendingDeviceId = typeof pending?.deviceId === "string" ? pending.deviceId.trim() : "";', @@ -413,6 +418,14 @@ const HANDLER_HELPER = [ "\t}", '\tif (roles.size !== 1 || !roles.has("operator")) return null;', "\tif (!Array.isArray(pending.scopes) || pending.scopes.length === 0) return null;", + "\tconst nemoclawPendingScopes = new Set();", + "\tfor (const scope of pending.scopes) {", + '\t\tif (typeof scope !== "string") return null;', + "\t\tconst normalized = scope.trim();", + '\t\tif (!normalized || !["operator.pairing", "operator.read", "operator.write"].includes(normalized) || nemoclawPendingScopes.has(normalized)) return null;', + "\t\tnemoclawPendingScopes.add(normalized);", + "\t}", + '\tif (pending.isRepair !== true && (pending.isRepair !== false || !nemoclawPendingScopes.has("operator.write"))) return null;', "\treturn { deviceId: callerDeviceId, publicKey: clientPublicKey, role: clientRole, clientId, clientMode };", "} // nemoclaw: bounded same-device scope approval (#4462)", "", @@ -593,7 +606,7 @@ const STATE_HELPER = [ 'const NEMOCLAW_SELF_APPROVAL_SCOPE_ORDER = ["operator.pairing", "operator.read", "operator.write"];', "const NEMOCLAW_SELF_APPROVAL_ALLOWED_SCOPES = new Set(NEMOCLAW_SELF_APPROVAL_SCOPE_ORDER);", "function resolveNemoClawSelfApprovalScopes(pending, callerScopes, identity) {", - '\tif (!identity || !Array.isArray(callerScopes) || !callerScopes.includes("operator.pairing") || pending?.isRepair !== true) return null;', + '\tif (!identity || !Array.isArray(callerScopes) || !callerScopes.includes("operator.pairing")) return null;', '\tconst expectedDeviceId = typeof identity.deviceId === "string" ? identity.deviceId.trim() : "";', '\tconst expectedPublicKey = typeof identity.publicKey === "string" ? identity.publicKey.trim() : "";', '\tconst expectedRole = typeof identity.role === "string" ? identity.role.trim() : "";', @@ -637,6 +650,7 @@ const STATE_HELPER = [ "\t\tscopes.add(normalized);", "\t}", '\tif (scopes.has("operator.write")) scopes.add("operator.read");', + '\tif (pending.isRepair !== true && (pending.isRepair !== false || !scopes.has("operator.write"))) return null;', '\tif (scopes.has("operator.read") || scopes.has("operator.write")) scopes.add("operator.pairing");', "\treturn NEMOCLAW_SELF_APPROVAL_SCOPE_ORDER.filter((scope) => scopes.has(scope));", "} // nemoclaw: validate bounded self-approval inside pairing lock (#4462)", diff --git a/test/helpers/openclaw-real-device-self-approval-proof.ts b/test/helpers/openclaw-real-device-self-approval-proof.ts index 4fd2a5f1ba7..c58aac592df 100644 --- a/test/helpers/openclaw-real-device-self-approval-proof.ts +++ b/test/helpers/openclaw-real-device-self-approval-proof.ts @@ -1269,7 +1269,7 @@ export async function runRealOpenClawDeviceSelfApprovalProof(options: ProofOptio role: "operator", roles: ["operator"], scopes: ["operator.write"], - isRepair: true, + isRepair: false, ts: now, }, "request-1": { @@ -1281,7 +1281,7 @@ export async function runRealOpenClawDeviceSelfApprovalProof(options: ProofOptio role: "operator", roles: ["operator"], scopes: ["operator.write"], - isRepair: true, + isRepair: false, ts: now, }, "request-2": { @@ -1385,6 +1385,7 @@ const repairRequest = { scopes: ["operator.write"], isRepair: true, }; +const preconvergenceWriteRequest = { ...repairRequest, isRepair: false }; const pairingOnly = ["operator.pairing"]; const missingPairedViewScopes = nemoclawResolveApprovePairingScopesForRequest(repairRequest, undefined); if (JSON.stringify(missingPairedViewScopes) !== JSON.stringify(pairingOnly)) throw new Error("missing paired CLI view requested read/write before canonical approval"); @@ -1395,13 +1396,13 @@ const roleKeyedTokenScopes = nemoclawResolveApprovePairingScopesForRequest(repai tokens: { operator: { role: "operator", scopes: ["operator.pairing"] } }, }); if (JSON.stringify(roleKeyedTokenScopes) !== JSON.stringify(pairingOnly)) throw new Error("role-keyed paired CLI view requested read/write before canonical approval"); -const storedAuthContext = nemoclawResolveSelfRepairPairingContext(repairRequest, { +const storedAuthContext = nemoclawResolveSelfRepairPairingContext(preconvergenceWriteRequest, { deviceId: "device-1", publicKey: "public-key-1", scopes: ["operator.pairing"], tokens: { operator: { role: "operator", scopes: ["operator.pairing"] } }, }); -if (storedAuthContext?.useStoredDeviceAuth !== true) throw new Error("exact same-device repair did not select stored device auth"); +if (storedAuthContext?.useStoredDeviceAuth !== true) throw new Error("exact pre-convergence write transition did not select stored device auth"); const mismatchedStoredAuthContext = nemoclawResolveSelfRepairPairingContext(repairRequest, { deviceId: "device-1", publicKey: "other-public-key", diff --git a/test/openclaw-device-self-approval-patch.test.ts b/test/openclaw-device-self-approval-patch.test.ts index d8c5b76c91a..ce593afde97 100644 --- a/test/openclaw-device-self-approval-patch.test.ts +++ b/test/openclaw-device-self-approval-patch.test.ts @@ -350,7 +350,7 @@ describe("OpenClaw bounded device self-approval patch (#4462)", () => { resolveScopes(validPending({ isRepair: false }), { tokens: [{ role: "operator", scopes: ["operator.pairing"] }], }), - ).toEqual(["operator.pairing", "operator.read", "operator.write"]); + ).toEqual(["operator.pairing"]); expect(resolveScopes(validPending({ scopes: ["operator.admin"] }), {})).toEqual([ "operator.admin", ]); @@ -362,7 +362,7 @@ describe("OpenClaw bounded device self-approval patch (#4462)", () => { } }); - it("preflights the exact repair before both live list and approval use stored pairing auth", async () => { + it("preflights exact bounded transitions before live list and approval use stored pairing auth", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-device-cli-preflight-")); const dist = path.join(tmp, "dist"); fs.mkdirSync(dist); @@ -398,17 +398,20 @@ describe("OpenClaw bounded device self-approval patch (#4462)", () => { } runtime.gatewayCalls.length = 0; - const ordinaryList = { + const preconvergenceList = { pending: [validPending({ isRepair: false })], paired: [validPaired()], }; - runtime.setPairingLists(ordinaryList); + runtime.setPairingLists(preconvergenceList); await runtime.approvePairingWithFallback({ json: true }, "request-1"); - expect(runtime.gatewayCalls[0]).toMatchObject({ - method: "device.pair.list", - scopes: undefined, - }); - expect(runtime.gatewayCalls[0]).not.toHaveProperty("useStoredDeviceAuth"); + expect(runtime.gatewayCalls).toHaveLength(2); + for (const call of runtime.gatewayCalls) { + expect(call).toMatchObject({ + scopes: ["operator.pairing"], + useStoredDeviceAuth: true, + requiredStoredDeviceAuthScopes: ["operator.pairing"], + }); + } } finally { fs.rmSync(tmp, { recursive: true, force: true }); } @@ -453,7 +456,7 @@ describe("OpenClaw bounded device self-approval patch (#4462)", () => { } }); - it("passes authenticated identity to the canonical approver and never publishes state itself", async () => { + it("passes authenticated identity for a pre-convergence write request to the canonical approver", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-device-handler-")); const dist = path.join(tmp, "dist"); fs.mkdirSync(dist); @@ -466,7 +469,7 @@ describe("OpenClaw bounded device self-approval patch (#4462)", () => { deviceHandlers: Record) => Promise>; captured: () => { requestId: string; options: Record }; }>(source, `({ pendingById, deviceHandlers, captured: () => capturedApproval })`); - runtime.pendingById.set("request-1", validPending()); + runtime.pendingById.set("request-1", validPending({ isRepair: false })); const responses: unknown[] = []; const broadcasts: unknown[] = []; await runtime.deviceHandlers["device.pair.approve"]({ @@ -650,6 +653,9 @@ describe("OpenClaw bounded device self-approval patch (#4462)", () => { "operator.read", "operator.write", ]); + expect( + resolveScopes(validPending({ isRepair: false }), ["operator.pairing"], identity), + ).toEqual(["operator.pairing", "operator.read", "operator.write"]); for (const pending of [ validPending({ deviceId: "device-2" }), validPending({ publicKey: "public-key-2" }), @@ -661,7 +667,8 @@ describe("OpenClaw bounded device self-approval patch (#4462)", () => { validPending({ scopes: ["operator.write", "operator.write"] }), validPending({ scopes: ["operator.admin"] }), validPending({ scopes: ["operator.unknown"] }), - validPending({ isRepair: false }), + validPending({ isRepair: false, scopes: ["operator.read"] }), + validPending({ isRepair: undefined }), ]) { expect(resolveScopes(pending, ["operator.pairing"], identity)).toBeNull(); } diff --git a/test/openclaw-device-stored-auth-patch.test.ts b/test/openclaw-device-stored-auth-patch.test.ts index ad761c7bdbb..7ffbf7fd39d 100644 --- a/test/openclaw-device-stored-auth-patch.test.ts +++ b/test/openclaw-device-stored-auth-patch.test.ts @@ -16,7 +16,7 @@ import { } from "./helpers/openclaw-device-self-approval-patch-harness"; describe("OpenClaw bounded stored-device-auth selection (#4462)", () => { - it("forwards stored device auth only for the exact same-device repair", async () => { + it("forwards stored device auth only for exact same-device transitions", async () => { const tmp = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-device-cli-stored-auth-")); const dist = path.join(tmp, "dist"); fs.mkdirSync(dist); @@ -36,21 +36,24 @@ describe("OpenClaw bounded stored-device-auth selection (#4462)", () => { setList: setPairingLists, })`, ); - runtime.setList({ pending: [validPending()], paired: [validPaired()] }); + for (const pending of [validPending(), validPending({ isRepair: false })]) { + runtime.calls.length = 0; + runtime.setList({ pending: [pending], paired: [validPaired()] }); - await runtime.approve({ json: true }, "request-1"); + await runtime.approve({ json: true }, "request-1"); - expect(runtime.calls).toHaveLength(2); - for (const [method, call] of [ - ["device.pair.list", runtime.calls[0]], - ["device.pair.approve", runtime.calls[1]], - ] as const) { - expect(call).toMatchObject({ - method, - scopes: ["operator.pairing"], - useStoredDeviceAuth: true, - requiredStoredDeviceAuthScopes: ["operator.pairing"], - }); + expect(runtime.calls).toHaveLength(2); + for (const [method, call] of [ + ["device.pair.list", runtime.calls[0]], + ["device.pair.approve", runtime.calls[1]], + ] as const) { + expect(call).toMatchObject({ + method, + scopes: ["operator.pairing"], + useStoredDeviceAuth: true, + requiredStoredDeviceAuthScopes: ["operator.pairing"], + }); + } } } finally { fs.rmSync(tmp, { recursive: true, force: true }); @@ -63,7 +66,12 @@ describe("OpenClaw bounded stored-device-auth selection (#4462)", () => { ["mismatched key", validPending(), validPaired({ publicKey: "public-key-2" }), true], ["missing device", validPending({ deviceId: "" }), validPaired(), true], ["missing key", validPending({ publicKey: "" }), validPaired(), true], - ["new pairing", validPending({ isRepair: false }), validPaired(), false], + [ + "nonrepair pairing-only request", + validPending({ isRepair: false, scopes: ["operator.pairing"] }), + validPaired(), + false, + ], ["wrong client", validPending({ clientId: "openclaw-control-ui" }), validPaired(), false], ["wrong mode", validPending({ clientMode: "webchat" }), validPaired(), false], ["multiple roles", validPending({ roles: ["operator", "node"] }), validPaired(), false], From 33efd8b7fb866ebdd478b2b5ed43feb9a634af52 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 09:08:06 -0700 Subject: [PATCH 13/14] fix(snapshot): classify clone pairing approval Signed-off-by: Carlos Villela --- .../sandbox/auto-pair-approval.test.ts | 61 +++++++- src/lib/actions/sandbox/auto-pair-approval.ts | 142 +++++++++++++----- .../sandbox/restore-gateway-pairing.test.ts | 74 ++++++--- .../sandbox/restore-gateway-pairing.ts | 26 ++-- ...penclaw-real-device-self-approval-proof.ts | 30 ++++ 5 files changed, 263 insertions(+), 70 deletions(-) diff --git a/src/lib/actions/sandbox/auto-pair-approval.test.ts b/src/lib/actions/sandbox/auto-pair-approval.test.ts index 9f3e2876018..5578efbe953 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.test.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.test.ts @@ -10,10 +10,12 @@ import { describe, expect, it } from "vitest"; import { AUTO_PAIR_MAX_APPROVALS, buildAutoPairApprovalScript, + parseAutoPairApprovalReceipt, readAutoPairApprovalPolicyModule, } from "./auto-pair-approval"; const SUMMARY_MARKER = "__NEMOCLAW_AUTO_PAIR_APPROVED__"; +const RECEIPT_MARKER = "__NEMOCLAW_AUTO_PAIR_RECEIPT__"; describe("buildAutoPairApprovalScript (#4263/#4616)", () => { it("builds the bounded allowlisted approval pass", () => { @@ -33,21 +35,25 @@ describe("buildAutoPairApprovalScript (#4263/#4616)", () => { it("adds local-device filtering only for restored-clone approval", () => { const ordinary = buildAutoPairApprovalScript("UE9MSUNZ"); const restoredClone = buildAutoPairApprovalScript("UE9MSUNZ", { + emitReceipt: true, localDeviceOnly: true, budget: { maxApprovals: 1 }, }); expect(ordinary).not.toContain("local_identity_public_key"); expect(restoredClone).toContain("local_identity_public_key"); - expect(restoredClone).toContain("len(related_pending) != 1"); + expect(restoredClone).toContain("if not related_pending:"); + expect(restoredClone).toContain("len(related_pending) > 1"); expect(restoredClone).toContain("pending = related_pending"); expect(restoredClone).toContain("MAX_APPROVALS = 1"); + expect(restoredClone).toContain(RECEIPT_MARKER); }); it("omits the summary marker by default and appends it when requested", () => { const silent = buildAutoPairApprovalScript("UE9MSUNZ"); const reporting = buildAutoPairApprovalScript("UE9MSUNZ", { emitSummary: true }); expect(silent).not.toContain(SUMMARY_MARKER); + expect(silent).not.toContain(RECEIPT_MARKER); expect(reporting).toContain(`print(f'${SUMMARY_MARKER}={approved_count}')`); // The reporting script is the silent script with exactly the summary line // inserted before the heredoc terminator — nothing else changes. @@ -62,6 +68,19 @@ describe("buildAutoPairApprovalScript (#4263/#4616)", () => { expect(module).toContain("def gateway_approval_env"); expect(module).not.toContain("recover_failed_scope_approval"); }); + + it("accepts exactly one terminal fixed receipt", () => { + expect( + parseAutoPairApprovalReceipt(`ignored setup output\n${RECEIPT_MARKER}=approved-one\n`), + ).toBe("approved-one"); + for (const output of [ + `${RECEIPT_MARKER}=approved-one\nlater output\n`, + `${RECEIPT_MARKER}=approve-failed\n${RECEIPT_MARKER}=approved-one\n`, + `${RECEIPT_MARKER}=raw-request-id\n`, + ]) { + expect(parseAutoPairApprovalReceipt(output)).toBeNull(); + } + }); }); describe("auto-pair approval pass behaviour (#4616)", () => { @@ -189,6 +208,7 @@ process.exit(2); Buffer.from(policy as string, "utf-8").toString("base64"), { emitSummary: true, + emitReceipt: true, localDeviceOnly: true, budget: { maxApprovals: 1 }, }, @@ -220,6 +240,10 @@ if (args[0] === "devices" && args[1] === "list") { process.exit(0); } if (args[0] === "devices" && args[1] === "approve") { + if (process.env.NEMOCLAW_APPROVE_FAIL === "1") { + process.stderr.write("raw approval output must stay private\\n"); + process.exit(1); + } fs.appendFileSync(${JSON.stringify(approvalsFile)}, args[2] + "\\n"); fs.appendFileSync( ${JSON.stringify(approveEnvFile)}, @@ -236,13 +260,18 @@ process.exit(2); `, { mode: 0o755 }, ); - const run = (pending: unknown[]) => + const run = ( + pending: unknown[], + options: { rawListResponse?: string; failApproval?: boolean } = {}, + ) => spawnSync("sh", ["-c", script], { encoding: "utf-8", env: { ...process.env, PATH: `${tmpDir}:/usr/bin:/bin`, - NEMOCLAW_LIST_RESPONSE: JSON.stringify({ pending, paired: [] }), + NEMOCLAW_LIST_RESPONSE: + options.rawListResponse ?? JSON.stringify({ pending, paired: [] }), + NEMOCLAW_APPROVE_FAIL: options.failApproval ? "1" : "0", OPENCLAW_GATEWAY_URL: "ws://127.0.0.1:18789", OPENCLAW_GATEWAY_PORT: "18789", OPENCLAW_GATEWAY_TOKEN: "secret-token", @@ -278,6 +307,7 @@ process.exit(2); const initial = run([foreignRequest, localRequest]); expect(initial.status).toBe(0); expect(initial.stdout).toContain(`${SUMMARY_MARKER}=1`); + expect(initial.stdout).toContain(`${RECEIPT_MARKER}=approved-one`); expect(readApprovals()).toEqual(["clone-pairing"]); expect(fs.readFileSync(approveEnvFile, "utf-8").trim()).toBe("unset:unset:unset"); @@ -315,6 +345,31 @@ process.exit(2); expect(writeOnlyInitial.stdout).toContain(`${SUMMARY_MARKER}=1`); expect(readApprovals()).toEqual(["clone-write-only"]); + resetLogs(); + const listFailed = run([], { rawListResponse: "raw list output must stay private" }); + expect(listFailed.stdout).toContain(`${RECEIPT_MARKER}=list-failed`); + expect(`${listFailed.stdout}${listFailed.stderr}`).not.toContain("raw list output"); + + resetLogs(); + const noMatch = run([foreignRequest]); + expect(noMatch.stdout).toContain(`${RECEIPT_MARKER}=clone-no-match`); + + resetLogs(); + const ambiguous = run([ + repairRequest, + { ...repairRequest, requestId: "second-clone-upgrade" }, + ]); + expect(ambiguous.stdout).toContain(`${RECEIPT_MARKER}=clone-ambiguous`); + + resetLogs(); + const rejected = run([{ ...repairRequest, publicKey: "mismatched-public-key" }]); + expect(rejected.stdout).toContain(`${RECEIPT_MARKER}=request-rejected`); + + resetLogs(); + const approveFailed = run([repairRequest], { failApproval: true }); + expect(approveFailed.stdout).toContain(`${RECEIPT_MARKER}=approve-failed`); + expect(`${approveFailed.stdout}${approveFailed.stderr}`).not.toContain("raw approval output"); + const { scopes: _ignoredScopes, ...repairWithoutScopes } = repairRequest; for (const rejected of [ [foreignRequest], diff --git a/src/lib/actions/sandbox/auto-pair-approval.ts b/src/lib/actions/sandbox/auto-pair-approval.ts index a03fae2a7b7..ae0c4fae0bf 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.ts @@ -80,8 +80,34 @@ export type AutoPairApprovalResult = { reported: boolean; /** Number of pending requests approved this pass (capture mode only). */ approved: number; + /** Fixed clone-only diagnostic; never contains command output or identifiers. */ + receipt: AutoPairApprovalReceipt | null; }; +export type AutoPairApprovalReceipt = + | "policy-missing" + | "exec-failed" + | "list-failed" + | "clone-no-match" + | "clone-ambiguous" + | "request-rejected" + | "approve-failed" + | "approved-one"; + +const AUTO_PAIR_RECEIPT_LINE_RE = + /^__NEMOCLAW_AUTO_PAIR_RECEIPT__=(policy-missing|exec-failed|list-failed|clone-no-match|clone-ambiguous|request-rejected|approve-failed|approved-one)$/; + +export function parseAutoPairApprovalReceipt(output: string): AutoPairApprovalReceipt | null { + const markerPrefix = "__NEMOCLAW_AUTO_PAIR_RECEIPT__="; + const receiptLines = output.split(/\r?\n/).filter((line) => line.startsWith(markerPrefix)); + const terminalLine = output.trimEnd().split(/\r?\n/).at(-1); + if (receiptLines.length !== 1 || terminalLine !== receiptLines[0]) { + return null; + } + const match = receiptLines[0].match(AUTO_PAIR_RECEIPT_LINE_RE); + return (match?.[1] as AutoPairApprovalReceipt | undefined) ?? null; +} + export function readAutoPairApprovalPolicyModule(): string | null { try { return readFileSync(AUTO_PAIR_POLICY_PATH, "utf-8"); @@ -94,16 +120,16 @@ export function readAutoPairApprovalPolicyModule(): string | null { } /** - * Build the in-sandbox sh+python approval-pass script. When `emitSummary` is - * false the output is byte-identical to the historical connect-time script so - * the connect approval-pass tests keep asserting against a stable payload; when - * true it appends a single machine-readable summary marker so the doctor - * recovery path can report how many upgrades it approved. + * Build the in-sandbox sh+python approval-pass script. With no emit option the + * output is byte-identical to the historical connect-time script. `emitSummary` + * adds the doctor's count; `emitReceipt` adds one fixed restored-clone + * classification without forwarding command output or request identifiers. */ export function buildAutoPairApprovalScript( approvalPolicyModuleB64: string, options: { emitSummary?: boolean; + emitReceipt?: boolean; budget?: AutoPairApprovalBudget; localDeviceOnly?: boolean; } = {}, @@ -111,6 +137,27 @@ export function buildAutoPairApprovalScript( const summaryLine = options.emitSummary ? "print(f'__NEMOCLAW_AUTO_PAIR_APPROVED__={approved_count}')\n" : ""; + const receiptPrelude = options.emitReceipt + ? ` +RECEIPT_MARKER = '__NEMOCLAW_AUTO_PAIR_RECEIPT__' + +def exit_with_receipt(receipt): + print(f'{RECEIPT_MARKER}={receipt}') + sys.exit(0) +` + : ""; + const exitWithReceipt = (receipt: AutoPairApprovalReceipt) => + options.emitReceipt ? `exit_with_receipt('${receipt}')` : "sys.exit(0)"; + const receiptSuccessLine = options.emitReceipt ? "exit_with_receipt('approved-one')\n" : ""; + const rejectedRequestAction = options.emitReceipt + ? "exit_with_receipt('request-rejected')" + : "continue"; + const failedApproveBranch = options.emitReceipt + ? " else:\n exit_with_receipt('approve-failed')\n" + : ""; + const failedApproveAction = options.emitReceipt + ? "exit_with_receipt('approve-failed')" + : "continue"; const maxApprovals = options.budget?.maxApprovals ?? AUTO_PAIR_MAX_APPROVALS; const listTimeoutS = options.budget?.listTimeoutS ?? AUTO_PAIR_LIST_TIMEOUT_S; const approveTimeoutS = options.budget?.approveTimeoutS ?? AUTO_PAIR_APPROVE_TIMEOUT_S; @@ -187,24 +234,24 @@ try: with open(os.path.join(state_dir, 'identity', 'device.json'), encoding='utf-8') as handle: local_identity = json.load(handle) except (OSError, ValueError): - sys.exit(0) + ${exitWithReceipt("request-rejected")} if not isinstance(local_identity, dict): - sys.exit(0) + ${exitWithReceipt("request-rejected")} local_device_id = str(local_identity.get('deviceId', '') or '').strip() local_public_key = local_identity_public_key(local_identity) if not local_device_id or not local_public_key: - sys.exit(0) + ${exitWithReceipt("request-rejected")} try: local_public_key_raw = base64.urlsafe_b64decode( local_public_key + '=' * (-len(local_public_key) % 4), ) except (ValueError, binascii.Error): - sys.exit(0) + ${exitWithReceipt("request-rejected")} if ( len(local_public_key_raw) != 32 or hashlib.sha256(local_public_key_raw).hexdigest() != local_device_id ): - sys.exit(0) + ${exitWithReceipt("request-rejected")} def is_local_pairing_transition(device): request_id = device.get('requestId') @@ -237,14 +284,18 @@ related_pending = [ or str(device.get('publicKey', '') or '').strip() == local_public_key ) ] -if len(related_pending) != 1 or not is_local_pairing_transition(related_pending[0]): - sys.exit(0) +if not related_pending: + ${exitWithReceipt("clone-no-match")} +if len(related_pending) > 1: + ${exitWithReceipt("clone-ambiguous")} +if not is_local_pairing_transition(related_pending[0]): + ${exitWithReceipt("request-rejected")} local_request_id = related_pending[0].get('requestId') if sum( 1 for device in pending if isinstance(device, dict) and device.get('requestId') == local_request_id ) != 1: - sys.exit(0) + ${exitWithReceipt("clone-ambiguous")} pending = related_pending ` : ""; @@ -259,7 +310,7 @@ import json import os import subprocess import sys - +${receiptPrelude} try: policy_source = base64.b64decode( os.environ.get('NEMOCLAW_APPROVAL_POLICY_B64', ''), validate=True, @@ -269,7 +320,7 @@ try: approval_request_decision = policy_globals['approval_request_decision'] gateway_approval_env = policy_globals['gateway_approval_env'] except Exception: - sys.exit(0) + ${exitWithReceipt("policy-missing")} OPENCLAW = os.environ.get('OPENCLAW_BIN', 'openclaw') MAX_APPROVALS = ${maxApprovals} @@ -280,18 +331,18 @@ try: capture_output=True, text=True, timeout=${listTimeoutS}, ) except (subprocess.TimeoutExpired, FileNotFoundError, OSError): - sys.exit(0) + ${exitWithReceipt("list-failed")} if proc.returncode != 0 or not proc.stdout.strip(): - sys.exit(0) + ${exitWithReceipt("list-failed")} try: data = json.loads(proc.stdout) except ValueError: - sys.exit(0) + ${exitWithReceipt("list-failed")} if not isinstance(data, dict): - sys.exit(0) + ${exitWithReceipt("list-failed")} pending = data.get('pending') if not isinstance(pending, list): - sys.exit(0)${localDeviceFilter} + ${exitWithReceipt("list-failed")}${localDeviceFilter} approved_count = 0 attempted_count = 0 seen_request_ids = set() @@ -305,7 +356,7 @@ for device in pending: continue decision = approval_request_decision(device) if not decision['allowed']: - continue + ${rejectedRequestAction} seen_request_ids.add(request_id) approve_env = gateway_approval_env(os.environ) attempted_count += 1 @@ -316,9 +367,9 @@ for device in pending: ) if approve_proc.returncode == 0: approved_count += 1 - except (subprocess.TimeoutExpired, FileNotFoundError, OSError): - continue -${summaryLine}PYAPPROVE +${failedApproveBranch} except (subprocess.TimeoutExpired, FileNotFoundError, OSError): + ${failedApproveAction} +${summaryLine}${receiptSuccessLine}PYAPPROVE exit 0 `; } @@ -329,26 +380,34 @@ exit 0 * unreachable, missing policy helper) are swallowed: callers treat this as * best-effort and must never let it throw. * - * When `capture` is true the script emits a summary marker and this function - * parses the approved count so doctor can report a repair outcome; otherwise it - * runs silently like the original connect-time pass. + * `capture` emits the doctor's count. The separate clone-only `receipt` option + * captures and parses one fixed classification; ordinary callers remain + * silent, and no captured command output is returned. */ export function runSandboxAutoPairApprovalPass( sandboxName: string, options: { capture?: boolean; + receipt?: boolean; budget?: AutoPairApprovalBudget; localDeviceOnly?: boolean; } = {}, ): AutoPairApprovalResult { - const capture = options.capture === true; + const emitReceipt = options.receipt === true && options.localDeviceOnly === true; + const capture = options.capture === true || emitReceipt; const approvalPolicyModule = readAutoPairApprovalPolicyModule(); if (!approvalPolicyModule) { - return { attempted: false, reported: false, approved: 0 }; + return { + attempted: false, + reported: false, + approved: 0, + receipt: emitReceipt ? "policy-missing" : null, + }; } const approvalPolicyModuleB64 = Buffer.from(approvalPolicyModule, "utf-8").toString("base64"); const script = buildAutoPairApprovalScript(approvalPolicyModuleB64, { - emitSummary: capture, + emitSummary: options.capture === true, + emitReceipt, budget: options.budget, localDeviceOnly: options.localDeviceOnly, }); @@ -370,16 +429,27 @@ export function runSandboxAutoPairApprovalPass( timeout: outerTimeoutMs, }, ); - if (!capture) { - return { attempted: true, reported: false, approved: 0 }; + const output = String(result.stdout || ""); + const receipt: AutoPairApprovalReceipt | null = !emitReceipt + ? null + : result.error || result.status !== 0 || result.signal + ? "exec-failed" + : (parseAutoPairApprovalReceipt(output) ?? "exec-failed"); + if (!options.capture) { + return { attempted: true, reported: false, approved: 0, receipt }; } - const match = String(result.stdout || "").match(/__NEMOCLAW_AUTO_PAIR_APPROVED__=(\d+)/); + const match = output.match(/__NEMOCLAW_AUTO_PAIR_APPROVED__=(\d+)/); if (!match) { - return { attempted: true, reported: false, approved: 0 }; + return { attempted: true, reported: false, approved: 0, receipt }; } - return { attempted: true, reported: true, approved: Number(match[1]) }; + return { attempted: true, reported: true, approved: Number(match[1]), receipt }; } catch { /* defense-in-depth — never throw from the connect or doctor path */ - return { attempted: true, reported: false, approved: 0 }; + return { + attempted: true, + reported: false, + approved: 0, + receipt: emitReceipt ? "exec-failed" : null, + }; } } diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index abb770e544d..117eacaf95d 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -19,7 +19,10 @@ describe("establishRestoredSandboxGatewayPairing", () => { order.push("restart"); }); const warmupScopeUpgrade = vi.fn(() => order.push("warmup")); - const approveRestoredClonePairing = vi.fn(() => order.push("approve")); + const approveRestoredClonePairing = vi.fn(() => { + order.push("approve"); + return "approved-one" as const; + }); const verifyGatewayPairing = vi.fn(() => { order.push("verify"); return { ok: true as const }; @@ -42,21 +45,41 @@ describe("establishRestoredSandboxGatewayPairing", () => { expect(order).toEqual(["restart", "warmup", "approve", "restart", "verify"]); }); + it("keeps the ordinary verifier as the sole success condition (#7431)", async () => { + const restartRestoredSandboxGateway = vi.fn(); + const warmupScopeUpgrade = vi.fn(); + const approveRestoredClonePairing = vi.fn(() => "approve-failed" as const); + const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); + + await establishRestoredSandboxGatewayPairing("beta", { + restartRestoredSandboxGateway, + warmupScopeUpgrade, + approveRestoredClonePairing, + verifyGatewayPairing, + }); + + expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); + expect(warmupScopeUpgrade).toHaveBeenCalledOnce(); + expect(approveRestoredClonePairing).toHaveBeenCalledOnce(); + expect(verifyGatewayPairing).toHaveBeenCalledOnce(); + }); + it("fails before pairing when the restored gateway cannot restart (#7431)", async () => { const warmupScopeUpgrade = vi.fn(); const approveRestoredClonePairing = vi.fn(); const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); - await expect( - establishRestoredSandboxGatewayPairing("beta", { - restartRestoredSandboxGateway: vi.fn(() => { - throw new Error("gateway did not restart"); - }), - warmupScopeUpgrade, - approveRestoredClonePairing, - verifyGatewayPairing, + const failure = await establishRestoredSandboxGatewayPairing("beta", { + restartRestoredSandboxGateway: vi.fn(() => { + throw new Error("raw gateway output must stay private"); }), - ).rejects.toThrow("gateway did not restart"); + warmupScopeUpgrade, + approveRestoredClonePairing, + verifyGatewayPairing, + }).catch((err: unknown) => err); + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain("unexpected-failure"); + expect((failure as Error).message).not.toContain("raw gateway output"); expect(warmupScopeUpgrade).not.toHaveBeenCalled(); expect(approveRestoredClonePairing).not.toHaveBeenCalled(); expect(verifyGatewayPairing).not.toHaveBeenCalled(); @@ -72,7 +95,10 @@ describe("establishRestoredSandboxGatewayPairing", () => { throw new Error("gateway did not restart after approval"); }); const warmupScopeUpgrade = vi.fn(() => order.push("warmup")); - const approveRestoredClonePairing = vi.fn(() => order.push("approve")); + const approveRestoredClonePairing = vi.fn(() => { + order.push("approve"); + return "approved-one" as const; + }); const verifyGatewayPairing = vi.fn(() => { order.push("verify"); return { ok: true as const }; @@ -85,7 +111,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { approveRestoredClonePairing, verifyGatewayPairing, }), - ).rejects.toThrow("gateway did not restart after approval"); + ).rejects.toThrow("unexpected-failure"); expect(order).toEqual(["restart:initial", "warmup", "approve", "restart:approved"]); expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); expect(verifyGatewayPairing).not.toHaveBeenCalled(); @@ -105,7 +131,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { approveRestoredClonePairing, verifyGatewayPairing, }), - ).rejects.toThrow("gateway not up"); + ).rejects.toThrow("unexpected-failure"); expect(approveRestoredClonePairing).not.toHaveBeenCalled(); expect(verifyGatewayPairing).not.toHaveBeenCalled(); }); @@ -113,7 +139,7 @@ describe("establishRestoredSandboxGatewayPairing", () => { it("fails after one ordinary verifier without retrying the handshake (#7431)", async () => { const restartRestoredSandboxGateway = vi.fn(); const warmupScopeUpgrade = vi.fn(); - const approveRestoredClonePairing = vi.fn(); + const approveRestoredClonePairing = vi.fn(() => "approve-failed" as const); const verifyGatewayPairing = vi.fn(() => ({ ok: false as const, failureLayer: "scope-upgrade-pending" as const, @@ -126,7 +152,9 @@ describe("establishRestoredSandboxGatewayPairing", () => { approveRestoredClonePairing, verifyGatewayPairing, }), - ).rejects.toThrow("authenticated gateway verification run failed (scope-upgrade-pending)"); + ).rejects.toThrow( + "authenticated gateway verification run failed (scope-upgrade-pending; approval=approve-failed)", + ); expect(restartRestoredSandboxGateway).toHaveBeenCalledTimes(2); expect(warmupScopeUpgrade).toHaveBeenCalledOnce(); expect(approveRestoredClonePairing).toHaveBeenCalledOnce(); @@ -148,15 +176,21 @@ describe("restartRestoredSandboxGateway", () => { expect(restartSandboxGateway).toHaveBeenCalledWith("beta", { quiet: true }); }); - it("propagates the classified gateway restart failure (#7431)", () => { - expect(() => + it("propagates only the classified gateway restart failure (#7431)", () => { + let failure: unknown; + try { restartRestoredSandboxGateway("beta", { restartSandboxGateway: () => ({ ok: false, failureLayer: "health timeout", - detail: "gateway process did not become healthy", + detail: "raw gateway output must stay private", }), - }), - ).toThrow("health timeout: gateway process did not become healthy"); + }); + } catch (err) { + failure = err; + } + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toBe("health timeout"); + expect((failure as Error).message).not.toContain("raw gateway output"); }); }); diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.ts b/src/lib/actions/sandbox/restore-gateway-pairing.ts index dbf2c738998..32961f31517 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.ts @@ -5,7 +5,7 @@ import { type RestoreGatewayPairingVerificationResult, verifyRestoredSandboxGatewayPairing, } from "../../adapters/openshell/restore-gateway-pairing"; -import { runSandboxAutoPairApprovalPass } from "./auto-pair-approval"; +import { type AutoPairApprovalReceipt, runSandboxAutoPairApprovalPass } from "./auto-pair-approval"; import { CONNECT_AUTO_PAIR_APPROVE_TIMEOUT_S, CONNECT_AUTO_PAIR_LIST_TIMEOUT_S, @@ -18,7 +18,7 @@ import { WARMUP_SESSION_ID_PREFIX } from "./warmup-session"; export type RestoreGatewayPairingDeps = { restartRestoredSandboxGateway: (sandboxName: string) => void; warmupScopeUpgrade: (sandboxName: string) => void; - approveRestoredClonePairing: (sandboxName: string) => void; + approveRestoredClonePairing: (sandboxName: string) => AutoPairApprovalReceipt | void; verifyGatewayPairing: (sandboxName: string) => RestoreGatewayPairingVerificationResult; }; @@ -29,6 +29,8 @@ const RESTORED_CLONE_PAIRING_BUDGET = { timeoutMs: CONNECT_AUTO_PAIR_TIMEOUT_MS, } as const; +class RestoreGatewayPairingClassifiedError extends Error {} + type RestoredSandboxGatewayRestartDeps = { restartSandboxGateway: ( sandboxName: string, @@ -48,15 +50,17 @@ export function restartRestoredSandboxGateway( ): void { const result = deps.restartSandboxGateway(sandboxName, { quiet: true }); if (!result.ok) { - throw new Error(`${result.failureLayer}: ${result.detail}`); + throw new RestoreGatewayPairingClassifiedError(result.failureLayer); } } -export function approveRestoredClonePairing(sandboxName: string): void { - runSandboxAutoPairApprovalPass(sandboxName, { +export function approveRestoredClonePairing(sandboxName: string): AutoPairApprovalReceipt { + const result = runSandboxAutoPairApprovalPass(sandboxName, { budget: RESTORED_CLONE_PAIRING_BUDGET, localDeviceOnly: true, + receipt: true, }); + return result.receipt ?? "exec-failed"; } function defaultRestoreGatewayPairingDeps(): RestoreGatewayPairingDeps { @@ -77,21 +81,21 @@ export async function establishRestoredSandboxGatewayPairing( try { deps.restartRestoredSandboxGateway(targetSandbox); deps.warmupScopeUpgrade(targetSandbox); - deps.approveRestoredClonePairing(targetSandbox); + const approvalReceipt = deps.approveRestoredClonePairing(targetSandbox) ?? "exec-failed"; // Publish the clone's approved pairing transition before the one ordinary // authenticated verifier. The verifier alone decides success. deps.restartRestoredSandboxGateway(targetSandbox); const verification = deps.verifyGatewayPairing(targetSandbox); if (!verification.ok) { - throw new Error( - `the authenticated gateway verification run failed (${verification.failureLayer})`, + throw new RestoreGatewayPairingClassifiedError( + `the authenticated gateway verification run failed (${verification.failureLayer}; approval=${approvalReceipt})`, ); } } catch (err) { + const classification = + err instanceof RestoreGatewayPairingClassifiedError ? err.message : "unexpected-failure"; throw new Error( - `could not establish gateway pairing for '${targetSandbox}': ${ - err instanceof Error ? err.message : String(err) - }`, + `could not establish gateway pairing for '${targetSandbox}': ${classification}`, ); } } diff --git a/test/helpers/openclaw-real-device-self-approval-proof.ts b/test/helpers/openclaw-real-device-self-approval-proof.ts index c58aac592df..ed874deb97f 100644 --- a/test/helpers/openclaw-real-device-self-approval-proof.ts +++ b/test/helpers/openclaw-real-device-self-approval-proof.ts @@ -1374,6 +1374,36 @@ const identity = (suffix) => ({ clientId: "cli", clientMode: "cli", }); +const coldCloneDevice = { + deviceId: "cold-clone-device", + publicKey: "cold-clone-public-key", + role: "operator", + roles: ["operator"], + clientId: "cli", + clientMode: "cli", + scopes: ["operator.write"], +}; +await pairingRuntime.m(coldCloneDevice, stateDir); +const coldPendingState = JSON.parse( + fs.readFileSync(path.join(stateDir, "devices", "pending.json"), "utf8"), +); +const coldRequests = Object.values(coldPendingState).filter( + (request) => request.deviceId === coldCloneDevice.deviceId, +); +if (coldRequests.length !== 1) throw new Error("cold clone did not create exactly one pending request"); +const coldRequest = coldRequests[0]; +if (coldRequest.isRepair !== false) throw new Error("cold clone request was not pre-convergence"); +const coldPairedState = JSON.parse( + fs.readFileSync(path.join(stateDir, "devices", "paired.json"), "utf8"), +); +if (coldPairedState[coldCloneDevice.deviceId]) throw new Error("cold clone unexpectedly had paired state"); +const coldStoredAuthContext = nemoclawResolveSelfRepairPairingContext( + coldRequest, + coldPairedState[coldCloneDevice.deviceId], +); +if (coldStoredAuthContext?.useStoredDeviceAuth === true) { + throw new Error("cold clone request incorrectly selected stored device auth"); +} const repairRequest = { requestId: "cli-scope-repair", deviceId: "device-1", From 4e0c8c2dba5853f9ea0a496361163b07ea55b0e7 Mon Sep 17 00:00:00 2001 From: Carlos Villela Date: Mon, 27 Jul 2026 09:55:05 -0700 Subject: [PATCH 14/14] test(snapshot): prove fail-once pairing recovery Signed-off-by: Carlos Villela --- .../patch-openclaw-device-self-approval.mts | 3 ++ src/lib/actions/sandbox/auto-pair-approval.ts | 4 +++ .../sandbox/restore-gateway-pairing.test.ts | 35 +++++++++++++++++++ .../sandbox/restore-gateway-pairing.ts | 2 ++ .../openshell/restore-gateway-pairing.ts | 5 +-- 5 files changed, 47 insertions(+), 2 deletions(-) diff --git a/scripts/patch-openclaw-device-self-approval.mts b/scripts/patch-openclaw-device-self-approval.mts index efb059a56ca..13f9f48a352 100644 --- a/scripts/patch-openclaw-device-self-approval.mts +++ b/scripts/patch-openclaw-device-self-approval.mts @@ -23,6 +23,9 @@ * convergence, explicitly use OpenClaw's stored device credential with * operator.pairing. Then let the gateway's canonical approveDevicePairing path * reload, lock, rotate the token, persist, broadcast, and respond. + * The ordinary patch tests and pinned real-dist proof cover this paired + * pre-convergence transition separately from a cold clone, which has no paired + * record and must not select stored device authentication. * * Remove this patch when upstream OpenClaw supports same-device, operator-only * scope approval through the gateway using the already-approved pairing scope diff --git a/src/lib/actions/sandbox/auto-pair-approval.ts b/src/lib/actions/sandbox/auto-pair-approval.ts index ae0c4fae0bf..357b990aaf5 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.ts @@ -97,6 +97,10 @@ export type AutoPairApprovalReceipt = const AUTO_PAIR_RECEIPT_LINE_RE = /^__NEMOCLAW_AUTO_PAIR_RECEIPT__=(policy-missing|exec-failed|list-failed|clone-no-match|clone-ambiguous|request-rejected|approve-failed|approved-one)$/; +/** + * Parse one fixed receipt only when it is the sole receipt and terminal output + * line. Any other shape fails closed without exposing command output. + */ export function parseAutoPairApprovalReceipt(output: string): AutoPairApprovalReceipt | null { const markerPrefix = "__NEMOCLAW_AUTO_PAIR_RECEIPT__="; const receiptLines = output.split(/\r?\n/).filter((line) => line.startsWith(markerPrefix)); diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts index 117eacaf95d..81d499af287 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.test.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.test.ts @@ -85,6 +85,41 @@ describe("establishRestoredSandboxGatewayPairing", () => { expect(verifyGatewayPairing).not.toHaveBeenCalled(); }); + it("classifies a transient-looking restart failure without retrying authorization (#7431)", async () => { + const restartSandboxGateway = vi + .fn() + .mockReturnValueOnce({ + ok: false as const, + failureLayer: "health timeout", + detail: "raw transient output must stay private", + }) + .mockReturnValueOnce({ + ok: true as const, + restarted: true as const, + healthPassed: true as const, + forwardRecovered: true, + }); + const warmupScopeUpgrade = vi.fn(); + const approveRestoredClonePairing = vi.fn(); + const verifyGatewayPairing = vi.fn(() => ({ ok: true as const })); + + const failure = await establishRestoredSandboxGatewayPairing("beta", { + restartRestoredSandboxGateway: (sandboxName) => + restartRestoredSandboxGateway(sandboxName, { restartSandboxGateway }), + warmupScopeUpgrade, + approveRestoredClonePairing, + verifyGatewayPairing, + }).catch((err: unknown) => err); + + expect(failure).toBeInstanceOf(Error); + expect((failure as Error).message).toContain("health timeout"); + expect((failure as Error).message).not.toContain("raw transient output"); + expect(restartSandboxGateway).toHaveBeenCalledOnce(); + expect(warmupScopeUpgrade).not.toHaveBeenCalled(); + expect(approveRestoredClonePairing).not.toHaveBeenCalled(); + expect(verifyGatewayPairing).not.toHaveBeenCalled(); + }); + it("fails without verification when the post-approval gateway restart fails (#7431)", async () => { const order: string[] = []; const restartRestoredSandboxGateway = vi diff --git a/src/lib/actions/sandbox/restore-gateway-pairing.ts b/src/lib/actions/sandbox/restore-gateway-pairing.ts index 32961f31517..50cff79caff 100644 --- a/src/lib/actions/sandbox/restore-gateway-pairing.ts +++ b/src/lib/actions/sandbox/restore-gateway-pairing.ts @@ -78,6 +78,8 @@ export async function establishRestoredSandboxGatewayPairing( targetSandbox: string, deps: RestoreGatewayPairingDeps = defaultRestoreGatewayPairingDeps(), ): Promise { + // Deliberately do not retry this authorization sequence internally. A fixed + // failure lets the caller retry the restore command as a new bounded attempt. try { deps.restartRestoredSandboxGateway(targetSandbox); deps.warmupScopeUpgrade(targetSandbox); diff --git a/src/lib/adapters/openshell/restore-gateway-pairing.ts b/src/lib/adapters/openshell/restore-gateway-pairing.ts index 291bd32a741..9a812186def 100644 --- a/src/lib/adapters/openshell/restore-gateway-pairing.ts +++ b/src/lib/adapters/openshell/restore-gateway-pairing.ts @@ -35,8 +35,9 @@ export type RestoreGatewayPairingVerificationResult = // JSON output does not expose a supported, stable transport discriminator. // These compatibility signals match the gateway-auth live tests. Keep the // returned classification fixed and output-free so restore diagnostics never -// expose agent output or credentials. Remove this classifier once OpenClaw -// provides a machine-readable gateway-only result. +// expose agent output or credentials. The pinned OpenClaw dependency-review +// gate is the removal checkpoint: reevaluate and remove this classifier when +// OpenClaw provides a supported machine-readable gateway-only result. const RESTORE_GATEWAY_PAIRING_REJECTIONS: ReadonlyArray<{ pattern: RegExp; failureLayer: RestoreGatewayPairingFailureLayer;