From 8b9c2282a9a07f7fbe9ededca142bf947094855f Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Mon, 6 Jul 2026 22:09:18 +0800 Subject: [PATCH 01/16] fix: bootstrap cli pairing when device list is gated --- ci/test-file-size-budget.json | 2 +- scripts/nemoclaw-start.sh | 178 ++++++++++++++++++ .../sandbox/auto-pair-approval.test.ts | 12 +- ...nemoclaw-start-auto-pair-bootstrap.test.ts | 146 ++++++++++++++ test/nemoclaw-start.test.ts | 23 ++- 5 files changed, 345 insertions(+), 16 deletions(-) create mode 100644 test/nemoclaw-start-auto-pair-bootstrap.test.ts diff --git a/ci/test-file-size-budget.json b/ci/test-file-size-budget.json index efa6090688e..ddfeda5bfd7 100644 --- a/ci/test-file-size-budget.json +++ b/ci/test-file-size-budget.json @@ -8,7 +8,7 @@ "test/channels-add-preset.test.ts": 1871, "test/generate-openclaw-config.test.ts": 1945, "test/install-preflight.test.ts": 3934, - "test/nemoclaw-start.test.ts": 4827, + "test/nemoclaw-start.test.ts": 4826, "test/onboard-messaging.test.ts": 2062, "test/onboard-selection.test.ts": 6146, "test/onboard.test.ts": 4057, diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index e246fc56c4e..53f77d4a8e7 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2377,9 +2377,13 @@ start_auto_pair() { OPENCLAW_BIN="$OPENCLAW" nohup "${run_prefix[@]}" python3 -u - <<'PYAUTOPAIR' >>/tmp/auto-pair.log 2>&1 & import json import importlib.util +import base64 +import hashlib import os +import secrets import stat import subprocess +import tempfile import time print('[auto-pair] watcher started', flush=True) @@ -2490,6 +2494,173 @@ HANDLED = set() # Track rejected/approved requestIds to avoid reprocessing # The approval_request_decision helper is shared with connect-time approvals. RUN_TIMEOUT_SECS = _env_seconds('NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS', 10) +INITIAL_PAIRING_SCOPES = ['operator.pairing'] +INITIAL_PAIRING_ALLOWED_SCOPES = {'operator.pairing', 'operator.read', 'operator.write'} + + +def _read_json(path, default): + try: + with open(path, 'r', encoding='utf-8') as handle: + data = json.load(handle) + return data if isinstance(data, dict) else default + except FileNotFoundError: + return default + except Exception: + raise + + +def _write_json_atomic(path, payload, mode=0o600): + os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) + fd, tmp = tempfile.mkstemp(prefix='.nemoclaw.', dir=os.path.dirname(path)) + try: + with os.fdopen(fd, 'w', encoding='utf-8') as handle: + json.dump(payload, handle, indent=2, sort_keys=True) + handle.write('\n') + handle.flush() + os.fsync(handle.fileno()) + os.fchmod(handle.fileno(), mode) + os.replace(tmp, path) + finally: + try: + os.unlink(tmp) + except FileNotFoundError: + pass + + +def _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 '' + der = base64.b64decode(body) + if len(der) < 32: + return '' + return base64.urlsafe_b64encode(der[-32:]).decode('ascii').rstrip('=') + + +def _same_initial_cli_requests(pending, device_id, public_key): + requests = [] + for key, value in pending.items(): + if not isinstance(value, dict): + continue + if str(value.get('deviceId', '')).strip() != device_id: + continue + if str(value.get('publicKey', '')).strip() != public_key: + raise RuntimeError('pending CLI pairing public key does not match persisted identity') + if str(value.get('clientId', '')).strip() != 'cli': + raise RuntimeError('pending CLI pairing clientId is not allowlisted') + if str(value.get('clientMode', '')).strip() != 'cli': + raise RuntimeError('pending CLI pairing clientMode is not allowlisted') + roles = set() + role = value.get('role') + if role is not None: + if not isinstance(role, str) or not role.strip(): + raise RuntimeError('pending CLI pairing role is malformed') + roles.add(role.strip()) + raw_roles = value.get('roles') + if raw_roles is not None: + if not isinstance(raw_roles, list): + raise RuntimeError('pending CLI pairing roles are malformed') + for item in raw_roles: + if not isinstance(item, str) or not item.strip(): + raise RuntimeError('pending CLI pairing roles are malformed') + roles.add(item.strip()) + if roles != {'operator'}: + raise RuntimeError('pending CLI pairing role is not operator-only') + raw_scopes = value.get('scopes') + if not isinstance(raw_scopes, list) or not raw_scopes: + raise RuntimeError('pending CLI pairing scopes are malformed') + scopes = set() + for item in raw_scopes: + if not isinstance(item, str) or not item.strip(): + raise RuntimeError('pending CLI pairing scopes are malformed') + scope = item.strip() + if scope not in INITIAL_PAIRING_ALLOWED_SCOPES or scope in scopes: + raise RuntimeError('pending CLI pairing scopes are not bounded') + scopes.add(scope) + if 'operator.pairing' not in scopes: + raise RuntimeError('pending CLI pairing does not request operator.pairing') + requests.append((key, value)) + return requests + + +def seed_initial_cli_pairing_from_state(): + state_dir = os.environ.get('OPENCLAW_STATE_DIR') or '/sandbox/.openclaw' + pending_path = os.path.join(state_dir, 'devices', 'pending.json') + paired_path = os.path.join(state_dir, 'devices', 'paired.json') + identity_path = os.path.join(state_dir, 'identity', 'device.json') + auth_path = os.path.join(state_dir, 'identity', 'device-auth.json') + try: + pending = _read_json(pending_path, {}) + if not pending: + return None + paired = _read_json(paired_path, {}) + identity = _read_json(identity_path, {}) + device_id = str(identity.get('deviceId', '') or '').strip() + public_key = _identity_public_key(identity) + if not device_id or not public_key: + return None + public_key_raw = base64.urlsafe_b64decode(public_key + '=' * (-len(public_key) % 4)) + if len(public_key_raw) != 32 or hashlib.sha256(public_key_raw).hexdigest() != device_id: + raise RuntimeError('persisted CLI identity does not match its device id') + if device_id in paired or any( + isinstance(item, dict) and str(item.get('deviceId', '')).strip() == device_id + for item in paired.values() + ): + return None + same_device = _same_initial_cli_requests(pending, device_id, public_key) + if not same_device: + return None + _, request = max(same_device, key=lambda pair: pair[1].get('ts') or 0) + request_id = str(request.get('requestId', '') or '').strip() + if not request_id: + return None + token = secrets.token_urlsafe(32) + if token == os.environ.get('OPENCLAW_GATEWAY_TOKEN'): + raise RuntimeError('temporary device token generation collided with gateway token') + now = int(time.time() * 1000) + operator_token = { + 'token': token, + 'role': 'operator', + 'scopes': INITIAL_PAIRING_SCOPES, + 'createdAtMs': now, + } + device = { + 'deviceId': device_id, + 'publicKey': public_key, + 'displayName': request.get('displayName'), + 'platform': request.get('platform'), + 'deviceFamily': request.get('deviceFamily'), + 'clientId': 'cli', + 'clientMode': 'cli', + 'role': 'operator', + 'roles': ['operator'], + 'scopes': INITIAL_PAIRING_SCOPES, + 'approvedScopes': INITIAL_PAIRING_SCOPES, + 'remoteIp': request.get('remoteIp'), + 'tokens': {'operator': operator_token}, + 'createdAtMs': now, + 'approvedAtMs': now, + } + device = {key: value for key, value in device.items() if value is not None} + for key, _ in same_device: + pending.pop(key, None) + paired[device_id] = device + auth = { + 'version': 1, + 'deviceId': device_id, + 'tokens': {'operator': operator_token}, + } + _write_json_atomic(pending_path, pending) + _write_json_atomic(paired_path, paired) + _write_json_atomic(auth_path, auth) + return request_id + except Exception as err: + print(f'[auto-pair] initial CLI pairing seed skipped: {str(err)[:240]}') + return None # Workaround boundary (NemoClaw#4462): list calls stay gateway-pinned so the # watcher inspects live state. Approval calls drop the gateway env triplet so @@ -2546,6 +2717,13 @@ def sleep_for_next_poll(default_seconds, productive=True): while time.time() < DEADLINE: rc, out, err = run(OPENCLAW, 'devices', 'list', '--json') if rc != 0 or not out: + seeded_request = seed_initial_cli_pairing_from_state() + if seeded_request: + APPROVED += 1 + print(f'[auto-pair] seeded initial CLI pairing request={seeded_request}') + FAST_REENTRY_REMAINING = max(FAST_REENTRY_REMAINING, FAST_REENTRY_POLLS) + sleep_for_next_poll(FAST_REENTRY_INTERVAL) + continue sleep_for_next_poll(SLOW_INTERVAL if SLOW_MODE else 1, productive=False) continue try: diff --git a/src/lib/actions/sandbox/auto-pair-approval.test.ts b/src/lib/actions/sandbox/auto-pair-approval.test.ts index ee3f8790322..a918ae3b590 100644 --- a/src/lib/actions/sandbox/auto-pair-approval.test.ts +++ b/src/lib/actions/sandbox/auto-pair-approval.test.ts @@ -97,6 +97,12 @@ describe("auto-pair approval pass behaviour (#4616)", () => { clientMode: "cli", requestedScopes: ["operator.pairing"], }, + { + requestId: "ok-agent-cli", + clientId: "cli", + clientMode: "cli", + requestedScopes: ["operator.pairing"], + }, { requestId: "deny-unknown", clientId: "evil", @@ -169,10 +175,10 @@ process.exit(2); ? fs.readFileSync(approveEnvFile, "utf-8").trim().split("\n").filter(Boolean) : []; - expect(approvals).toEqual(["ok-webchat", "ok-cli"]); + expect(approvals).toEqual(["ok-webchat", "ok-cli", "ok-agent-cli"]); // Gateway env stripped on the approve subprocess (#4462 workaround). - expect(approveEnv).toEqual(["unset:unset:unset", "unset:unset:unset"]); - expect(result.stdout).toContain(`${SUMMARY_MARKER}=2`); + expect(approveEnv).toEqual(["unset:unset:unset", "unset:unset:unset", "unset:unset:unset"]); + expect(result.stdout).toContain(`${SUMMARY_MARKER}=3`); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts new file mode 100644 index 00000000000..e44cbd48436 --- /dev/null +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -0,0 +1,146 @@ +// @ts-nocheck +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. +// SPDX-License-Identifier: Apache-2.0 + +import { spawnSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { describe, expect, it } from "vitest"; + +const START_SCRIPT = path.join(import.meta.dirname, "..", "scripts", "nemoclaw-start.sh"); +const APPROVAL_POLICY_DIR = path.join(import.meta.dirname, "..", "scripts", "lib"); + +function startScriptHeredoc(src: string, marker: string): string { + const match = src.match(new RegExp(`<<'${marker}'[^\\n]*\\n([\\s\\S]*?)\\n${marker}`)); + if (match) return match[1]; + throw new Error(`Expected heredoc marker ${marker} in scripts/nemoclaw-start.sh`); +} + +function trustedApprovalPolicyFile(tmpDir: string): string { + const helperPath = path.join(tmpDir, "openclaw_device_approval_policy.py"); + fs.copyFileSync(path.join(APPROVAL_POLICY_DIR, "openclaw_device_approval_policy.py"), helperPath); + fs.chmodSync(helperPath, 0o444); + return helperPath; +} + +function autoPairPythonScript(src: string, tmpDir: string): string { + return startScriptHeredoc(src, "PYAUTOPAIR") + .replace( + "APPROVAL_POLICY_FILE = '/usr/local/lib/nemoclaw/openclaw_device_approval_policy.py'", + `APPROVAL_POLICY_FILE = ${JSON.stringify(trustedApprovalPolicyFile(tmpDir))}`, + ) + .replaceAll("time.time()", "_nemoclaw_test_time()") + .replaceAll("time.sleep(", "_nemoclaw_test_sleep(") + .replace( + "import time", + `import time +_nemoclaw_test_clock = [time.time()] +_nemoclaw_test_time = lambda: _nemoclaw_test_clock[0] +def _nemoclaw_test_sleep(seconds): _nemoclaw_test_clock.__setitem__(0, _nemoclaw_test_clock[0] + min(max(float(seconds), 0), 0.25)) +`, + ); +} + +describe("nemoclaw-start initial CLI auto-pair bootstrap (#6113)", () => { + const src = fs.readFileSync(START_SCRIPT, "utf-8"); + + it("seeds an initial CLI pairing request when device list is itself gated", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-bootstrap-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const pendingFile = path.join(devicesDir, "pending.json"); + const pairedFile = path.join(devicesDir, "paired.json"); + const authFile = path.join(identityDir, "device-auth.json"); + fs.mkdirSync(devicesDir, { recursive: true }); + fs.mkdirSync(identityDir, { recursive: true }); + const publicKey = "y3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8"; + const deviceId = "04a4c561c730435e9f6a2e38d2e7b929bcbec2ea1c37d3dd053f3341ecce4e47"; + fs.writeFileSync( + path.join(identityDir, "device.json"), + JSON.stringify({ + version: 1, + deviceId, + publicKeyPem: + "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAy3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8=\n-----END PUBLIC KEY-----\n", + }), + ); + fs.writeFileSync( + pendingFile, + JSON.stringify({ + "request-1": { + requestId: "request-1", + deviceId, + publicKey, + platform: "linux", + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing", "operator.write"], + remoteIp: "10.200.0.2", + ts: 100, + }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then + if [ -s ${JSON.stringify(pairedFile)} ]; then + node -e 'const fs=require("fs"); const paired=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); process.stdout.write(JSON.stringify({pending:[], paired:Object.values(paired)})+"\\n")' ${JSON.stringify(pairedFile)} + exit 0 + fi + printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' + exit 1 +fi +echo "unexpected: $*" >&2 +exit 2 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + OPENCLAW_GATEWAY_TOKEN: "gateway-token", + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "3", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + expect(run.stdout).toContain("[auto-pair] seeded initial CLI pairing request=request-1"); + const paired = JSON.parse(fs.readFileSync(pairedFile, "utf-8")); + const auth = JSON.parse(fs.readFileSync(authFile, "utf-8")); + expect(Object.keys(paired)).toEqual([deviceId]); + expect(paired[deviceId]).toMatchObject({ + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + scopes: ["operator.pairing"], + approvedScopes: ["operator.pairing"], + }); + expect(paired[deviceId].tokens.operator.token).toBeTruthy(); + expect(paired[deviceId].tokens.operator.token).not.toBe("gateway-token"); + expect(auth).toMatchObject({ + version: 1, + deviceId, + tokens: { operator: { role: "operator", scopes: ["operator.pairing"] } }, + }); + expect(auth.tokens.operator.token).toBe(paired[deviceId].tokens.operator.token); + expect(JSON.parse(fs.readFileSync(pendingFile, "utf-8"))).toEqual({}); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 40_000); +}); diff --git a/test/nemoclaw-start.test.ts b/test/nemoclaw-start.test.ts index c95abc652e5..88784e4abc2 100644 --- a/test/nemoclaw-start.test.ts +++ b/test/nemoclaw-start.test.ts @@ -548,7 +548,6 @@ describe("nemoclaw-start non-root fallback", () => { ["#!/usr/bin/env bash", "set -euo pipefail", fn, "fix_openclaw_ownership"].join("\n"), { mode: 0o700 }, ); - try { const result = spawnSync("bash", [scriptPath], { encoding: "utf-8", @@ -1554,6 +1553,7 @@ describe("nemoclaw-start auto-pair client whitelisting (#117)", () => { "not-a-device", { requestId: "ok-browser", clientId: "openclaw-control-ui", clientMode: "unknown" }, { requestId: "ok-browser", clientId: "openclaw-control-ui", clientMode: "unknown" }, + { requestId: "ok-agent-cli", clientId: "cli", clientMode: "cli" }, { requestId: "ok-webchat", clientId: "other-client", clientMode: "webchat" }, { requestId: "reject-me", clientId: "evil-client", clientMode: "unknown" }, ], @@ -1592,7 +1592,6 @@ exit 2 ); const autoPairScript = autoPairPythonScript(src); - try { const run = spawnSync("python3", ["-c", autoPairScript], { encoding: "utf-8", @@ -1613,22 +1612,26 @@ exit 2 expect(run.stdout).toContain( "[auto-pair] approved request=ok-browser client=openclaw-control-ui", ); + expect(run.stdout).toContain("[auto-pair] approved request=ok-agent-cli client=cli mode=cli"); expect(run.stdout).toContain("[auto-pair] rejected unknown client=other-client mode=webchat"); expect(run.stdout).toContain("[auto-pair] rejected unknown client=evil-client mode=unknown"); expect(run.stdout).toContain( - "[auto-pair] browser pairing converged; entering slow-mode approvals=1", + "[auto-pair] browser pairing converged; entering slow-mode approvals=2", ); - expect(fs.readFileSync(approveLog, "utf-8").trim().split("\n")).toEqual(["ok-browser"]); + expect(fs.readFileSync(approveLog, "utf-8").trim().split("\n")).toEqual([ + "ok-browser", + "ok-agent-cli", + ]); const envLogLines = fs.readFileSync(envLog, "utf-8").trim().split("\n"); expect(envLogLines).toContain("list:ws://127.0.0.1:18789:18789:test-gateway-token"); expect(envLogLines).toContain("approve:ok-browser:unset:unset:unset"); + expect(envLogLines).toContain("approve:ok-agent-cli:unset:unset:unset"); expect(envLogLines).not.toContain("approve:ok-webchat:unset:unset:unset"); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } }, 40_000); }); - describe("nemoclaw-start auto-pair slow-mode keepalive (#4263)", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); @@ -1651,7 +1654,7 @@ describe("nemoclaw-start auto-pair slow-mode keepalive (#4263)", () => { const stateFile = path.join(tmpDir, "list-count"); const approveLog = path.join(tmpDir, "approvals.log"); const browserClient = { clientId: "openclaw-control-ui", clientMode: "webchat" }; - const cliClient = { clientId: "openclaw-cli", clientMode: "cli" }; + const cliClient = { clientId: "cli", clientMode: "cli" }; const initialPending = JSON.stringify({ pending: [{ requestId: "browser-pair", ...browserClient }], paired: [], @@ -1717,12 +1720,8 @@ exit 2 "[auto-pair] browser pairing converged; entering slow-mode approvals=1", ); // Concurrent late wave — proxy for two sibling sandboxes' upgrades. - expect(run.stdout).toContain( - "[auto-pair] approved request=late-cli client=openclaw-cli mode=cli", - ); - expect(run.stdout).toContain( - "[auto-pair] approved request=late-cli-b client=openclaw-cli mode=cli", - ); + expect(run.stdout).toContain("[auto-pair] approved request=late-cli client=cli mode=cli"); + expect(run.stdout).toContain("[auto-pair] approved request=late-cli-b client=cli mode=cli"); expect(run.stdout).toContain("watcher deadline reached approvals=3"); // Single marker per poll wave, transition after convergence. expect(run.stdout).toContain("[auto-pair] fast-reentry bumped polls=3 approved=3 mode=slow"); From 2c164d077b2f3746dadf28bf2a8f5228da5b5651 Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Mon, 6 Jul 2026 22:31:34 +0800 Subject: [PATCH 02/16] fix: tighten cli pairing bootstrap fallback Signed-off-by: Chengjie Wang --- scripts/nemoclaw-start.sh | 48 ++++++++---- ...nemoclaw-start-auto-pair-bootstrap.test.ts | 74 ++++++++++++++++++- 2 files changed, 106 insertions(+), 16 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 53f77d4a8e7..2e9fc99e3c4 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2538,6 +2538,8 @@ def _identity_public_key(identity): der = base64.b64decode(body) if len(der) < 32: return '' + # OpenClaw device identities currently use Ed25519 SubjectPublicKeyInfo; + # the raw 32-byte public key is the BIT STRING payload at the end. return base64.urlsafe_b64encode(der[-32:]).decode('ascii').rstrip('=') @@ -2588,6 +2590,25 @@ def _same_initial_cli_requests(pending, device_id, public_key): def seed_initial_cli_pairing_from_state(): + # SOURCE_OF_TRUTH_REVIEW (NemoClaw#6113 initial CLI bootstrap): + # Invalid state handled: the gateway records a local first-run `cli` + # pending request, then rejects `openclaw devices list --json` with + # "pairing required", so the watcher cannot observe the request through + # OpenClaw's normal approval API. + # + # Source boundary: this function only reads/writes the local OpenClaw + # state directory for the same persisted device identity. It refuses + # mismatched keys, non-cli clients, non-operator roles, duplicate or + # non-bounded scopes, and any existing paired record for that device. + # + # Source-fix constraint: the gateway/list API should eventually expose a + # bounded way for the local bootstrapper to see and approve first-run + # requests without already being paired. That change is upstream of this + # startup script and would not help already-packaged NemoClaw sandboxes. + # + # Removal condition: delete this fallback once OpenClaw exposes a + # non-paired local bootstrap path for initial CLI pairing and NemoClaw no + # longer needs to support gateway builds that gate `devices list`. state_dir = os.environ.get('OPENCLAW_STATE_DIR') or '/sandbox/.openclaw' pending_path = os.path.join(state_dir, 'devices', 'pending.json') paired_path = os.path.join(state_dir, 'devices', 'paired.json') @@ -2631,21 +2652,16 @@ def seed_initial_cli_pairing_from_state(): device = { 'deviceId': device_id, 'publicKey': public_key, - 'displayName': request.get('displayName'), - 'platform': request.get('platform'), - 'deviceFamily': request.get('deviceFamily'), 'clientId': 'cli', 'clientMode': 'cli', 'role': 'operator', 'roles': ['operator'], 'scopes': INITIAL_PAIRING_SCOPES, 'approvedScopes': INITIAL_PAIRING_SCOPES, - 'remoteIp': request.get('remoteIp'), 'tokens': {'operator': operator_token}, 'createdAtMs': now, 'approvedAtMs': now, } - device = {key: value for key, value in device.items() if value is not None} for key, _ in same_device: pending.pop(key, None) paired[device_id] = device @@ -2659,9 +2675,14 @@ def seed_initial_cli_pairing_from_state(): _write_json_atomic(auth_path, auth) return request_id except Exception as err: - print(f'[auto-pair] initial CLI pairing seed skipped: {str(err)[:240]}') + print(f'[auto-pair] initial CLI pairing seed skipped: {type(err).__name__}: {str(err)[:220]}') return None + +def is_pairing_required_list_failure(out, err): + message = f'{out}\n{err}'.lower() + return 'pairing required' in message and 'device is not approved yet' in message + # Workaround boundary (NemoClaw#4462): list calls stay gateway-pinned so the # watcher inspects live state. Approval calls drop the gateway env triplet so # OpenClaw resolves its local loopback gateway and device token. The reviewed @@ -2717,13 +2738,14 @@ def sleep_for_next_poll(default_seconds, productive=True): while time.time() < DEADLINE: rc, out, err = run(OPENCLAW, 'devices', 'list', '--json') if rc != 0 or not out: - seeded_request = seed_initial_cli_pairing_from_state() - if seeded_request: - APPROVED += 1 - print(f'[auto-pair] seeded initial CLI pairing request={seeded_request}') - FAST_REENTRY_REMAINING = max(FAST_REENTRY_REMAINING, FAST_REENTRY_POLLS) - sleep_for_next_poll(FAST_REENTRY_INTERVAL) - continue + if is_pairing_required_list_failure(out, err): + seeded_request = seed_initial_cli_pairing_from_state() + if seeded_request: + APPROVED += 1 + print(f'[auto-pair] seeded initial CLI pairing request={seeded_request}') + FAST_REENTRY_REMAINING = max(FAST_REENTRY_REMAINING, FAST_REENTRY_POLLS) + sleep_for_next_poll(FAST_REENTRY_INTERVAL) + continue sleep_for_next_poll(SLOW_INTERVAL if SLOW_MODE else 1, productive=False) continue try: diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index e44cbd48436..71bb6ce69c2 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -1,4 +1,3 @@ -// @ts-nocheck // SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. // SPDX-License-Identifier: Apache-2.0 @@ -13,8 +12,8 @@ const APPROVAL_POLICY_DIR = path.join(import.meta.dirname, "..", "scripts", "lib function startScriptHeredoc(src: string, marker: string): string { const match = src.match(new RegExp(`<<'${marker}'[^\\n]*\\n([\\s\\S]*?)\\n${marker}`)); - if (match) return match[1]; - throw new Error(`Expected heredoc marker ${marker} in scripts/nemoclaw-start.sh`); + expect(match).not.toBeNull(); + return match![1]; } function trustedApprovalPolicyFile(tmpDir: string): string { @@ -143,4 +142,73 @@ exit 2 fs.rmSync(tmpDir, { recursive: true, force: true }); } }, 40_000); + + it("does not seed when device list fails for a non-pairing error", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-nonpairing-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const pairedFile = path.join(devicesDir, "paired.json"); + const authFile = path.join(identityDir, "device-auth.json"); + fs.mkdirSync(devicesDir, { recursive: true }); + fs.mkdirSync(identityDir, { recursive: true }); + const publicKey = "y3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8"; + const deviceId = "04a4c561c730435e9f6a2e38d2e7b929bcbec2ea1c37d3dd053f3341ecce4e47"; + fs.writeFileSync( + path.join(identityDir, "device.json"), + JSON.stringify({ + version: 1, + deviceId, + publicKeyPem: + "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAy3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8=\n-----END PUBLIC KEY-----\n", + }), + ); + fs.writeFileSync( + path.join(devicesDir, "pending.json"), + JSON.stringify({ + "request-1": { + requestId: "request-1", + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + ts: 100, + }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +printf '%s\\n' '{"ok":false,"error":{"reason":"gateway unavailable"}}' +exit 1 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "2", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + expect(run.stdout).not.toContain("seeded initial CLI pairing"); + expect(fs.existsSync(pairedFile)).toBe(false); + expect(fs.existsSync(authFile)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 40_000); }); From b48adb292255d4308c0ddde6f1c4dc398af12056 Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 00:49:10 +0800 Subject: [PATCH 03/16] fix: delegate gated cli pairing approval Signed-off-by: Chengjie Wang --- scripts/nemoclaw-start.sh | 221 +++--------------- ...nemoclaw-start-auto-pair-bootstrap.test.ts | 29 +-- 2 files changed, 46 insertions(+), 204 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 2e9fc99e3c4..3986fe8e847 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2377,13 +2377,10 @@ start_auto_pair() { OPENCLAW_BIN="$OPENCLAW" nohup "${run_prefix[@]}" python3 -u - <<'PYAUTOPAIR' >>/tmp/auto-pair.log 2>&1 & import json import importlib.util -import base64 -import hashlib import os -import secrets +import re import stat import subprocess -import tempfile import time print('[auto-pair] watcher started', flush=True) @@ -2494,194 +2491,27 @@ HANDLED = set() # Track rejected/approved requestIds to avoid reprocessing # The approval_request_decision helper is shared with connect-time approvals. RUN_TIMEOUT_SECS = _env_seconds('NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS', 10) -INITIAL_PAIRING_SCOPES = ['operator.pairing'] -INITIAL_PAIRING_ALLOWED_SCOPES = {'operator.pairing', 'operator.read', 'operator.write'} -def _read_json(path, default): - try: - with open(path, 'r', encoding='utf-8') as handle: - data = json.load(handle) - return data if isinstance(data, dict) else default - except FileNotFoundError: - return default - except Exception: - raise +def is_pairing_required_list_failure(out, err): + message = f'{out}\n{err}'.lower() + return 'pairing required' in message and 'device is not approved yet' in message -def _write_json_atomic(path, payload, mode=0o600): - os.makedirs(os.path.dirname(path), mode=0o700, exist_ok=True) - fd, tmp = tempfile.mkstemp(prefix='.nemoclaw.', dir=os.path.dirname(path)) - try: - with os.fdopen(fd, 'w', encoding='utf-8') as handle: - json.dump(payload, handle, indent=2, sort_keys=True) - handle.write('\n') - handle.flush() - os.fsync(handle.fileno()) - os.fchmod(handle.fileno(), mode) - os.replace(tmp, path) - finally: - try: - os.unlink(tmp) - except FileNotFoundError: - pass - - -def _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 '' - der = base64.b64decode(body) - if len(der) < 32: - return '' - # OpenClaw device identities currently use Ed25519 SubjectPublicKeyInfo; - # the raw 32-byte public key is the BIT STRING payload at the end. - return base64.urlsafe_b64encode(der[-32:]).decode('ascii').rstrip('=') - - -def _same_initial_cli_requests(pending, device_id, public_key): - requests = [] - for key, value in pending.items(): - if not isinstance(value, dict): - continue - if str(value.get('deviceId', '')).strip() != device_id: - continue - if str(value.get('publicKey', '')).strip() != public_key: - raise RuntimeError('pending CLI pairing public key does not match persisted identity') - if str(value.get('clientId', '')).strip() != 'cli': - raise RuntimeError('pending CLI pairing clientId is not allowlisted') - if str(value.get('clientMode', '')).strip() != 'cli': - raise RuntimeError('pending CLI pairing clientMode is not allowlisted') - roles = set() - role = value.get('role') - if role is not None: - if not isinstance(role, str) or not role.strip(): - raise RuntimeError('pending CLI pairing role is malformed') - roles.add(role.strip()) - raw_roles = value.get('roles') - if raw_roles is not None: - if not isinstance(raw_roles, list): - raise RuntimeError('pending CLI pairing roles are malformed') - for item in raw_roles: - if not isinstance(item, str) or not item.strip(): - raise RuntimeError('pending CLI pairing roles are malformed') - roles.add(item.strip()) - if roles != {'operator'}: - raise RuntimeError('pending CLI pairing role is not operator-only') - raw_scopes = value.get('scopes') - if not isinstance(raw_scopes, list) or not raw_scopes: - raise RuntimeError('pending CLI pairing scopes are malformed') - scopes = set() - for item in raw_scopes: - if not isinstance(item, str) or not item.strip(): - raise RuntimeError('pending CLI pairing scopes are malformed') - scope = item.strip() - if scope not in INITIAL_PAIRING_ALLOWED_SCOPES or scope in scopes: - raise RuntimeError('pending CLI pairing scopes are not bounded') - scopes.add(scope) - if 'operator.pairing' not in scopes: - raise RuntimeError('pending CLI pairing does not request operator.pairing') - requests.append((key, value)) - return requests - - -def seed_initial_cli_pairing_from_state(): - # SOURCE_OF_TRUTH_REVIEW (NemoClaw#6113 initial CLI bootstrap): - # Invalid state handled: the gateway records a local first-run `cli` - # pending request, then rejects `openclaw devices list --json` with - # "pairing required", so the watcher cannot observe the request through - # OpenClaw's normal approval API. - # - # Source boundary: this function only reads/writes the local OpenClaw - # state directory for the same persisted device identity. It refuses - # mismatched keys, non-cli clients, non-operator roles, duplicate or - # non-bounded scopes, and any existing paired record for that device. - # - # Source-fix constraint: the gateway/list API should eventually expose a - # bounded way for the local bootstrapper to see and approve first-run - # requests without already being paired. That change is upstream of this - # startup script and would not help already-packaged NemoClaw sandboxes. - # - # Removal condition: delete this fallback once OpenClaw exposes a - # non-paired local bootstrap path for initial CLI pairing and NemoClaw no - # longer needs to support gateway builds that gate `devices list`. - state_dir = os.environ.get('OPENCLAW_STATE_DIR') or '/sandbox/.openclaw' - pending_path = os.path.join(state_dir, 'devices', 'pending.json') - paired_path = os.path.join(state_dir, 'devices', 'paired.json') - identity_path = os.path.join(state_dir, 'identity', 'device.json') - auth_path = os.path.join(state_dir, 'identity', 'device-auth.json') - try: - pending = _read_json(pending_path, {}) - if not pending: - return None - paired = _read_json(paired_path, {}) - identity = _read_json(identity_path, {}) - device_id = str(identity.get('deviceId', '') or '').strip() - public_key = _identity_public_key(identity) - if not device_id or not public_key: - return None - public_key_raw = base64.urlsafe_b64decode(public_key + '=' * (-len(public_key) % 4)) - if len(public_key_raw) != 32 or hashlib.sha256(public_key_raw).hexdigest() != device_id: - raise RuntimeError('persisted CLI identity does not match its device id') - if device_id in paired or any( - isinstance(item, dict) and str(item.get('deviceId', '')).strip() == device_id - for item in paired.values() - ): - return None - same_device = _same_initial_cli_requests(pending, device_id, public_key) - if not same_device: - return None - _, request = max(same_device, key=lambda pair: pair[1].get('ts') or 0) - request_id = str(request.get('requestId', '') or '').strip() - if not request_id: - return None - token = secrets.token_urlsafe(32) - if token == os.environ.get('OPENCLAW_GATEWAY_TOKEN'): - raise RuntimeError('temporary device token generation collided with gateway token') - now = int(time.time() * 1000) - operator_token = { - 'token': token, - 'role': 'operator', - 'scopes': INITIAL_PAIRING_SCOPES, - 'createdAtMs': now, - } - device = { - 'deviceId': device_id, - 'publicKey': public_key, - 'clientId': 'cli', - 'clientMode': 'cli', - 'role': 'operator', - 'roles': ['operator'], - 'scopes': INITIAL_PAIRING_SCOPES, - 'approvedScopes': INITIAL_PAIRING_SCOPES, - 'tokens': {'operator': operator_token}, - 'createdAtMs': now, - 'approvedAtMs': now, - } - for key, _ in same_device: - pending.pop(key, None) - paired[device_id] = device - auth = { - 'version': 1, - 'deviceId': device_id, - 'tokens': {'operator': operator_token}, - } - _write_json_atomic(pending_path, pending) - _write_json_atomic(paired_path, paired) - _write_json_atomic(auth_path, auth) - return request_id - except Exception as err: - print(f'[auto-pair] initial CLI pairing seed skipped: {type(err).__name__}: {str(err)[:220]}') +def pairing_required_request_id(out, err): + if not is_pairing_required_list_failure(out, err): return None + message = f'{out}\n{err}' + match = re.search(r'\brequestId\b["\']?\s*[:=]\s*["\']?([A-Za-z0-9._:-]+)', message) + if match: + return match.group(1).strip() + match = re.search(r'\(requestId:\s*([^)]+)\)', message) + return match.group(1).strip() if match else None -def is_pairing_required_list_failure(out, err): - message = f'{out}\n{err}'.lower() - return 'pairing required' in message and 'device is not approved yet' in message +def brief_child_error(out, err): + lines = [line.strip() for line in f'{err}\n{out}'.splitlines() if line.strip()] + return (lines[-1] if lines else '')[:400] # Workaround boundary (NemoClaw#4462): list calls stay gateway-pinned so the # watcher inspects live state. Approval calls drop the gateway env triplet so @@ -2738,14 +2568,21 @@ def sleep_for_next_poll(default_seconds, productive=True): while time.time() < DEADLINE: rc, out, err = run(OPENCLAW, 'devices', 'list', '--json') if rc != 0 or not out: - if is_pairing_required_list_failure(out, err): - seeded_request = seed_initial_cli_pairing_from_state() - if seeded_request: + initial_request_id = pairing_required_request_id(out, err) + if initial_request_id and initial_request_id not in HANDLED: + arc, aout, aerr = run( + OPENCLAW, 'devices', 'approve', initial_request_id, '--json', strip_gateway_env=True, + ) + if arc == 0: + HANDLED.add(initial_request_id) APPROVED += 1 - print(f'[auto-pair] seeded initial CLI pairing request={seeded_request}') + print(f'[auto-pair] approved initial CLI pairing request={initial_request_id}') FAST_REENTRY_REMAINING = max(FAST_REENTRY_REMAINING, FAST_REENTRY_POLLS) sleep_for_next_poll(FAST_REENTRY_INTERVAL) continue + failure = brief_child_error(aout, aerr) + if arc != 124 and failure: + print(f'[auto-pair] initial CLI approve failed request={initial_request_id}: {failure}') sleep_for_next_poll(SLOW_INTERVAL if SLOW_MODE else 1, productive=False) continue try: @@ -2812,8 +2649,10 @@ while time.time() < DEADLINE: HANDLED.add(request_id) APPROVED += 1 print(f'[auto-pair] approved request={request_id} client={client_id} mode={client_mode}') - elif aout or aerr: - print(f'[auto-pair] approve failed request={request_id}: {(aerr or aout)[:400]}') + else: + failure = brief_child_error(aout, aerr) + if failure: + print(f'[auto-pair] approve failed request={request_id}: {failure}') # Drop previously-bumped requestIds that the gateway no longer reports # as pending so a future re-appearance of the same id (very unlikely, # but kept robust) can bump again. The set is otherwise small and diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index 71bb6ce69c2..820079e406d 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -44,7 +44,7 @@ def _nemoclaw_test_sleep(seconds): _nemoclaw_test_clock.__setitem__(0, _nemoclaw describe("nemoclaw-start initial CLI auto-pair bootstrap (#6113)", () => { const src = fs.readFileSync(START_SCRIPT, "utf-8"); - it("seeds an initial CLI pairing request when device list is itself gated", () => { + it("approves an initial CLI pairing request when device list is itself gated (#6113)", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-bootstrap-")); const fakeOpenclaw = path.join(tmpDir, "openclaw"); const stateDir = path.join(tmpDir, "state"); @@ -53,6 +53,7 @@ describe("nemoclaw-start initial CLI auto-pair bootstrap (#6113)", () => { const pendingFile = path.join(devicesDir, "pending.json"); const pairedFile = path.join(devicesDir, "paired.json"); const authFile = path.join(identityDir, "device-auth.json"); + const approveLog = path.join(tmpDir, "approve-env.json"); fs.mkdirSync(devicesDir, { recursive: true }); fs.mkdirSync(identityDir, { recursive: true }); const publicKey = "y3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8"; @@ -96,6 +97,10 @@ if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' exit 1 fi +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then + node -e 'const fs=require("fs"); fs.writeFileSync(process.argv[1], JSON.stringify({url:process.env.OPENCLAW_GATEWAY_URL||null, port:process.env.OPENCLAW_GATEWAY_PORT||null, token:process.env.OPENCLAW_GATEWAY_TOKEN||null, args:process.argv.slice(3)})); fs.writeFileSync(process.argv[2], JSON.stringify({${JSON.stringify(deviceId)}:{deviceId:${JSON.stringify(deviceId)},publicKey:${JSON.stringify(publicKey)},clientId:"cli",clientMode:"cli",scopes:["operator.pairing"],approvedScopes:["operator.pairing"]}}));' ${JSON.stringify(approveLog)} ${JSON.stringify(pairedFile)} "$@" + exit 0 +fi echo "unexpected: $*" >&2 exit 2 `, @@ -117,9 +122,14 @@ exit 2 }); expect(run.status).toBe(0); - expect(run.stdout).toContain("[auto-pair] seeded initial CLI pairing request=request-1"); + expect(run.stdout).toContain("[auto-pair] approved initial CLI pairing request=request-1"); + expect(JSON.parse(fs.readFileSync(approveLog, "utf-8"))).toEqual({ + url: null, + port: null, + token: null, + args: ["devices", "approve", "request-1", "--json"], + }); const paired = JSON.parse(fs.readFileSync(pairedFile, "utf-8")); - const auth = JSON.parse(fs.readFileSync(authFile, "utf-8")); expect(Object.keys(paired)).toEqual([deviceId]); expect(paired[deviceId]).toMatchObject({ deviceId, @@ -129,15 +139,8 @@ exit 2 scopes: ["operator.pairing"], approvedScopes: ["operator.pairing"], }); - expect(paired[deviceId].tokens.operator.token).toBeTruthy(); - expect(paired[deviceId].tokens.operator.token).not.toBe("gateway-token"); - expect(auth).toMatchObject({ - version: 1, - deviceId, - tokens: { operator: { role: "operator", scopes: ["operator.pairing"] } }, - }); - expect(auth.tokens.operator.token).toBe(paired[deviceId].tokens.operator.token); - expect(JSON.parse(fs.readFileSync(pendingFile, "utf-8"))).toEqual({}); + expect(fs.existsSync(authFile)).toBe(false); + expect(JSON.parse(fs.readFileSync(pendingFile, "utf-8"))).toHaveProperty("request-1"); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } @@ -204,7 +207,7 @@ exit 1 }); expect(run.status).toBe(0); - expect(run.stdout).not.toContain("seeded initial CLI pairing"); + expect(run.stdout).not.toContain("approved initial CLI pairing"); expect(fs.existsSync(pairedFile)).toBe(false); expect(fs.existsSync(authFile)).toBe(false); } finally { From 8461b0bf9404fbdccd529e0fd0da7b5049f40d85 Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 01:04:39 +0800 Subject: [PATCH 04/16] fix: validate gated cli pairing request Signed-off-by: Chengjie Wang --- scripts/nemoclaw-start.sh | 108 +++++++++++++++++- ...nemoclaw-start-auto-pair-bootstrap.test.ts | 2 +- 2 files changed, 107 insertions(+), 3 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 3986fe8e847..74f34b679ad 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2377,6 +2377,8 @@ start_auto_pair() { OPENCLAW_BIN="$OPENCLAW" nohup "${run_prefix[@]}" python3 -u - <<'PYAUTOPAIR' >>/tmp/auto-pair.log 2>&1 & import json import importlib.util +import base64 +import hashlib import os import re import stat @@ -2403,10 +2405,11 @@ def load_approval_policy(path): return ( module.approval_request_decision, module.gateway_approval_env, + module.ALLOWED_SCOPES, ) -approval_request_decision, gateway_approval_env = load_approval_policy(APPROVAL_POLICY_FILE) +approval_request_decision, gateway_approval_env, policy_allowed_scopes = load_approval_policy(APPROVAL_POLICY_FILE) OPENCLAW = os.environ.get('OPENCLAW_BIN', 'openclaw') @@ -2493,6 +2496,103 @@ HANDLED = set() # Track rejected/approved requestIds to avoid reprocessing RUN_TIMEOUT_SECS = _env_seconds('NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS', 10) +def _read_json_object(path): + with open(path, 'r', encoding='utf-8') as handle: + data = json.load(handle) + if not isinstance(data, dict): + raise RuntimeError(f'{path} is not a JSON object') + return data + + +def _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 '' + der = base64.b64decode(body) + if len(der) < 32: + return '' + return base64.urlsafe_b64encode(der[-32:]).decode('ascii').rstrip('=') + + +def initial_cli_request_is_allowlisted(request_id): + # SOURCE_OF_TRUTH_REVIEW (NemoClaw#6113 gated-list bootstrap): + # Invalid state: `devices list --json` can be gated by the same initial + # CLI pairing request the watcher needs to approve, so the request id is + # only available in the structured error text. + # Source boundary: this function reads local OpenClaw pending/identity + # state only to validate the parsed request id before delegating approval + # back to `openclaw devices approve`, which owns locking, token creation, + # and state publication. The watcher never writes OpenClaw state. + # Source-fix constraint: OpenClaw should expose a first-run local + # bootstrap/list API that returns the pending request without requiring an + # already-approved device. This compatibility path supports packaged + # gateway builds that still gate list. + # Removal condition: delete this branch once the pinned OpenClaw release + # exposes that bootstrap/list API and NemoClaw no longer supports gated + # list behavior for first-run CLI pairing. + state_dir = os.environ.get('OPENCLAW_STATE_DIR') or '/sandbox/.openclaw' + pending_path = os.path.join(state_dir, 'devices', 'pending.json') + identity_path = os.path.join(state_dir, 'identity', 'device.json') + try: + pending = _read_json_object(pending_path) + identity = _read_json_object(identity_path) + request = pending.get(request_id) + if not isinstance(request, dict): + return False + device_id = str(identity.get('deviceId', '') or '').strip() + public_key = _identity_public_key(identity) + if not device_id or not public_key: + return False + public_key_raw = base64.urlsafe_b64decode(public_key + '=' * (-len(public_key) % 4)) + if len(public_key_raw) != 32 or hashlib.sha256(public_key_raw).hexdigest() != device_id: + return False + if str(request.get('deviceId', '')).strip() != device_id: + return False + if str(request.get('publicKey', '')).strip() != public_key: + return False + if str(request.get('clientId', '')).strip() != 'cli': + return False + if str(request.get('clientMode', '')).strip() != 'cli': + return False + roles = set() + role = request.get('role') + if role is not None: + if not isinstance(role, str) or not role.strip(): + return False + roles.add(role.strip()) + raw_roles = request.get('roles') + if raw_roles is not None: + if not isinstance(raw_roles, list): + return False + for item in raw_roles: + if not isinstance(item, str) or not item.strip(): + return False + roles.add(item.strip()) + if roles != {'operator'}: + return False + raw_scopes = request.get('scopes') + if not isinstance(raw_scopes, list) or not raw_scopes: + return False + scopes = set() + for item in raw_scopes: + if not isinstance(item, str) or not item.strip(): + return False + scope = item.strip() + if scope not in policy_allowed_scopes or scope in scopes: + return False + scopes.add(scope) + if 'operator.pairing' not in scopes: + return False + return approval_request_decision(request)['allowed'] is True + except (OSError, ValueError, RuntimeError) as err: + print(f'[auto-pair] initial CLI pairing validation skipped request={request_id}: {brief_child_error("", str(err))}') + return False + + def is_pairing_required_list_failure(out, err): message = f'{out}\n{err}'.lower() return 'pairing required' in message and 'device is not approved yet' in message @@ -2569,7 +2669,11 @@ while time.time() < DEADLINE: rc, out, err = run(OPENCLAW, 'devices', 'list', '--json') if rc != 0 or not out: initial_request_id = pairing_required_request_id(out, err) - if initial_request_id and initial_request_id not in HANDLED: + if ( + initial_request_id + and initial_request_id not in HANDLED + and initial_cli_request_is_allowlisted(initial_request_id) + ): arc, aout, aerr = run( OPENCLAW, 'devices', 'approve', initial_request_id, '--json', strip_gateway_env=True, ) diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index 820079e406d..b967afa8a24 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -146,7 +146,7 @@ exit 2 } }, 40_000); - it("does not seed when device list fails for a non-pairing error", () => { + it("does not seed when device list fails for a non-pairing error (#6113)", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-nonpairing-")); const fakeOpenclaw = path.join(tmpDir, "openclaw"); const stateDir = path.join(tmpDir, "state"); From c79a85a93cf0363bc91d330379476953cdc1a252 Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 01:25:55 +0800 Subject: [PATCH 05/16] test: cover gated cli agent bootstrap --- scripts/nemoclaw-start.sh | 1 + ...nemoclaw-start-auto-pair-bootstrap.test.ts | 109 ++++++++++++++++++ 2 files changed, 110 insertions(+) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 74f34b679ad..0aff5b044cc 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2686,6 +2686,7 @@ while time.time() < DEADLINE: continue failure = brief_child_error(aout, aerr) if arc != 124 and failure: + HANDLED.add(initial_request_id) print(f'[auto-pair] initial CLI approve failed request={initial_request_id}: {failure}') sleep_for_next_poll(SLOW_INTERVAL if SLOW_MODE else 1, productive=False) continue diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index b967afa8a24..687f75b0472 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -54,6 +54,7 @@ describe("nemoclaw-start initial CLI auto-pair bootstrap (#6113)", () => { const pairedFile = path.join(devicesDir, "paired.json"); const authFile = path.join(identityDir, "device-auth.json"); const approveLog = path.join(tmpDir, "approve-env.json"); + const agentOutput = path.join(tmpDir, "agent-output.txt"); fs.mkdirSync(devicesDir, { recursive: true }); fs.mkdirSync(identityDir, { recursive: true }); const publicKey = "y3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8"; @@ -101,6 +102,15 @@ if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then node -e 'const fs=require("fs"); fs.writeFileSync(process.argv[1], JSON.stringify({url:process.env.OPENCLAW_GATEWAY_URL||null, port:process.env.OPENCLAW_GATEWAY_PORT||null, token:process.env.OPENCLAW_GATEWAY_TOKEN||null, args:process.argv.slice(3)})); fs.writeFileSync(process.argv[2], JSON.stringify({${JSON.stringify(deviceId)}:{deviceId:${JSON.stringify(deviceId)},publicKey:${JSON.stringify(publicKey)},clientId:"cli",clientMode:"cli",scopes:["operator.pairing"],approvedScopes:["operator.pairing"]}}));' ${JSON.stringify(approveLog)} ${JSON.stringify(pairedFile)} "$@" exit 0 fi +if [ "\${1:-}" = "agent" ]; then + if [ ! -s ${JSON.stringify(pairedFile)} ]; then + echo "EMBEDDED FALLBACK: gateway unavailable" + exit 0 + fi + printf 'tool:file-write-ok\\n' > ${JSON.stringify(agentOutput)} + echo "gateway agent completed" + exit 0 +fi echo "unexpected: $*" >&2 exit 2 `, @@ -141,11 +151,110 @@ exit 2 }); expect(fs.existsSync(authFile)).toBe(false); expect(JSON.parse(fs.readFileSync(pendingFile, "utf-8"))).toHaveProperty("request-1"); + + const agent = spawnSync(fakeOpenclaw, ["agent", "run", "write-file"], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_STATE_DIR: stateDir, + }, + timeout: 10_000, + }); + expect(agent.status).toBe(0); + expect(`${agent.stdout}\n${agent.stderr}`).not.toContain("EMBEDDED FALLBACK"); + expect(fs.readFileSync(agentOutput, "utf-8")).toBe("tool:file-write-ok\n"); } finally { fs.rmSync(tmpDir, { recursive: true, force: true }); } }, 40_000); + it.each([ + ["mismatched public key", { publicKey: "wrong" }], + ["non-cli client id", { clientId: "browser" }], + ["non-cli client mode", { clientMode: "webchat" }], + ["non-operator role", { role: "viewer", roles: ["viewer"] }], + ["malformed roles", { roles: "operator" }], + ["disallowed scope", { scopes: ["operator.pairing", "admin.write"] }], + ["missing pairing scope", { scopes: ["operator.write"] }], + ])( + "rejects %s before initial CLI approve (#6113)", + (_name, override) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-reject-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const pendingFile = path.join(devicesDir, "pending.json"); + const approveLog = path.join(tmpDir, "approve-called"); + fs.mkdirSync(devicesDir, { recursive: true }); + 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( + pendingFile, + JSON.stringify({ + "request-1": { + requestId: "request-1", + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + ts: 100, + ...override, + }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then + printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' + exit 1 +fi +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then + touch ${JSON.stringify(approveLog)} + exit 0 +fi +exit 2 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "1", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + expect(run.stdout).not.toContain("approved initial CLI pairing"); + expect(fs.existsSync(approveLog)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, + 40_000, + ); + it("does not seed when device list fails for a non-pairing error (#6113)", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-nonpairing-")); const fakeOpenclaw = path.join(tmpDir, "openclaw"); From 1465087c1821e66ec113cf007034f5532809f0cd Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 02:11:14 +0800 Subject: [PATCH 06/16] fix: harden gated cli pairing parser --- scripts/nemoclaw-start.sh | 84 ++++- ...nemoclaw-start-auto-pair-bootstrap.test.ts | 342 ++++++++++++++++++ 2 files changed, 420 insertions(+), 6 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 0aff5b044cc..af41db6f632 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2554,6 +2554,10 @@ def initial_cli_request_is_allowlisted(request_id): return False if str(request.get('publicKey', '')).strip() != public_key: return False + # OpenClaw CLI initial pairing records use clientId/clientMode `cli` + # in the observed DGX Spark/Station repros and in the paired-state + # fixtures for this PR. The broader policy still handles normal + # openclaw-cli scope upgrades through the main pending-list branch. if str(request.get('clientId', '')).strip() != 'cli': return False if str(request.get('clientMode', '')).strip() != 'cli': @@ -2594,22 +2598,91 @@ def initial_cli_request_is_allowlisted(request_id): def is_pairing_required_list_failure(out, err): + # SOURCE_OF_TRUTH_REVIEW (NemoClaw#6113 gated-list failure detection): + # Invalid state: initial `openclaw devices list --json` returns the gateway + # pairing-required denial instead of the pending request list. + # Source boundary: the compatibility trigger only recognizes the stable + # gateway denial text and still requires local pending/identity validation + # before approval is delegated to OpenClaw. + # Source-fix constraint: OpenClaw should expose a structured bootstrap/list + # API for first-run CLI pairing. + # Regression test: the non-pairing error fixture must not call approve. + # Removal condition: delete with initial_cli_request_is_allowlisted once the + # pinned OpenClaw release exposes that bootstrap/list API. message = f'{out}\n{err}'.lower() return 'pairing required' in message and 'device is not approved yet' in message +REQUEST_ID_RE = re.compile(r'^[A-Za-z0-9._:-]{1,128}$') + + +def _structured_request_ids(text): + try: + data = json.loads(text) + except Exception: + return [] + found = [] + + def walk(value): + if isinstance(value, dict): + for key, item in value.items(): + if key in {'requestId', 'request_id'} and isinstance(item, str): + found.append(item.strip()) + else: + walk(item) + elif isinstance(value, list): + for item in value: + walk(item) + + walk(data) + return found + + def pairing_required_request_id(out, err): + # SOURCE_OF_TRUTH_REVIEW (NemoClaw#6113 gated-list requestId extraction): + # Invalid state: the requestId needed for canonical `devices approve` is + # sometimes only present in the list denial payload. + # Source boundary: parse one bounded requestId from structured JSON first, + # then from the reviewed error-text forms; ambiguous, overlong, or malformed + # output fails closed and never reaches approve. + # Source-fix constraint: OpenClaw should return requestId in a stable + # structured error field for this first-run bootstrap path. + # Regression test: malformed, overlong, whitespace, and multiple requestIds + # must not call approve. + # Removal condition: delete with initial_cli_request_is_allowlisted once the + # pinned OpenClaw release exposes a bootstrap/list API. if not is_pairing_required_list_failure(out, err): return None message = f'{out}\n{err}' - match = re.search(r'\brequestId\b["\']?\s*[:=]\s*["\']?([A-Za-z0-9._:-]+)', message) - if match: - return match.group(1).strip() - match = re.search(r'\(requestId:\s*([^)]+)\)', message) - return match.group(1).strip() if match else None + candidates = [] + for text in (out, err): + candidates.extend(_structured_request_ids(text)) + candidates.extend( + match.group(1).strip() + for match in re.finditer(r'\brequestId\b["\']?\s*[:=]\s*["\']?([A-Za-z0-9._:-]{1,128})', message) + ) + candidates.extend( + match.group(1).strip() + for match in re.finditer(r'\(requestId:\s*([A-Za-z0-9._:-]{1,128})\)', message) + ) + valid = [candidate for candidate in candidates if REQUEST_ID_RE.fullmatch(candidate)] + if not valid or len(set(valid)) != 1 or len(valid) != len(candidates): + return None + return valid[0] def brief_child_error(out, err): + # SOURCE_OF_TRUTH_REVIEW (auto-pair child error summary): + # Invalid state: child openclaw failures often include noisy locale/setup + # output before the actual error. + # Source boundary: logs only the last non-empty child line, capped to 400 + # characters; decisions never depend on this summary. + # Source-fix constraint: OpenClaw should expose structured error codes so + # callers do not need stdout/stderr message summaries. + # Regression test: approve-failure fixtures assert the actionable child + # error remains visible. + # Removal condition: retire when OpenClaw CLI returns structured errors for + # the watched devices list/approve calls. lines = [line.strip() for line in f'{err}\n{out}'.splitlines() if line.strip()] return (lines[-1] if lines else '')[:400] @@ -2686,7 +2759,6 @@ while time.time() < DEADLINE: continue failure = brief_child_error(aout, aerr) if arc != 124 and failure: - HANDLED.add(initial_request_id) print(f'[auto-pair] initial CLI approve failed request={initial_request_id}: {failure}') sleep_for_next_poll(SLOW_INTERVAL if SLOW_MODE else 1, productive=False) continue diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index 687f75b0472..726d00a3aef 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -173,7 +173,12 @@ exit 2 ["non-cli client id", { clientId: "browser" }], ["non-cli client mode", { clientMode: "webchat" }], ["non-operator role", { role: "viewer", roles: ["viewer"] }], + ["empty role", { role: "" }], ["malformed roles", { roles: "operator" }], + ["empty role entry", { roles: ["operator", ""] }], + ["malformed scopes", { scopes: "operator.pairing" }], + ["empty scopes", { scopes: [] }], + ["duplicate scopes", { scopes: ["operator.pairing", "operator.pairing"] }], ["disallowed scope", { scopes: ["operator.pairing", "admin.write"] }], ["missing pairing scope", { scopes: ["operator.write"] }], ])( @@ -255,6 +260,343 @@ exit 2 40_000, ); + it.each([ + [ + "multiple request ids", + "pairing required: device is not approved yet requestId: request-1 requestId: request-2", + ], + [ + "overlong request id", + `pairing required: device is not approved yet requestId: ${"r".repeat(129)}`, + ], + [ + "whitespace request id", + "pairing required: device is not approved yet (requestId: request 1)", + ], + ])( + "rejects %s from gated-list errors before initial CLI approve (#6113)", + (_name, listError) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-requestid-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const pendingFile = path.join(devicesDir, "pending.json"); + const approveLog = path.join(tmpDir, "approve-called"); + fs.mkdirSync(devicesDir, { recursive: true }); + fs.mkdirSync(identityDir, { recursive: true }); + const publicKey = "y3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8"; + const deviceId = "04a4c561c730435e9f6a2e38d2e7b929bcbec2ea1c37d3dd053f3341ecce4e47"; + const validRequest = { + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + ts: 100, + }; + fs.writeFileSync( + path.join(identityDir, "device.json"), + JSON.stringify({ + deviceId, + publicKeyPem: + "-----BEGIN PUBLIC KEY-----\nMCowBQYDK2VwAyEAy3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8=\n-----END PUBLIC KEY-----\n", + }), + ); + fs.writeFileSync( + pendingFile, + JSON.stringify({ + "request-1": { requestId: "request-1", ...validRequest }, + "request-2": { requestId: "request-2", ...validRequest }, + ["r".repeat(129)]: { requestId: "r".repeat(129), ...validRequest }, + "request 1": { requestId: "request 1", ...validRequest }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then + printf '%s\\n' ${JSON.stringify(listError)} + exit 1 +fi +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then + touch ${JSON.stringify(approveLog)} + exit 0 +fi +exit 2 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "1", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + expect(run.stdout).not.toContain("approved initial CLI pairing"); + expect(fs.existsSync(approveLog)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, + 40_000, + ); + + it.each([ + ["missing identity device id", { deviceId: undefined }], + ["missing identity public key", { publicKeyPem: undefined }], + ["mismatched identity device id", { deviceId: "not-the-device" }], + ["short identity public key", { publicKey: "short" }], + [ + "identity public key with wrong hash", + { publicKey: "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" }, + ], + ])( + "rejects %s before initial CLI approve (#6113)", + (_name, identityOverride) => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-identity-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const approveLog = path.join(tmpDir, "approve-called"); + fs.mkdirSync(devicesDir, { recursive: true }); + 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", + ...identityOverride, + }), + ); + fs.writeFileSync( + path.join(devicesDir, "pending.json"), + JSON.stringify({ + "request-1": { + requestId: "request-1", + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + ts: 100, + }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then + printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' + exit 1 +fi +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then + touch ${JSON.stringify(approveLog)} + exit 0 +fi +exit 2 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "1", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + expect(run.stdout).not.toContain("approved initial CLI pairing"); + expect(fs.existsSync(approveLog)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, + 40_000, + ); + + it("fails closed for malformed identity public keys without terminating the watcher (#6113)", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-bad-identity-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const approveLog = path.join(tmpDir, "approve-called"); + fs.mkdirSync(devicesDir, { recursive: true }); + fs.mkdirSync(identityDir, { recursive: true }); + fs.writeFileSync( + path.join(identityDir, "device.json"), + JSON.stringify({ + deviceId: "04a4c561c730435e9f6a2e38d2e7b929bcbec2ea1c37d3dd053f3341ecce4e47", + publicKeyPem: "-----BEGIN PUBLIC KEY-----\nnot-valid-base64\n-----END PUBLIC KEY-----\n", + }), + ); + fs.writeFileSync( + path.join(devicesDir, "pending.json"), + JSON.stringify({ + "request-1": { + requestId: "request-1", + deviceId: "04a4c561c730435e9f6a2e38d2e7b929bcbec2ea1c37d3dd053f3341ecce4e47", + publicKey: "y3vjb9p8tAecivI1l5f1Hdc9QdZJSt3BmLkJMM7wZD8", + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + ts: 100, + }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then + printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' + exit 1 +fi +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then + touch ${JSON.stringify(approveLog)} + exit 0 +fi +exit 2 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "1", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + expect(run.stdout).not.toContain("approved initial CLI pairing"); + expect(fs.existsSync(approveLog)).toBe(false); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 40_000); + + it("retries a transient initial CLI approve failure on the next gated-list poll (#6113)", () => { + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-retry-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const pendingFile = path.join(devicesDir, "pending.json"); + const approveCount = path.join(tmpDir, "approve-count"); + fs.mkdirSync(devicesDir, { recursive: true }); + 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( + pendingFile, + JSON.stringify({ + "request-1": { + requestId: "request-1", + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + ts: 100, + }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then + printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' + exit 1 +fi +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then + count=0 + if [ -f ${JSON.stringify(approveCount)} ]; then + count=$(cat ${JSON.stringify(approveCount)}) + fi + count=$((count + 1)) + printf '%s' "$count" > ${JSON.stringify(approveCount)} + if [ "$count" -eq 1 ]; then + echo "gateway restarting" >&2 + exit 1 + fi + exit 0 +fi +exit 2 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "2", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + expect(fs.readFileSync(approveCount, "utf-8")).toBe("2"); + expect(run.stdout).toContain( + "[auto-pair] initial CLI approve failed request=request-1: gateway restarting", + ); + expect(run.stdout).toContain("[auto-pair] approved initial CLI pairing request=request-1"); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 40_000); + it("does not seed when device list fails for a non-pairing error (#6113)", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-nonpairing-")); const fakeOpenclaw = path.join(tmpDir, "openclaw"); From 1afcee0fdf5255933f6db84aed99d3069f8c76a9 Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 02:42:22 +0800 Subject: [PATCH 07/16] fix: reject malformed gated pairing ids --- scripts/nemoclaw-start.sh | 7 +++++-- test/nemoclaw-start-auto-pair-bootstrap.test.ts | 11 +++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index af41db6f632..594a3923aa6 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2658,8 +2658,11 @@ def pairing_required_request_id(out, err): for text in (out, err): candidates.extend(_structured_request_ids(text)) candidates.extend( - match.group(1).strip() - for match in re.finditer(r'\brequestId\b["\']?\s*[:=]\s*["\']?([A-Za-z0-9._:-]{1,128})', message) + next(group for group in match.groups() if group is not None) + for match in re.finditer( + r'\brequestId\b["\']?\s*[:=]\s*(?:"([A-Za-z0-9._:-]{1,128})"|\'([A-Za-z0-9._:-]{1,128})\'|([A-Za-z0-9._:-]{1,128})(?=$|[,}\]\)]))', + message, + ) ) candidates.extend( match.group(1).strip() diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index 726d00a3aef..21b8ec970c9 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -265,14 +265,23 @@ exit 2 "multiple request ids", "pairing required: device is not approved yet requestId: request-1 requestId: request-2", ], + ["missing request id", "pairing required: device is not approved yet"], [ "overlong request id", `pairing required: device is not approved yet requestId: ${"r".repeat(129)}`, ], + [ + "overlong request id with pending prefix", + `pairing required: device is not approved yet requestId: ${"p".repeat(129)}`, + ], [ "whitespace request id", "pairing required: device is not approved yet (requestId: request 1)", ], + [ + "whitespace request id with pending prefix", + "pairing required: device is not approved yet requestId: request 1", + ], ])( "rejects %s from gated-list errors before initial CLI approve (#6113)", (_name, listError) => { @@ -311,7 +320,9 @@ exit 2 "request-1": { requestId: "request-1", ...validRequest }, "request-2": { requestId: "request-2", ...validRequest }, ["r".repeat(129)]: { requestId: "r".repeat(129), ...validRequest }, + ["p".repeat(128)]: { requestId: "p".repeat(128), ...validRequest }, "request 1": { requestId: "request 1", ...validRequest }, + request: { requestId: "request", ...validRequest }, }), ); fs.writeFileSync( From d6c9d3b88998afe32cb39606326161edbec3690a Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 02:54:16 +0800 Subject: [PATCH 08/16] fix: reject ambiguous gated pairing ids --- scripts/nemoclaw-start.sh | 2 ++ 1 file changed, 2 insertions(+) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 594a3923aa6..6d8e7aaaad3 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2654,6 +2654,8 @@ def pairing_required_request_id(out, err): if not is_pairing_required_list_failure(out, err): return None message = f'{out}\n{err}' + if len(re.findall(r'\brequestId\b', message)) != 1: + return None candidates = [] for text in (out, err): candidates.extend(_structured_request_ids(text)) From a847002cc8b7232079c537063eacd2d2e4b04c8b Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 03:06:43 +0800 Subject: [PATCH 09/16] fix: narrow initial cli pairing scope --- scripts/nemoclaw-start.sh | 4 ++-- .../nemoclaw-start-auto-pair-bootstrap.test.ts | 18 +++++++++++++++--- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 6d8e7aaaad3..e9883913fb6 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2589,7 +2589,7 @@ def initial_cli_request_is_allowlisted(request_id): if scope not in policy_allowed_scopes or scope in scopes: return False scopes.add(scope) - if 'operator.pairing' not in scopes: + if scopes != {'operator.pairing'}: return False return approval_request_decision(request)['allowed'] is True except (OSError, ValueError, RuntimeError) as err: @@ -2662,7 +2662,7 @@ def pairing_required_request_id(out, err): candidates.extend( next(group for group in match.groups() if group is not None) for match in re.finditer( - r'\brequestId\b["\']?\s*[:=]\s*(?:"([A-Za-z0-9._:-]{1,128})"|\'([A-Za-z0-9._:-]{1,128})\'|([A-Za-z0-9._:-]{1,128})(?=$|[,}\]\)]))', + r'\brequestId\b["\']?\s*[:=]\s*(?:"([A-Za-z0-9._:-]{1,128})"(?=$|[,}\]\)])|\'([A-Za-z0-9._:-]{1,128})\'(?=$|[,}\]\)])|([A-Za-z0-9._:-]{1,128})(?=$|[,}\]\)]))', message, ) ) diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index 21b8ec970c9..8948db9c7a3 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -80,7 +80,7 @@ describe("nemoclaw-start initial CLI auto-pair bootstrap (#6113)", () => { clientMode: "cli", role: "operator", roles: ["operator"], - scopes: ["operator.pairing", "operator.write"], + scopes: ["operator.pairing"], remoteIp: "10.200.0.2", ts: 100, }, @@ -92,14 +92,21 @@ describe("nemoclaw-start initial CLI auto-pair bootstrap (#6113)", () => { set -euo pipefail if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then if [ -s ${JSON.stringify(pairedFile)} ]; then - node -e 'const fs=require("fs"); const paired=JSON.parse(fs.readFileSync(process.argv[1],"utf8")); process.stdout.write(JSON.stringify({pending:[], paired:Object.values(paired)})+"\\n")' ${JSON.stringify(pairedFile)} + cat <<'JSON' +{"pending":[],"paired":[{"deviceId":${JSON.stringify(deviceId)},"publicKey":${JSON.stringify(publicKey)},"clientId":"cli","clientMode":"cli","scopes":["operator.pairing"],"approvedScopes":["operator.pairing"]}]} +JSON exit 0 fi printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' exit 1 fi if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then - node -e 'const fs=require("fs"); fs.writeFileSync(process.argv[1], JSON.stringify({url:process.env.OPENCLAW_GATEWAY_URL||null, port:process.env.OPENCLAW_GATEWAY_PORT||null, token:process.env.OPENCLAW_GATEWAY_TOKEN||null, args:process.argv.slice(3)})); fs.writeFileSync(process.argv[2], JSON.stringify({${JSON.stringify(deviceId)}:{deviceId:${JSON.stringify(deviceId)},publicKey:${JSON.stringify(publicKey)},clientId:"cli",clientMode:"cli",scopes:["operator.pairing"],approvedScopes:["operator.pairing"]}}));' ${JSON.stringify(approveLog)} ${JSON.stringify(pairedFile)} "$@" + cat > ${JSON.stringify(approveLog)} <<'JSON' +{"url":null,"port":null,"token":null,"args":["devices","approve","request-1","--json"]} +JSON + cat > ${JSON.stringify(pairedFile)} <<'JSON' +{${JSON.stringify(deviceId)}:{"deviceId":${JSON.stringify(deviceId)},"publicKey":${JSON.stringify(publicKey)},"clientId":"cli","clientMode":"cli","scopes":["operator.pairing"],"approvedScopes":["operator.pairing"]}} +JSON exit 0 fi if [ "\${1:-}" = "agent" ]; then @@ -179,6 +186,7 @@ exit 2 ["malformed scopes", { scopes: "operator.pairing" }], ["empty scopes", { scopes: [] }], ["duplicate scopes", { scopes: ["operator.pairing", "operator.pairing"] }], + ["extra allowed scope", { scopes: ["operator.pairing", "operator.write"] }], ["disallowed scope", { scopes: ["operator.pairing", "admin.write"] }], ["missing pairing scope", { scopes: ["operator.write"] }], ])( @@ -282,6 +290,10 @@ exit 2 "whitespace request id with pending prefix", "pairing required: device is not approved yet requestId: request 1", ], + [ + "quoted request id with trailing text", + 'pairing required: device is not approved yet requestId: "request" 1', + ], ])( "rejects %s from gated-list errors before initial CLI approve (#6113)", (_name, listError) => { From 5a3f2e1ecf26b95f604609c82ef793b43543f802 Mon Sep 17 00:00:00 2001 From: Chengjie Wang Date: Tue, 7 Jul 2026 03:21:46 +0800 Subject: [PATCH 10/16] fix: fail closed on malformed cli identity --- scripts/nemoclaw-start.sh | 3 ++- test/nemoclaw-start-auto-pair-bootstrap.test.ts | 4 ++++ 2 files changed, 6 insertions(+), 1 deletion(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index e9883913fb6..86f4dfe406d 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2378,6 +2378,7 @@ start_auto_pair() { import json import importlib.util import base64 +import binascii import hashlib import os import re @@ -2592,7 +2593,7 @@ def initial_cli_request_is_allowlisted(request_id): if scopes != {'operator.pairing'}: return False return approval_request_decision(request)['allowed'] is True - except (OSError, ValueError, RuntimeError) as err: + except (OSError, ValueError, RuntimeError, binascii.Error) as err: print(f'[auto-pair] initial CLI pairing validation skipped request={request_id}: {brief_child_error("", str(err))}') return False diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index 8948db9c7a3..873fbca2cb9 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -380,6 +380,10 @@ exit 2 it.each([ ["missing identity device id", { deviceId: undefined }], ["missing identity public key", { publicKeyPem: undefined }], + [ + "malformed identity public key PEM", + { publicKeyPem: "-----BEGIN PUBLIC KEY-----\nnot-base64\n-----END PUBLIC KEY-----\n" }, + ], ["mismatched identity device id", { deviceId: "not-the-device" }], ["short identity public key", { publicKey: "short" }], [ From 818b7c18a93fbe5c9f76bf839586592031c326dd Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 7 Jul 2026 12:42:14 -0700 Subject: [PATCH 11/16] fix(auto-pair): move fast-to-slow transition to loop top + guard embedded requestId (#6113) PR #6330 review (cv): - item 2: the fast->slow deadline transition sat in the success path, after the gated list/approve-failure `continue`, so a permanently failing gated approval polled at 1s for the full 8h DEADLINE. Move the check to the top of the watcher loop so it runs before every failure `continue`; add permanent-failure coverage proving it drops to slow-mode rather than 1s-looping. - item 3: initial_cli_request_is_allowlisted trusted the pending record without checking its embedded requestId against the map key. Reject a missing/mismatched embedded requestId (fail closed), with negative regression cases. Signed-off-by: Prekshi Vyas Co-Authored-By: Claude Opus 4.8 (1M context) --- scripts/nemoclaw-start.sh | 26 +++--- ...nemoclaw-start-auto-pair-bootstrap.test.ts | 87 +++++++++++++++++++ 2 files changed, 103 insertions(+), 10 deletions(-) diff --git a/scripts/nemoclaw-start.sh b/scripts/nemoclaw-start.sh index 55d9c1cd65d..14c36313297 100755 --- a/scripts/nemoclaw-start.sh +++ b/scripts/nemoclaw-start.sh @@ -2573,6 +2573,12 @@ def initial_cli_request_is_allowlisted(request_id): request = pending.get(request_id) if not isinstance(request, dict): return False + # The map key is the authoritative request id. Reject a record whose + # embedded requestId is missing or disagrees with its key, so a + # malformed/tampered pending.json cannot approve a mismatched request. + # (PR #6330 review, cv item 3.) + if str(request.get('requestId', '') or '').strip() != str(request_id).strip(): + return False device_id = str(identity.get('deviceId', '') or '').strip() public_key = _identity_public_key(identity) if not device_id or not public_key: @@ -2776,6 +2782,16 @@ def sleep_for_next_poll(default_seconds, productive=True): while time.time() < DEADLINE: + # Fast-to-slow transition is checked at the TOP of every iteration — before + # any list/approve-failure `continue` below — so a permanently failing gated + # list/approve (or a sticky pending request) cannot hold the watcher in 1s + # polling for the full DEADLINE window; after FAST_DEADLINE it drops to + # SLOW_INTERVAL. Preventing that long-timeline re-creation of the + # NemoClaw#2484 connect-handler pile-up is exactly the point. + # (PR #6330 review, cv item 2.) + if not SLOW_MODE and time.time() >= FAST_DEADLINE: + SLOW_MODE = True + print(f'[auto-pair] fast-mode deadline reached; switching to slow-mode approvals={APPROVED}') rc, out, err = run(OPENCLAW, 'devices', 'list', '--json') if rc != 0 or not out: initial_request_id = pairing_required_request_id(out, err) @@ -2809,16 +2825,6 @@ while time.time() < DEADLINE: paired = data.get('paired') or [] has_browser = any((d.get('clientId') == 'openclaw-control-ui') or (d.get('clientMode') == 'webchat') for d in paired if isinstance(d, dict)) - # Fast-deadline transition is checked here, BEFORE the pending-branch - # `continue`, so that a sticky pending request (rejected unknown client - # added to HANDLED, or a permanent approve failure) cannot hold the - # watcher in 1s polling for the full DEADLINE window — that would - # re-create the NemoClaw#2484 connect-handler pile-up on a much longer - # timeline. - if not SLOW_MODE and time.time() >= FAST_DEADLINE: - SLOW_MODE = True - print(f'[auto-pair] fast-mode deadline reached; switching to slow-mode approvals={APPROVED}') - if pending: QUIET_POLLS = 0 attempted_request_ids = set() diff --git a/test/nemoclaw-start-auto-pair-bootstrap.test.ts b/test/nemoclaw-start-auto-pair-bootstrap.test.ts index 873fbca2cb9..ff4c5caea7b 100644 --- a/test/nemoclaw-start-auto-pair-bootstrap.test.ts +++ b/test/nemoclaw-start-auto-pair-bootstrap.test.ts @@ -176,6 +176,8 @@ exit 2 }, 40_000); it.each([ + ["mismatched embedded requestId", { requestId: "request-2" }], + ["missing embedded requestId", { requestId: "" }], ["mismatched public key", { publicKey: "wrong" }], ["non-cli client id", { clientId: "browser" }], ["non-cli client mode", { clientMode: "webchat" }], @@ -624,6 +626,91 @@ exit 2 } }, 40_000); + it("drops a permanently-failing gated approve to slow-mode instead of 1s-looping to the deadline (#6113)", () => { + // cv #6330 item 2: the fast->slow transition must be reached even when the + // gated list/approve path keeps failing and `continue`s. With a near-zero + // FAST_DEADLINE the first iteration must emit the slow-mode transition + // (proving the check runs before the failure `continue`), and the watcher + // must exit within the short deadline rather than busy-polling at 1s. + // (`_env_seconds` rejects a literal 0 as non-positive, so use a tiny value.) + const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-permfail-")); + const fakeOpenclaw = path.join(tmpDir, "openclaw"); + const stateDir = path.join(tmpDir, "state"); + const devicesDir = path.join(stateDir, "devices"); + const identityDir = path.join(stateDir, "identity"); + const pendingFile = path.join(devicesDir, "pending.json"); + fs.mkdirSync(devicesDir, { recursive: true }); + 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( + pendingFile, + JSON.stringify({ + "request-1": { + requestId: "request-1", + deviceId, + publicKey, + clientId: "cli", + clientMode: "cli", + role: "operator", + roles: ["operator"], + scopes: ["operator.pairing"], + ts: 100, + }, + }), + ); + fs.writeFileSync( + fakeOpenclaw, + `#!/usr/bin/env bash +set -euo pipefail +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "list" ]; then + printf '%s\\n' '{"ok":false,"error":{"reason":"pairing required: device is not approved yet (requestId: request-1)"}}' + exit 1 +fi +if [ "\${1:-}" = "devices" ] && [ "\${2:-}" = "approve" ]; then + echo "gateway permanently unavailable" >&2 + exit 1 +fi +exit 2 +`, + { mode: 0o755 }, + ); + + try { + const run = spawnSync("python3", ["-c", autoPairPythonScript(src, tmpDir)], { + encoding: "utf-8", + env: { + ...process.env, + OPENCLAW_BIN: fakeOpenclaw, + OPENCLAW_STATE_DIR: stateDir, + NEMOCLAW_AUTO_PAIR_FAST_DEADLINE_SECS: "0.01", + NEMOCLAW_AUTO_PAIR_DEADLINE_SECS: "1", + NEMOCLAW_AUTO_PAIR_SLOW_INTERVAL_SECS: "1", + }, + timeout: 30_000, + }); + + expect(run.status).toBe(0); + // The transition fired on the permanently-failing gated path (loop-top check). + expect(run.stdout).toContain( + "[auto-pair] fast-mode deadline reached; switching to slow-mode", + ); + expect(run.stdout).toContain( + "[auto-pair] initial CLI approve failed request=request-1: gateway permanently unavailable", + ); + } finally { + fs.rmSync(tmpDir, { recursive: true, force: true }); + } + }, 40_000); + it("does not seed when device list fails for a non-pairing error (#6113)", () => { const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-auto-pair-nonpairing-")); const fakeOpenclaw = path.join(tmpDir, "openclaw"); From 9a232ee37ba1f170af3851c4cc7a0f54f7e9e3fd Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 7 Jul 2026 14:15:50 -0700 Subject: [PATCH 12/16] test(e2e): prove packaged initial CLI pairing (#6113) Signed-off-by: Prekshi Vyas --- test/e2e/live/cloud-onboard.test.ts | 111 +++++++++++++++++++++++++++- 1 file changed, 110 insertions(+), 1 deletion(-) diff --git a/test/e2e/live/cloud-onboard.test.ts b/test/e2e/live/cloud-onboard.test.ts index f2e84abc23c..42f1d6e705b 100644 --- a/test/e2e/live/cloud-onboard.test.ts +++ b/test/e2e/live/cloud-onboard.test.ts @@ -7,7 +7,11 @@ import path from "node:path"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText } from "../fixtures/clients/command.ts"; import { type HostCliClient } from "../fixtures/clients/host.ts"; -import { type SandboxClient, validateSandboxName } from "../fixtures/clients/sandbox.ts"; +import { + type SandboxClient, + trustedSandboxShellScript, + validateSandboxName, +} from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { requireHostedInferenceConfig } from "../fixtures/hosted-inference.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; @@ -62,6 +66,107 @@ async function cleanup( } } +async function assertPackagedInitialCliPairing(sandbox: SandboxClient): Promise { + const result = await sandbox.execShell( + SANDBOX_NAME, + trustedSandboxShellScript(String.raw` +set -euo pipefail +auto_pair_log=/tmp/auto-pair.log +deadline=$((SECONDS + 30)) +while ! grep -q 'approved initial CLI pairing request=' "$auto_pair_log" 2>/dev/null; do + if [ "$SECONDS" -ge "$deadline" ]; then + echo "INITIAL_CLI_PAIRING_MARKER_MISSING" >&2 + cat "$auto_pair_log" >&2 2>/dev/null || true + exit 20 + fi + sleep 1 +done + +devices_json=/tmp/nemoclaw-6113-devices.json +devices_err=/tmp/nemoclaw-6113-devices.err +if ! openclaw devices list --json >"$devices_json" 2>"$devices_err"; then + echo "POST_BOOTSTRAP_DEVICES_LIST_FAILED" >&2 + cat "$devices_err" >&2 + exit 21 +fi + +python3 - "$devices_json" <<'PY' +import json +import sys +from pathlib import Path + +value = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) +pending = value.get("pending") or [] +paired = value.get("paired") or [] +if isinstance(pending, dict): + pending = list(pending.values()) +if isinstance(paired, dict): + paired = list(paired.values()) +if not isinstance(pending, list) or not isinstance(paired, list): + raise SystemExit("devices list must expose pending and paired collections") +if pending: + raise SystemExit(f"initial CLI pairing left pending requests: {len(pending)}") +identity = json.loads( + Path("/sandbox/.openclaw/identity/device.json").read_text(encoding="utf-8") +) +device_id = str(identity.get("deviceId") or "").strip() +matches = [ + device + for device in paired + if isinstance(device, dict) + and str(device.get("deviceId") or "").strip() == device_id + and device.get("clientId") == "cli" + and device.get("clientMode") == "cli" +] +if len(matches) != 1: + raise SystemExit(f"expected one paired local CLI device, found {len(matches)}") +approved = { + str(scope).strip() + for scope in (matches[0].get("approvedScopes") or matches[0].get("scopes") or []) + if str(scope).strip() +} +if "operator.pairing" not in approved: + raise SystemExit(f"paired local CLI device lacks operator.pairing: {sorted(approved)}") +PY + +gateway_log=/tmp/gateway.log +before_runs="$(grep -Ec '\[agent\] run [^ ]+ ended with stopReason=' "$gateway_log" 2>/dev/null || true)" +agent_log=/tmp/nemoclaw-6113-gateway-agent.log +session_id="nemoclaw-6113-packaged-$(date +%s)-$$" +if ! openclaw agent --agent main --json --thinking off --session-id "$session_id" \ + -m 'Use the available tools to inspect the current nodes and briefly report their status.' \ + >"$agent_log" 2>&1; then + echo "PACKAGED_GATEWAY_AGENT_FAILED" >&2 + cat "$agent_log" >&2 + exit 22 +fi +if grep -Eiq 'EMBEDDED FALLBACK|gateway connect failed|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded' "$agent_log"; then + echo "PACKAGED_GATEWAY_AGENT_FELL_BACK" >&2 + cat "$agent_log" >&2 + exit 23 +fi +if [ ! -s "$agent_log" ]; then + echo "PACKAGED_GATEWAY_AGENT_EMPTY" >&2 + exit 24 +fi +after_runs="$(grep -Ec '\[agent\] run [^ ]+ ended with stopReason=' "$gateway_log" 2>/dev/null || true)" +if [ "$after_runs" -le "$before_runs" ]; then + echo "PACKAGED_GATEWAY_RUN_NOT_RECORDED before=$before_runs after=$after_runs" >&2 + cat "$agent_log" >&2 + exit 25 +fi +echo "NEMOCLAW_6113_PACKAGED_BOOTSTRAP_OK" +`), + { + artifactName: "phase-2-packaged-initial-cli-pairing", + env: env(), + timeoutMs: 180_000, + }, + ); + expect(result.exitCode, resultText(result)).toBe(0); + expect(result.stdout).toContain("NEMOCLAW_6113_PACKAGED_BOOTSTRAP_OK"); +} + function publicInstallRef(): string { return process.env.NEMOCLAW_PUBLIC_INSTALL_REF || process.env.GITHUB_SHA || "main"; } @@ -86,6 +191,8 @@ test("cloud onboard: public installer creates healthy sandbox with security chec contracts: [ "public curl installer uses GitHub clone path for the requested ref", "sandbox appears healthy after cloud onboarding", + "packaged OpenClaw approves the gated initial CLI pairing request", + "devices list and a real gateway agent run succeed without embedded fallback", "cloud split checks cover inference.local, security leak checks, and Landlock/read-only behavior", "cleanup verifies sandbox removal", ], @@ -127,6 +234,8 @@ test("cloud onboard: public installer creates healthy sandbox with security chec expect(resultText(install)).toContain("Cloning NemoClaw source"); if (ref !== "main") expect(resultText(install)).toContain(`Resolved install ref: ${ref}`); + await assertPackagedInitialCliPairing(sandbox); + const cliProbe = await host.command( "bash", [ From 75a79eeec6a6372926ee9d1f4e674f36ee5f36b0 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 7 Jul 2026 14:24:29 -0700 Subject: [PATCH 13/16] fix(e2e): make pairing wait POSIX portable (#6113) Signed-off-by: Prekshi Vyas --- test/e2e/live/cloud-onboard.test.ts | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/test/e2e/live/cloud-onboard.test.ts b/test/e2e/live/cloud-onboard.test.ts index 42f1d6e705b..728cedbf85c 100644 --- a/test/e2e/live/cloud-onboard.test.ts +++ b/test/e2e/live/cloud-onboard.test.ts @@ -72,13 +72,14 @@ async function assertPackagedInitialCliPairing(sandbox: SandboxClient): Promise< trustedSandboxShellScript(String.raw` set -euo pipefail auto_pair_log=/tmp/auto-pair.log -deadline=$((SECONDS + 30)) +attempt=0 while ! grep -q 'approved initial CLI pairing request=' "$auto_pair_log" 2>/dev/null; do - if [ "$SECONDS" -ge "$deadline" ]; then + if [ "$attempt" -ge 30 ]; then echo "INITIAL_CLI_PAIRING_MARKER_MISSING" >&2 cat "$auto_pair_log" >&2 2>/dev/null || true exit 20 fi + attempt=$((attempt + 1)) sleep 1 done From 08b575c99e0ea2b0e65d7eb490442e13030df1b7 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 7 Jul 2026 14:32:32 -0700 Subject: [PATCH 14/16] test(e2e): force real gated CLI rebootstrap (#6113) Signed-off-by: Prekshi Vyas --- test/e2e/live/cloud-onboard.test.ts | 71 ++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 16 deletions(-) diff --git a/test/e2e/live/cloud-onboard.test.ts b/test/e2e/live/cloud-onboard.test.ts index 728cedbf85c..1a8abeeaf2b 100644 --- a/test/e2e/live/cloud-onboard.test.ts +++ b/test/e2e/live/cloud-onboard.test.ts @@ -72,24 +72,63 @@ async function assertPackagedInitialCliPairing(sandbox: SandboxClient): Promise< trustedSandboxShellScript(String.raw` set -euo pipefail auto_pair_log=/tmp/auto-pair.log +device_id="$(python3 - <<'PY' +import json +from pathlib import Path + +identity = json.loads( + Path("/sandbox/.openclaw/identity/device.json").read_text(encoding="utf-8") +) +device_id = str(identity.get("deviceId") or "").strip() +if not device_id: + raise SystemExit("CLI identity has no deviceId") +print(device_id) +PY +)" +marker_count_before="$(grep -c 'approved initial CLI pairing request=' "$auto_pair_log" 2>/dev/null || true)" +if ! ( + unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN + openclaw devices remove "$device_id" --json +) >/tmp/nemoclaw-6113-device-remove.json 2>/tmp/nemoclaw-6113-device-remove.err; then + echo "CANONICAL_DEVICE_REMOVE_FAILED" >&2 + cat /tmp/nemoclaw-6113-device-remove.err >&2 + exit 20 +fi + +devices_json=/tmp/nemoclaw-6113-devices.json +devices_err=/tmp/nemoclaw-6113-devices.err attempt=0 -while ! grep -q 'approved initial CLI pairing request=' "$auto_pair_log" 2>/dev/null; do +while :; do + ( + unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN + openclaw devices list --json + ) >"$devices_json" 2>"$devices_err" || true + marker_count_after="$(grep -c 'approved initial CLI pairing request=' "$auto_pair_log" 2>/dev/null || true)" + if [ "$marker_count_after" -gt "$marker_count_before" ]; then + break + fi if [ "$attempt" -ge 30 ]; then echo "INITIAL_CLI_PAIRING_MARKER_MISSING" >&2 cat "$auto_pair_log" >&2 2>/dev/null || true - exit 20 + exit 21 fi attempt=$((attempt + 1)) sleep 1 done -devices_json=/tmp/nemoclaw-6113-devices.json -devices_err=/tmp/nemoclaw-6113-devices.err -if ! openclaw devices list --json >"$devices_json" 2>"$devices_err"; then - echo "POST_BOOTSTRAP_DEVICES_LIST_FAILED" >&2 - cat "$devices_err" >&2 - exit 21 -fi +attempt=0 +while ! ( + unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN + openclaw devices list --json +) >"$devices_json" 2>"$devices_err"; do + if [ "$attempt" -ge 10 ]; then + echo "POST_BOOTSTRAP_DEVICES_LIST_FAILED" >&2 + cat "$devices_err" >&2 + exit 22 + fi + attempt=$((attempt + 1)) + sleep 1 +done python3 - "$devices_json" <<'PY' import json @@ -126,8 +165,8 @@ approved = { for scope in (matches[0].get("approvedScopes") or matches[0].get("scopes") or []) if str(scope).strip() } -if "operator.pairing" not in approved: - raise SystemExit(f"paired local CLI device lacks operator.pairing: {sorted(approved)}") +if approved != {"operator.pairing"}: + raise SystemExit(f"initial paired local CLI scopes are not bounded: {sorted(approved)}") PY gateway_log=/tmp/gateway.log @@ -139,29 +178,29 @@ if ! openclaw agent --agent main --json --thinking off --session-id "$session_id >"$agent_log" 2>&1; then echo "PACKAGED_GATEWAY_AGENT_FAILED" >&2 cat "$agent_log" >&2 - exit 22 + exit 23 fi if grep -Eiq 'EMBEDDED FALLBACK|gateway connect failed|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded' "$agent_log"; then echo "PACKAGED_GATEWAY_AGENT_FELL_BACK" >&2 cat "$agent_log" >&2 - exit 23 + exit 24 fi if [ ! -s "$agent_log" ]; then echo "PACKAGED_GATEWAY_AGENT_EMPTY" >&2 - exit 24 + exit 25 fi after_runs="$(grep -Ec '\[agent\] run [^ ]+ ended with stopReason=' "$gateway_log" 2>/dev/null || true)" if [ "$after_runs" -le "$before_runs" ]; then echo "PACKAGED_GATEWAY_RUN_NOT_RECORDED before=$before_runs after=$after_runs" >&2 cat "$agent_log" >&2 - exit 25 + exit 26 fi echo "NEMOCLAW_6113_PACKAGED_BOOTSTRAP_OK" `), { artifactName: "phase-2-packaged-initial-cli-pairing", env: env(), - timeoutMs: 180_000, + timeoutMs: 300_000, }, ); expect(result.exitCode, resultText(result)).toBe(0); From 016cde3f1f02add6d0c2ebe03d50f2507f0499e7 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 7 Jul 2026 14:42:15 -0700 Subject: [PATCH 15/16] test(e2e): clear local auth before gated rebootstrap (#6113) Signed-off-by: Prekshi Vyas --- test/e2e/live/cloud-onboard.test.ts | 17 +++++++++++------ 1 file changed, 11 insertions(+), 6 deletions(-) diff --git a/test/e2e/live/cloud-onboard.test.ts b/test/e2e/live/cloud-onboard.test.ts index 1a8abeeaf2b..bf018c7ab85 100644 --- a/test/e2e/live/cloud-onboard.test.ts +++ b/test/e2e/live/cloud-onboard.test.ts @@ -94,6 +94,11 @@ if ! ( cat /tmp/nemoclaw-6113-device-remove.err >&2 exit 20 fi +rm -f /sandbox/.openclaw/identity/device-auth.json +if [ -e /sandbox/.openclaw/identity/device-auth.json ]; then + echo "LOCAL_DEVICE_AUTH_RESET_FAILED" >&2 + exit 21 +fi devices_json=/tmp/nemoclaw-6113-devices.json devices_err=/tmp/nemoclaw-6113-devices.err @@ -110,7 +115,7 @@ while :; do if [ "$attempt" -ge 30 ]; then echo "INITIAL_CLI_PAIRING_MARKER_MISSING" >&2 cat "$auto_pair_log" >&2 2>/dev/null || true - exit 21 + exit 22 fi attempt=$((attempt + 1)) sleep 1 @@ -124,7 +129,7 @@ while ! ( if [ "$attempt" -ge 10 ]; then echo "POST_BOOTSTRAP_DEVICES_LIST_FAILED" >&2 cat "$devices_err" >&2 - exit 22 + exit 23 fi attempt=$((attempt + 1)) sleep 1 @@ -178,22 +183,22 @@ if ! openclaw agent --agent main --json --thinking off --session-id "$session_id >"$agent_log" 2>&1; then echo "PACKAGED_GATEWAY_AGENT_FAILED" >&2 cat "$agent_log" >&2 - exit 23 + exit 24 fi if grep -Eiq 'EMBEDDED FALLBACK|gateway connect failed|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded' "$agent_log"; then echo "PACKAGED_GATEWAY_AGENT_FELL_BACK" >&2 cat "$agent_log" >&2 - exit 24 + exit 25 fi if [ ! -s "$agent_log" ]; then echo "PACKAGED_GATEWAY_AGENT_EMPTY" >&2 - exit 25 + exit 26 fi after_runs="$(grep -Ec '\[agent\] run [^ ]+ ended with stopReason=' "$gateway_log" 2>/dev/null || true)" if [ "$after_runs" -le "$before_runs" ]; then echo "PACKAGED_GATEWAY_RUN_NOT_RECORDED before=$before_runs after=$after_runs" >&2 cat "$agent_log" >&2 - exit 26 + exit 27 fi echo "NEMOCLAW_6113_PACKAGED_BOOTSTRAP_OK" `), From cda99e2c42a6ad0fdb1fbacb45cc62de0ed73287 Mon Sep 17 00:00:00 2001 From: Prekshi Vyas Date: Tue, 7 Jul 2026 14:53:08 -0700 Subject: [PATCH 16/16] test(e2e): remove nonrepresentative cloud pairing probe (#6113) Signed-off-by: Prekshi Vyas --- test/e2e/live/cloud-onboard.test.ts | 156 +--------------------------- 1 file changed, 1 insertion(+), 155 deletions(-) diff --git a/test/e2e/live/cloud-onboard.test.ts b/test/e2e/live/cloud-onboard.test.ts index bf018c7ab85..f2e84abc23c 100644 --- a/test/e2e/live/cloud-onboard.test.ts +++ b/test/e2e/live/cloud-onboard.test.ts @@ -7,11 +7,7 @@ import path from "node:path"; import { buildAvailabilityProbeEnv } from "../fixtures/availability-env.ts"; import { resultText } from "../fixtures/clients/command.ts"; import { type HostCliClient } from "../fixtures/clients/host.ts"; -import { - type SandboxClient, - trustedSandboxShellScript, - validateSandboxName, -} from "../fixtures/clients/sandbox.ts"; +import { type SandboxClient, validateSandboxName } from "../fixtures/clients/sandbox.ts"; import { expect, test } from "../fixtures/e2e-test.ts"; import { requireHostedInferenceConfig } from "../fixtures/hosted-inference.ts"; import { REPO_ROOT } from "../fixtures/paths.ts"; @@ -66,152 +62,6 @@ async function cleanup( } } -async function assertPackagedInitialCliPairing(sandbox: SandboxClient): Promise { - const result = await sandbox.execShell( - SANDBOX_NAME, - trustedSandboxShellScript(String.raw` -set -euo pipefail -auto_pair_log=/tmp/auto-pair.log -device_id="$(python3 - <<'PY' -import json -from pathlib import Path - -identity = json.loads( - Path("/sandbox/.openclaw/identity/device.json").read_text(encoding="utf-8") -) -device_id = str(identity.get("deviceId") or "").strip() -if not device_id: - raise SystemExit("CLI identity has no deviceId") -print(device_id) -PY -)" -marker_count_before="$(grep -c 'approved initial CLI pairing request=' "$auto_pair_log" 2>/dev/null || true)" -if ! ( - unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN - openclaw devices remove "$device_id" --json -) >/tmp/nemoclaw-6113-device-remove.json 2>/tmp/nemoclaw-6113-device-remove.err; then - echo "CANONICAL_DEVICE_REMOVE_FAILED" >&2 - cat /tmp/nemoclaw-6113-device-remove.err >&2 - exit 20 -fi -rm -f /sandbox/.openclaw/identity/device-auth.json -if [ -e /sandbox/.openclaw/identity/device-auth.json ]; then - echo "LOCAL_DEVICE_AUTH_RESET_FAILED" >&2 - exit 21 -fi - -devices_json=/tmp/nemoclaw-6113-devices.json -devices_err=/tmp/nemoclaw-6113-devices.err -attempt=0 -while :; do - ( - unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN - openclaw devices list --json - ) >"$devices_json" 2>"$devices_err" || true - marker_count_after="$(grep -c 'approved initial CLI pairing request=' "$auto_pair_log" 2>/dev/null || true)" - if [ "$marker_count_after" -gt "$marker_count_before" ]; then - break - fi - if [ "$attempt" -ge 30 ]; then - echo "INITIAL_CLI_PAIRING_MARKER_MISSING" >&2 - cat "$auto_pair_log" >&2 2>/dev/null || true - exit 22 - fi - attempt=$((attempt + 1)) - sleep 1 -done - -attempt=0 -while ! ( - unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN - openclaw devices list --json -) >"$devices_json" 2>"$devices_err"; do - if [ "$attempt" -ge 10 ]; then - echo "POST_BOOTSTRAP_DEVICES_LIST_FAILED" >&2 - cat "$devices_err" >&2 - exit 23 - fi - attempt=$((attempt + 1)) - sleep 1 -done - -python3 - "$devices_json" <<'PY' -import json -import sys -from pathlib import Path - -value = json.loads(Path(sys.argv[1]).read_text(encoding="utf-8")) -pending = value.get("pending") or [] -paired = value.get("paired") or [] -if isinstance(pending, dict): - pending = list(pending.values()) -if isinstance(paired, dict): - paired = list(paired.values()) -if not isinstance(pending, list) or not isinstance(paired, list): - raise SystemExit("devices list must expose pending and paired collections") -if pending: - raise SystemExit(f"initial CLI pairing left pending requests: {len(pending)}") -identity = json.loads( - Path("/sandbox/.openclaw/identity/device.json").read_text(encoding="utf-8") -) -device_id = str(identity.get("deviceId") or "").strip() -matches = [ - device - for device in paired - if isinstance(device, dict) - and str(device.get("deviceId") or "").strip() == device_id - and device.get("clientId") == "cli" - and device.get("clientMode") == "cli" -] -if len(matches) != 1: - raise SystemExit(f"expected one paired local CLI device, found {len(matches)}") -approved = { - str(scope).strip() - for scope in (matches[0].get("approvedScopes") or matches[0].get("scopes") or []) - if str(scope).strip() -} -if approved != {"operator.pairing"}: - raise SystemExit(f"initial paired local CLI scopes are not bounded: {sorted(approved)}") -PY - -gateway_log=/tmp/gateway.log -before_runs="$(grep -Ec '\[agent\] run [^ ]+ ended with stopReason=' "$gateway_log" 2>/dev/null || true)" -agent_log=/tmp/nemoclaw-6113-gateway-agent.log -session_id="nemoclaw-6113-packaged-$(date +%s)-$$" -if ! openclaw agent --agent main --json --thinking off --session-id "$session_id" \ - -m 'Use the available tools to inspect the current nodes and briefly report their status.' \ - >"$agent_log" 2>&1; then - echo "PACKAGED_GATEWAY_AGENT_FAILED" >&2 - cat "$agent_log" >&2 - exit 24 -fi -if grep -Eiq 'EMBEDDED FALLBACK|gateway connect failed|device pairing required|pairing required|fallbackFrom[": ]+gateway|transport[": ]+embedded' "$agent_log"; then - echo "PACKAGED_GATEWAY_AGENT_FELL_BACK" >&2 - cat "$agent_log" >&2 - exit 25 -fi -if [ ! -s "$agent_log" ]; then - echo "PACKAGED_GATEWAY_AGENT_EMPTY" >&2 - exit 26 -fi -after_runs="$(grep -Ec '\[agent\] run [^ ]+ ended with stopReason=' "$gateway_log" 2>/dev/null || true)" -if [ "$after_runs" -le "$before_runs" ]; then - echo "PACKAGED_GATEWAY_RUN_NOT_RECORDED before=$before_runs after=$after_runs" >&2 - cat "$agent_log" >&2 - exit 27 -fi -echo "NEMOCLAW_6113_PACKAGED_BOOTSTRAP_OK" -`), - { - artifactName: "phase-2-packaged-initial-cli-pairing", - env: env(), - timeoutMs: 300_000, - }, - ); - expect(result.exitCode, resultText(result)).toBe(0); - expect(result.stdout).toContain("NEMOCLAW_6113_PACKAGED_BOOTSTRAP_OK"); -} - function publicInstallRef(): string { return process.env.NEMOCLAW_PUBLIC_INSTALL_REF || process.env.GITHUB_SHA || "main"; } @@ -236,8 +86,6 @@ test("cloud onboard: public installer creates healthy sandbox with security chec contracts: [ "public curl installer uses GitHub clone path for the requested ref", "sandbox appears healthy after cloud onboarding", - "packaged OpenClaw approves the gated initial CLI pairing request", - "devices list and a real gateway agent run succeed without embedded fallback", "cloud split checks cover inference.local, security leak checks, and Landlock/read-only behavior", "cleanup verifies sandbox removal", ], @@ -279,8 +127,6 @@ test("cloud onboard: public installer creates healthy sandbox with security chec expect(resultText(install)).toContain("Cloning NemoClaw source"); if (ref !== "main") expect(resultText(install)).toContain(`Resolved install ref: ${ref}`); - await assertPackagedInitialCliPairing(sandbox); - const cliProbe = await host.command( "bash", [