Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,11 @@ FROM ${BASE_IMAGE}
ARG OPENCLAW_VERSION=2026.5.27
ARG OPENCLAW_2026_5_27_INTEGRITY=sha512-2N93zhdAo88KAbHt6T7KvYXf4s7XIkYXBgv1npYpn7e1Y9FvrtgtpsA38my9rtFW+70uXEojRPX5/OqnuDqJPw==

# OpenClaw 2026.5.27 loads some generated source through jiti. Disable its
# filesystem transform cache so source fragments that mention provider marker
# names do not persist under /tmp/jiti inside the sandbox.
ENV JITI_FS_CACHE=false

# Harden: remove unnecessary build tools and network probes from base image (#830)
# Protect runtime tools before autoremove — the GHCR base may predate the
# procps/e2fsprogs/tmux additions, leaving ps/chattr/tmux absent or auto-marked.
Expand Down Expand Up @@ -396,6 +401,7 @@ RUN mkdir -p /sandbox/.nemoclaw/blueprints/0.1.0 \

# Copy startup script and shared sandbox initialisation library
COPY scripts/lib/sandbox-init.sh /usr/local/lib/nemoclaw/sandbox-init.sh
COPY scripts/lib/openclaw_device_approval_policy.py /usr/local/lib/nemoclaw/openclaw_device_approval_policy.py
COPY scripts/nemoclaw-start.sh /usr/local/bin/nemoclaw-start
# Copy NODE_OPTIONS preload modules to a Landlock-accessible path. OpenShell ≥0.0.36
# blocks /opt/nemoclaw-blueprint/ from non-root users, but the entrypoint
Expand All @@ -411,6 +417,7 @@ RUN chmod 755 /usr/local/bin/nemoclaw-start /usr/local/bin/nemoclaw-codex-acp \
/usr/local/lib/nemoclaw/generate-openclaw-config.mts \
/usr/local/lib/nemoclaw/openclaw-build-messaging-plugins.py \
/usr/local/lib/nemoclaw/seed-wechat-accounts.py \
&& chmod 644 /usr/local/lib/nemoclaw/openclaw_device_approval_policy.py \
&& if [ -d /usr/local/lib/nemoclaw/preloads ]; then find /usr/local/lib/nemoclaw/preloads -type f -name '*.js' -exec chmod 644 {} +; fi \
&& chmod 755 /usr/local/share/nemoclaw \
/usr/local/share/nemoclaw/openclaw-plugins \
Expand Down
4 changes: 4 additions & 0 deletions Dockerfile.base
Original file line number Diff line number Diff line change
Expand Up @@ -182,6 +182,10 @@ RUN printf '%s\n' \
ARG OPENCLAW_VERSION=2026.5.27
ARG OPENCLAW_2026_5_27_INTEGRITY=sha512-2N93zhdAo88KAbHt6T7KvYXf4s7XIkYXBgv1npYpn7e1Y9FvrtgtpsA38my9rtFW+70uXEojRPX5/OqnuDqJPw==

# Keep OpenClaw's jiti-generated source cache out of /tmp so provider marker
# names do not persist in runtime snapshots or leak-scan inputs.
ENV JITI_FS_CACHE=false

SHELL ["/bin/bash", "-o", "pipefail", "-c"]

# Install OpenClaw CLI + PyYAML.
Expand Down
75 changes: 75 additions & 0 deletions scripts/lib/openclaw_device_approval_policy.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved.
# SPDX-License-Identifier: Apache-2.0

"""Shared OpenClaw device approval policy for NemoClaw sandbox helpers."""

import os


ALLOWED_CLIENTS = {"openclaw-control-ui"}
ALLOWED_MODES = {"webchat", "cli"}
ALLOWED_SCOPES = {"operator.pairing", "operator.read", "operator.write"}

GATEWAY_APPROVAL_ENV_KEYS = (
"OPENCLAW_GATEWAY_URL",
"OPENCLAW_GATEWAY_PORT",
"OPENCLAW_GATEWAY_TOKEN",
)


def requested_scopes(device):
if "scopes" in device:
scopes = device.get("scopes")
elif "requestedScopes" in device:
scopes = device.get("requestedScopes")
else:
return set()
if not isinstance(scopes, list):
return None
return {str(scope).strip() for scope in scopes if str(scope or "").strip()}


def approval_request_decision(device):
client_id = str(device.get("clientId", ""))
client_mode = str(device.get("clientMode", ""))
if client_id not in ALLOWED_CLIENTS and client_mode not in ALLOWED_MODES:
return {
"allowed": False,
"reason": "unknown-client",
"client_id": client_id,
"client_mode": client_mode,
"scopes": set(),
}

scopes = requested_scopes(device)
if scopes is None:
return {
"allowed": False,
"reason": "malformed-scopes",
"client_id": client_id,
"client_mode": client_mode,
"scopes": set(),
}
if scopes and not scopes.issubset(ALLOWED_SCOPES):
return {
"allowed": False,
"reason": "disallowed-scopes",
"client_id": client_id,
"client_mode": client_mode,
"scopes": scopes,
}

return {
"allowed": True,
"reason": "allowlisted",
"client_id": client_id,
"client_mode": client_mode,
"scopes": scopes,
}


def gateway_approval_env(source_env=None):
env = dict(os.environ if source_env is None else source_env)
for key in GATEWAY_APPROVAL_ENV_KEYS:
env.pop(key, None)
return env
117 changes: 106 additions & 11 deletions scripts/nemoclaw-start.sh
Original file line number Diff line number Diff line change
Expand Up @@ -1727,8 +1727,14 @@ start_auto_pair() {
import json
import os
import subprocess
import sys
import time

APPROVAL_POLICY_DIR = os.environ.get('NEMOCLAW_APPROVAL_POLICY_DIR', '/usr/local/lib/nemoclaw')
if APPROVAL_POLICY_DIR:
sys.path.insert(0, APPROVAL_POLICY_DIR)
from openclaw_device_approval_policy import approval_request_decision, gateway_approval_env

OPENCLAW = os.environ.get('OPENCLAW_BIN', 'openclaw')


Expand Down Expand Up @@ -1760,8 +1766,7 @@ HANDLED = set() # Track rejected/approved requestIds to avoid reprocessing
# (the gateway stores connectParams.client.id verbatim). This allowlist
# is defense-in-depth, not a trust boundary. PR #690 adds one-shot exit,
# timeout reduction, and token cleanup for a more comprehensive fix.
ALLOWED_CLIENTS = {'openclaw-control-ui'}
ALLOWED_MODES = {'webchat', 'cli'}
# The approval_request_decision helper is shared with connect-time approvals.

RUN_TIMEOUT_SECS = _env_seconds('NEMOCLAW_AUTO_PAIR_RUN_TIMEOUT_SECS', 10)

Expand All @@ -1781,10 +1786,7 @@ def run(*args, strip_gateway_env=False):
# the fast→slow transition and the 8h deadline check.
env = None
if strip_gateway_env:
env = os.environ.copy()
env.pop('OPENCLAW_GATEWAY_URL', None)
env.pop('OPENCLAW_GATEWAY_PORT', None)
env.pop('OPENCLAW_GATEWAY_TOKEN', None)
env = gateway_approval_env(os.environ)
try:
proc = subprocess.run(
args, capture_output=True, text=True, timeout=RUN_TIMEOUT_SECS, env=env,
Expand Down Expand Up @@ -1830,12 +1832,22 @@ while time.time() < DEADLINE:
request_id = device.get('requestId')
if not request_id or request_id in HANDLED:
continue
client_id = device.get('clientId', '')
client_mode = device.get('clientMode', '')
if client_id not in ALLOWED_CLIENTS and client_mode not in ALLOWED_MODES:
decision = approval_request_decision(device)
client_id = decision['client_id']
client_mode = decision['client_mode']
if decision['reason'] == 'unknown-client':
HANDLED.add(request_id)
print(f'[auto-pair] rejected unknown client={client_id} mode={client_mode}')
continue
if decision['reason'] == 'malformed-scopes':
HANDLED.add(request_id)
print(f'[auto-pair] rejected malformed scopes client={client_id} mode={client_mode}')
continue
if decision['reason'] == 'disallowed-scopes':
HANDLED.add(request_id)
scopes = decision['scopes']
print(f'[auto-pair] rejected disallowed scopes={sorted(scopes)} client={client_id} mode={client_mode}')
continue
arc, aout, aerr = run(
OPENCLAW, 'devices', 'approve', request_id, '--json', strip_gateway_env=True,
)
Expand Down Expand Up @@ -2081,6 +2093,7 @@ export NO_PROXY="$_NO_PROXY_VAL"
export http_proxy="$_PROXY_URL"
export https_proxy="$_PROXY_URL"
export no_proxy="$_NO_PROXY_VAL"
export JITI_FS_CACHE="false"
PROXYEOF
local _openclaw_env_name _openclaw_env_value _escaped_openclaw_env_value
for _openclaw_env_name in OPENCLAW_HOME OPENCLAW_STATE_DIR OPENCLAW_CONFIG_PATH OPENCLAW_OAUTH_DIR OPENCLAW_WORKSPACE_DIR; do
Expand Down Expand Up @@ -2110,8 +2123,90 @@ openclaw() {
# the approval command itself. Approval calls temporarily drop the gateway
# URL/port/token; other commands keep the full gateway environment.
if [ "${1:-}" = "devices" ] && [ "${2:-}" = "approve" ]; then
( unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN; command openclaw "$@" )
return $?
_nemoclaw_approve_request_id="${3:-}"
_nemoclaw_approve_state_dir="${OPENCLAW_STATE_DIR:-/sandbox/.openclaw}"
_nemoclaw_approve_before=""
if [ -n "$_nemoclaw_approve_request_id" ] && command -v python3 >/dev/null 2>&1; then
_nemoclaw_approve_before="$(NEMOCLAW_APPROVE_REQUEST_ID="$_nemoclaw_approve_request_id" NEMOCLAW_APPROVE_STATE_DIR="$_nemoclaw_approve_state_dir" python3 - <<'PYAPPROVEBEFORE' 2>/dev/null || true
import json
import os
from pathlib import Path

root = Path(os.environ.get("NEMOCLAW_APPROVE_STATE_DIR") or "/sandbox/.openclaw") / "devices"
request_id = os.environ.get("NEMOCLAW_APPROVE_REQUEST_ID") or ""
try:
pending = json.loads((root / "pending.json").read_text(encoding="utf-8"))
except Exception:
pending = {}
if not isinstance(pending, dict):
pending = {}
request = next((item for item in pending.values() if isinstance(item, dict) and item.get("requestId") == request_id), None)
if request:
print(json.dumps({
"requestId": request_id,
"deviceId": request.get("deviceId"),
"scopes": request.get("scopes") or request.get("requestedScopes") or [],
}, sort_keys=True))
PYAPPROVEBEFORE
)"
fi
_nemoclaw_approve_errexit=0
case $- in *e*) _nemoclaw_approve_errexit=1 ;; esac
set +e
_nemoclaw_approve_output="$(unset OPENCLAW_GATEWAY_URL OPENCLAW_GATEWAY_PORT OPENCLAW_GATEWAY_TOKEN; command openclaw "$@" 2>&1)"
_nemoclaw_approve_rc=$?
if [ "$_nemoclaw_approve_errexit" = "1" ]; then set -e; else set +e; fi
if [ "$_nemoclaw_approve_rc" -eq 0 ]; then
printf '%s\n' "$_nemoclaw_approve_output"
return 0
fi
if [ -n "$_nemoclaw_approve_request_id" ] && [ -n "$_nemoclaw_approve_before" ] && command -v python3 >/dev/null 2>&1; then
if NEMOCLAW_APPROVE_REQUEST_ID="$_nemoclaw_approve_request_id" NEMOCLAW_APPROVE_STATE_DIR="$_nemoclaw_approve_state_dir" NEMOCLAW_APPROVE_BEFORE="$_nemoclaw_approve_before" python3 - <<'PYAPPROVEAFTER'; then
import json
import os
from pathlib import Path

request_id = os.environ.get("NEMOCLAW_APPROVE_REQUEST_ID") or ""
root = Path(os.environ.get("NEMOCLAW_APPROVE_STATE_DIR") or "/sandbox/.openclaw") / "devices"
try:
before = json.loads(os.environ.get("NEMOCLAW_APPROVE_BEFORE") or "{}")
except Exception:
before = {}

def load(name):
try:
value = json.loads((root / name).read_text(encoding="utf-8"))
except Exception:
return {}
return value if isinstance(value, dict) else {}

def norm(value):
return str(value or "").strip()

def scopes(entry):
return {norm(scope) for scope in (entry.get("approvedScopes") or entry.get("scopes") or []) if norm(scope)}

requested = {norm(scope) for scope in (before.get("scopes") or []) if norm(scope)}
device_id = norm(before.get("deviceId"))
pending = load("pending.json")
paired = load("paired.json")
still_pending = any(isinstance(item, dict) and item.get("requestId") == request_id for item in pending.values())
paired_entry = paired.get(device_id) if device_id else None
if request_id and requested and not still_pending and isinstance(paired_entry, dict) and requested.issubset(scopes(paired_entry)):
print(json.dumps({
"requestId": request_id,
"deviceId": device_id,
"approvedScopes": sorted(requested),
"compatibility": "openclaw-approve-applied-after-nonzero",
}, sort_keys=True))
raise SystemExit(0)
raise SystemExit(1)
PYAPPROVEAFTER
return 0
fi
fi
printf '%s\n' "$_nemoclaw_approve_output"
return "$_nemoclaw_approve_rc"
fi
case "$1" in
configure)
Expand Down
36 changes: 29 additions & 7 deletions src/lib/actions/sandbox/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@
// SPDX-License-Identifier: Apache-2.0

import { spawnSync } from "node:child_process";
import { readFileSync } from "node:fs";
import os from "node:os";
import path from "node:path";
import { resolveOpenshell } from "../../adapters/openshell/resolve";
import {
captureOpenshell,
Expand Down Expand Up @@ -681,22 +683,44 @@ function ensureSandboxInferenceRouteOrExit(
// mid-loop kill cannot strand allowlisted requests within a normal batch.
const CONNECT_AUTO_PAIR_MAX_APPROVALS = 8;
const CONNECT_AUTO_PAIR_TIMEOUT_MS = 12_000;
const CONNECT_AUTO_PAIR_POLICY_PATH = path.join(
ROOT,
"scripts",
"lib",
"openclaw_device_approval_policy.py",
);

function readConnectAutoPairPolicyModule(): string | null {
try {
return readFileSync(CONNECT_AUTO_PAIR_POLICY_PATH, "utf-8");
} catch {
return null;
}
}

function runConnectAutoPairApprovalPass(sandboxName: string): void {
const approvalPolicyModule = readConnectAutoPairPolicyModule();
if (!approvalPolicyModule) {
return;
}
const script = `
PROXY_ENV=/tmp/nemoclaw-proxy-env.sh
[ -r "$PROXY_ENV" ] && . "$PROXY_ENV"
command -v openclaw >/dev/null 2>&1 || exit 0
command -v python3 >/dev/null 2>&1 || exit 0
cat > /tmp/openclaw_device_approval_policy.py <<'NEMOCLAW_APPROVAL_POLICY_PY'
${approvalPolicyModule}
NEMOCLAW_APPROVAL_POLICY_PY
OPENCLAW_BIN="$(command -v openclaw)" python3 - <<'PYAPPROVE'
import json
import os
import subprocess
import sys

sys.path.insert(0, '/tmp')
from openclaw_device_approval_policy import approval_request_decision, gateway_approval_env

OPENCLAW = os.environ.get('OPENCLAW_BIN', 'openclaw')
ALLOWED_CLIENTS = {'openclaw-control-ui'}
ALLOWED_MODES = {'webchat', 'cli'}
MAX_APPROVALS = ${CONNECT_AUTO_PAIR_MAX_APPROVALS}

try:
Expand Down Expand Up @@ -728,13 +752,11 @@ for device in pending:
request_id = device.get('requestId')
if not request_id or request_id in seen_request_ids:
continue
client_id = device.get('clientId', '')
client_mode = device.get('clientMode', '')
if client_id not in ALLOWED_CLIENTS and client_mode not in ALLOWED_MODES:
decision = approval_request_decision(device)
if not decision['allowed']:
continue
seen_request_ids.add(request_id)
approve_env = os.environ.copy()
approve_env.pop('OPENCLAW_GATEWAY_URL', None)
approve_env = gateway_approval_env(os.environ)
attempted_count += 1
try:
approve_proc = subprocess.run(
Expand Down
4 changes: 4 additions & 0 deletions src/lib/sandbox/build-context.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,10 @@ function stageOptimizedSandboxBuildContext(
path.join(rootDir, "scripts", "lib", "sandbox-init.sh"),
path.join(stagedScriptsDir, "lib", "sandbox-init.sh"),
);
fs.copyFileSync(
path.join(rootDir, "scripts", "lib", "openclaw_device_approval_policy.py"),
path.join(stagedScriptsDir, "lib", "openclaw_device_approval_policy.py"),
);
// OpenClaw config generator extracted in #2449 (fixed in #2565)
fs.copyFileSync(
path.join(rootDir, "scripts", "generate-openclaw-config.mts"),
Expand Down
Loading
Loading